diff options
76 files changed, 6370 insertions, 3361 deletions
diff --git a/Makefile.builds.in b/Makefile.builds.in index 296e5a974..eb27bcac8 100644 --- a/Makefile.builds.in +++ b/Makefile.builds.in @@ -6,14 +6,8 @@ # # Its main purposes are to: # 1. build the current build profile -# 2. install into "builds/$(CURRENT_BUILD)/$(prefix)" -# 3. set up "builds/$(CURRENT_BUILD)/{bin,lib}" symlinks -# 4. install into "builds/$(prefix)" -# 5. set up "builds/bin" and "builds/lib" -# -# Steps 2 and 4 require libtool-relinking for dynamically-linked -# executables and libraries, since build/bin is not the final -# installation path. +# 2. set up builds/$(CURRENT_BUILD)/{bin,lib} symlinks +# 3. set up builds/bin and builds/lib symlinks # Include the "current" build profile. include current @@ -40,12 +34,6 @@ LIBTOOL = $(CURRENT_BUILD)/libtool # Are we building the libcvc4compat library ? CVC4_BUILD_LIBCOMPAT = @CVC4_BUILD_LIBCOMPAT@ -# Are we building static/dynamic libraries/binaries? One or the other can be -# on, or both. -BUILDING_STATIC = @BUILDING_STATIC@ -BUILDING_SHARED = @BUILDING_SHARED@ -STATIC_BINARY = @STATIC_BINARY@ - # @ AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) @@ -61,21 +49,6 @@ AM_V_mkdir = $(am__v_mkdir_$(V)) am__v_mkdir_ = $(am__v_mkdir_$(AM_DEFAULT_VERBOSITY)) am__v_mkdir_0 = @$(am__v_mkdir_noat_0) am__v_mkdir_1 = $(am__v_mkdir_noat_1) -# libtool --mode=install $(install_sh) -AM_V_ltinstall = $(am__v_ltinstall_$(V)) -am__v_ltinstall_ = $(am__v_ltinstall_$(AM_DEFAULT_VERBOSITY)) -am__v_ltinstall_0 = @$(SHELL) -c 'echo " LTINS $$1"; $(LIBTOOL) --silent --mode=install $(install_sh) "$$@"' bash -am__v_ltinstall_1 = $(LIBTOOL) --mode=install $(install_sh) -# install_sh (never prefix with @) -AM_V_install_sh_noat = $(am__v_install_sh_noat_$(V)) -am__v_install_sh_noat_ = $(am__v_install_sh_noat_$(AM_DEFAULT_VERBOSITY)) -am__v_install_sh_noat_0 = $(SHELL) -c 'echo " INSTL $$1"; $(install_sh) "$$@"' bash -am__v_install_sh_noat_1 = $(install_sh) -# relinking -AM_V_relink = $(am__v_relink_$(V)) -am__v_relink_ = $(am__v_relink_$(AM_DEFAULT_VERBOSITY)) -am__v_relink_0 = echo " RELNK" -am__v_relink_1 = : # all the binaries that might need to be installed # (it's not a fatal error for one/some don't exist in a given build @@ -87,108 +60,43 @@ _default_build_: all all: # build the current build profile $(AM_V_at)(cd $(CURRENT_BUILD) && $(MAKE) $@) -# set up builds/$(CURRENT_BUILD)/...prefix.../bin -# and builds/$(CURRENT_BUILD)/...prefix.../lib - $(AM_V_mkdir) "$(CURRENT_BUILD)$(bindir)" - $(AM_V_mkdir) "$(CURRENT_BUILD)$(libdir)" -# install libcvc4 - $(AM_V_ltinstall) $(CURRENT_BUILD)/src/libcvc4.la \ - "$(abs_builddir)$(libdir)" -# install libcvc4parser - $(AM_V_ltinstall) $(CURRENT_BUILD)/src/parser/libcvc4parser.la \ - "$(abs_builddir)$(libdir)" +# set up builds/$(CURRENT_BUILD)/{bin,lib} + $(AM_V_mkdir) $(CURRENT_BUILD)/bin + $(AM_V_mkdir) $(CURRENT_BUILD)/lib +# symlink libcvc4, libcvc4parser + cd $(CURRENT_BUILD)/lib && \ + ln -sf ../src/libcvc4.* \ + ../src/parser/libcvc4parser.* \ + . + -cd $(CURRENT_BUILD)/lib && \ + test -d ../src/.libs && \ + ln -sf ../src/.libs/libcvc4.* \ + . + -cd $(CURRENT_BUILD)/lib && \ + test -d ../src/parser/.libs && \ + ln -sf ../src/parser/.libs/libcvc4parser.* \ + . ifeq ($(CVC4_BUILD_LIBCOMPAT),yes) -# install libcvc4compat - $(CURRENT_BUILD)/libtool --mode=install $(install_sh) \ - $(CURRENT_BUILD)/src/compat/libcvc4compat.la \ - "$(abs_builddir)$(libdir)" +# symlink libcvc4compat + cd $(CURRENT_BUILD)/lib && \ + ln -sf ../src/compat/libcvc4compat.* \ + . + -cd $(CURRENT_BUILD)/lib && \ + test -d ../src/compat/.libs && \ + ln -sf ../src/compat/.libs/libcvc4compat.* \ + . endif -ifeq ($(BUILDING_SHARED)$(STATIC_BINARY),10) -# if we're building shared libs and the binary is not static, relink -# the handling with empty $relink_command is a hack for Mac OS - $(AM_V_at)thelibdir="$(abs_builddir)$(libdir)"; \ - progdir="$(abs_builddir)$(bindir)"; for file in $(CVC4_BINARIES); do \ - if test -r $(CURRENT_BUILD)/src/main/$$file; then \ - eval `grep '^relink_command=' $(CURRENT_BUILD)/src/main/$$file | sed 's:-Wl,-rpath:-Wl,-rpath -Wl,\\\\$$thelibdir -Wl,-rpath:'`; \ - if test -z "$$relink_command"; then \ - $(AM_V_mkdir_noat) "$(CURRENT_BUILD)$(bindir)/.libs"; \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/.libs/$$file \ - "$(abs_builddir)$(bindir)/.libs"; \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/$$file \ - "$(abs_builddir)$(bindir)"; \ - else \ - $(AM_V_relink) "$$file"; eval "(cd $(CURRENT_BUILD)/src/main && $$relink_command)"; \ - fi; \ - else \ - rm -f "$(abs_builddir)$(bindir)/$$file"; \ - fi; \ - done -else -# if we're building static libs only, just install the driver binary directly - $(AM_V_at)for file in $(CVC4_BINARIES); do \ - if test -r $(CURRENT_BUILD)/src/main/$$file; then \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/$$file \ - "$(abs_builddir)$(bindir)"; \ - else \ - rm -f "$(abs_builddir)$(bindir)/$$file"; \ - fi; \ +# symlink the binaries + cd $(CURRENT_BUILD)/bin && \ + for binary in $(CVC4_BINARIES); do \ + ln -sf ../src/main/$$binary \ + . ; \ done -endif -# set up builds/$(CURRENT_BUILD)/bin and builds/$(CURRENT_BUILD)/lib - rm -f $(CURRENT_BUILD)/lib; ln -sf "$(abs_builddir)$(libdir)" $(CURRENT_BUILD)/lib - rm -f $(CURRENT_BUILD)/bin; ln -sf "$(abs_builddir)$(bindir)" $(CURRENT_BUILD)/bin -# set up builds/...prefix.../bin and builds/...prefix.../lib - $(AM_V_mkdir) ".$(bindir)" - $(AM_V_mkdir) ".$(libdir)" -# install libcvc4 - $(AM_V_ltinstall) $(CURRENT_BUILD)/src/libcvc4.la "`pwd`$(libdir)" -# install libcvc4parser - $(AM_V_ltinstall) $(CURRENT_BUILD)/src/parser/libcvc4parser.la "`pwd`$(libdir)" -ifeq ($(CVC4_BUILD_LIBCOMPAT),yes) -# install libcvc4compat - $(CURRENT_BUILD)/libtool --mode=install $(install_sh) $(CURRENT_BUILD)/src/compat/libcvc4compat.la "`pwd`$(libdir)" -endif -ifeq ($(BUILDING_SHARED)$(STATIC_BINARY),10) -# if we're building shared libs and the binary is not static, relink -# the handling with empty $relink_command is a hack for Mac OS - $(AM_V_at)thelibdir="`pwd`$(libdir)"; progdir="`pwd`$(bindir)"; for file in $(CVC4_BINARIES); do \ - if test -r $(CURRENT_BUILD)/src/main/$$file; then \ - eval `grep '^relink_command=' $(CURRENT_BUILD)/src/main/$$file | sed 's:-Wl,-rpath:-Wl,-rpath -Wl,\\\\$$thelibdir -Wl,-rpath:'`; \ - if test -z "$$relink_command"; then \ - $(AM_V_mkdir_noat) ".$(bindir)/.libs"; \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/.libs/$$file \ - "`pwd`$(bindir)/.libs"; \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/$$file \ - "`pwd`$(bindir)"; \ - else \ - $(AM_V_relink) "$$file"; eval "(cd $(CURRENT_BUILD)/src/main && $$relink_command)"; \ - fi; \ - else \ - rm -f "`pwd`$(bindir)/$$file"; \ - fi; \ - done -else -# if we're building static libs only, just install the driver binary directly - $(AM_V_at)for file in $(CVC4_BINARIES); do \ - if test -r $(CURRENT_BUILD)/src/main/$$file; then \ - $(AM_V_install_sh_noat) \ - $(CURRENT_BUILD)/src/main/$$file \ - "`pwd`$(bindir)"; \ - else \ - rm -f "`pwd`$(bindir)/$$file"; \ - fi; \ - done -endif -# set up builds/bin and builds/lib - rm -f lib; ln -sf ".$(libdir)" lib - rm -f bin; ln -sf ".$(bindir)" bin - rm -f doc; ln -sf "$(CURRENT_BUILD)/doc" doc - rm -f examples; ln -sf "$(CURRENT_BUILD)/examples" examples +# set up builds/doc and builds/examples + rm -f bin; ln -sf $(CURRENT_BUILD)/bin bin + rm -f lib; ln -sf $(CURRENT_BUILD)/lib lib + rm -f doc; ln -sf $(CURRENT_BUILD)/doc doc + rm -f examples; ln -sf $(CURRENT_BUILD)/examples examples # The descent into "src" with target "check" is to build check # prerequisites (e.g. CHECK_PROGRAMS, CHECK_LTLIBRARIES, ...). diff --git a/configure.ac b/configure.ac index 1ae4dbe21..d83293079 100644 --- a/configure.ac +++ b/configure.ac @@ -2,8 +2,8 @@ # Process this file with autoconf to produce a configure script. m4_define(_CVC4_MAJOR, 1) dnl version (major) -m4_define(_CVC4_MINOR, 4) dnl version (minor) -m4_define(_CVC4_RELEASE, 1) dnl version (alpha) +m4_define(_CVC4_MINOR, 5) dnl version (minor) +m4_define(_CVC4_RELEASE, 0) dnl version (alpha) m4_define(_CVC4_EXTRAVERSION, [-prerelease]) dnl version (extra) m4_define(_CVC4_RELEASE_STRING, _CVC4_MAJOR[.]_CVC4_MINOR[]m4_if(_CVC4_RELEASE,[0],,[.]_CVC4_RELEASE)_CVC4_EXTRAVERSION) dnl version string @@ -126,6 +126,10 @@ if test -n "${enable_optimized+set}"; then btargs="$btargs nooptimized" fi fi +# --enable-staticbinary is an alias for --enable-static-binary +if test -n "${enable_staticbinary+set}"; then + enable_static_binary="$enable_staticbinary" +fi if test -n "${enable_static_binary+set}"; then if test "$enable_static_binary" = yes; then btargs="$btargs staticbinary" diff --git a/doc/SmtEngine.3cvc_template.in b/doc/SmtEngine.3cvc_template.in index 3a876fefc..d741fd33f 100644 --- a/doc/SmtEngine.3cvc_template.in +++ b/doc/SmtEngine.3cvc_template.in @@ -19,6 +19,8 @@ and .I SmtEngine::getOption() use the following option keys. +.ad l + .RS .TP 10 .I "COMMON OPTIONS" @@ -28,6 +30,8 @@ ${remaining_manpage_smt_documentation} .PD .RE +.ad b + .SH VERSION This manual page refers to .B CVC4 diff --git a/doc/options.3cvc_template.in b/doc/options.3cvc_template.in index a0d6c1640..f92faf47f 100644 --- a/doc/options.3cvc_template.in +++ b/doc/options.3cvc_template.in @@ -7,6 +7,8 @@ options \- the options infrastructure .SH AVAILABLE INTERNAL OPTIONS +.ad l + .RS .TP 10 .I "COMMON OPTIONS" @@ -16,6 +18,8 @@ ${remaining_manpage_internals_documentation} .PD .RE +.ad b + .SH VERSION This manual page refers to .B CVC4 diff --git a/library_versions b/library_versions index 13bdad78e..a487695d7 100644 --- a/library_versions +++ b/library_versions @@ -58,3 +58,4 @@ 1\.4-prerelease libcvc4:2:0:0 libcvc4parser:2:0:0 libcvc4compat:2:0:0 libcvc4bindings:2:0:0 1\.4 libcvc4:3:0:0 libcvc4parser:3:0:0 libcvc4compat:3:0:0 libcvc4bindings:3:0:0 1\.4\.1-prerelease libcvc4:3:0:0 libcvc4parser:3:0:0 libcvc4compat:3:0:0 libcvc4bindings:3:0:0 +1\.5-prerelease libcvc4:3:0:0 libcvc4parser:3:0:0 libcvc4compat:3:0:0 libcvc4bindings:3:0:0 diff --git a/proofs/signatures/ex_bv.plf b/proofs/signatures/ex_bv.plf new file mode 100755 index 000000000..02cadaeab --- /dev/null +++ b/proofs/signatures/ex_bv.plf @@ -0,0 +1,57 @@ +; a = b ^ a = 00000 ^ b = 11111 is UNSAT
+
+(check
+(% a var_bv
+(% b var_bv
+(% f1 (th_holds (= BitVec (a_var_bv a) (a_var_bv b)))
+(% f2 (th_holds (= BitVec (a_var_bv a) (a_bv (bvc b0 (bvc b0 (bvc b0 (bvc b0 (bvc b0 bvn))))))))
+(% f3 (th_holds (= BitVec (a_var_bv b) (a_bv (bvc b1 (bvc b1 (bvc b1 (bvc b1 (bvc b1 bvn))))))))
+(: (holds cln)
+
+(decl_bv_atom_var 5 a (\ ba1
+(decl_bv_atom_var 5 b (\ ba2
+(decl_bv_atom_const _ (bvc b0 (bvc b0 (bvc b0 (bvc b0 (bvc b0 bvn))))) (\ c (\ ba3
+(decl_bv_atom_const _ (bvc b1 (bvc b1 (bvc b1 (bvc b1 (bvc b1 bvn))))) (\ d (\ ba4
+
+(decl_atom (bblast a 4) (\ v1 (\ a1
+(decl_atom (bblast b 4) (\ v2 (\ a2
+
+; bitblasting terms
+(th_let_pf _ (bv_bbl_var _ _ _ ba1) (\ bt1
+(th_let_pf _ (bv_bbl_var _ _ _ ba2) (\ bt2
+(th_let_pf _ (bv_bbl_const _ _ _ _ ba3) (\ bt3
+(th_let_pf _ (bv_bbl_const _ _ _ _ ba4) (\ bt4
+
+; bitblasting formulas
+(th_let_pf _ (bv_bbl_eq _ _ _ _ _ bt1 bt2) (\ bf1
+(th_let_pf _ (bv_bbl_eq _ _ _ _ _ bt1 bt3) (\ bf2
+(th_let_pf _ (bv_bbl_eq _ _ _ _ _ bt2 bt4) (\ bf3
+
+; CNFication
+; a.4 V ~b.4
+(satlem _ _
+(asf _ _ _ a1 (\ l1
+(ast _ _ _ a2 (\ l2
+(clausify_false
+ (contra _ (impl_elim _ _ l2 (iff_elim_2 _ _ (and_elim_1 _ _ (impl_elim _ _ f1 bf1)))) l1) ; notice at the intermost we impl_elim, which converts from atom to bit-blasting representation
+))))) (\ C2
+
+; ~a.4
+(satlem _ _
+(ast _ _ _ a1 (\ l1
+(clausify_false
+ (impl_elim _ _ l1 (iff_elim_1 _ _ (and_elim_1 _ _ (impl_elim _ _ f2 bf2))))
+))) (\ C3
+
+; b.4
+(satlem _ _
+(asf _ _ _ a2 (\ l2
+(clausify_false
+ (contra _ (impl_elim _ _ truth (iff_elim_2 _ _ (and_elim_1 _ _ (impl_elim _ _ f3 bf3)))) l2)
+))) (\ C6
+
+
+(satlem_simplify _ _ _
+(R _ _ (R _ _ C6 C2 v2) C3 v1) (\ x x))
+
+)))))))))))))))))))))))))))))))))))))))))))
\ No newline at end of file diff --git a/proofs/signatures/smt.plf b/proofs/signatures/smt.plf index bbee2d49b..942e17df0 100755 --- a/proofs/signatures/smt.plf +++ b/proofs/signatures/smt.plf @@ -104,6 +104,9 @@ (! r2 (th_holds (not f)) (th_holds false))))) +; truth +(declare truth (th_holds true)) + ;; not not (declare not_not_intro diff --git a/proofs/signatures/th_bv.plf b/proofs/signatures/th_bv.plf new file mode 100755 index 000000000..3fb9d1356 --- /dev/null +++ b/proofs/signatures/th_bv.plf @@ -0,0 +1,145 @@ +; "bitvec" is a term of type "sort"
+(declare BitVec sort)
+
+; bit type
+(declare bit type)
+(declare b0 bit)
+(declare b1 bit)
+
+; bit vector type
+(declare bv type)
+(declare bvn bv)
+(declare bvc (! b bit (! v bv bv)))
+; a bv constant term
+(declare a_bv (! v bv (term BitVec)))
+
+; calculate the length of a bitvector
+(program bv_len ((v bv)) mpz
+ (match v
+ (bvn 0)
+ ((bvc b v') (mp_add (bv_len v') 1))))
+
+; a bv variable
+(declare var_bv type)
+; a bv variable term
+(declare a_var_bv (! v var_bv (term BitVec)))
+
+
+; bit vector operators
+(define bvoper (! x (term BitVec)
+ (! y (term BitVec)
+ (term BitVec))))
+(declare bvand bvoper)
+(declare bvadd bvoper)
+;....
+
+; all bit-vector terms are mapped with "bv_atom" to:
+; - a simply-typed term of type "var_bv", which is necessary for bit-blasting
+; - a integer size
+(declare bv_atom (! x (term BitVec) (! y var_bv (! n mpz type))))
+
+(declare decl_bv_atom_var (! n mpz ; must be specified
+ (! x var_bv
+ (! p (! u (bv_atom (a_var_bv x) x n)
+ (holds cln))
+ (holds cln)))))
+
+(declare decl_bv_atom_const (! n mpz
+ (! v bv
+ (! s (^ (bv_len v) n)
+ (! p (! w var_bv
+ (! u (bv_atom (a_bv v) w n)
+ (holds cln)))
+ (holds cln))))))
+
+
+; other terms here?
+
+
+; bit blasted terms
+(declare bblt type)
+(declare bbltn bblt)
+(declare bbltc (! f formula (! v bblt bblt)))
+
+; (bblast_term x y) means term x corresponds to bit level interpretation y
+(declare bblast_term (! x (term BitVec) (! y bblt formula)))
+
+; a predicate to represent the n^th bit of a bitvector term
+(declare bblast (! x var_bv (! n mpz formula)))
+
+
+; bit blast constant
+(program bblast_const ((v bv) (n mpz)) bblt
+ (mp_ifneg n (match v (bvn bbltn)
+ (default (fail bblt)))
+ (match v ((bvc b v') (bbltc (match b (b0 false) (b1 true)) (bblast_const v' (mp_add n (~ 1)))))
+ (default (fail bblt)))))
+
+(declare bv_bbl_const (! n mpz
+ (! v bv
+ (! x var_bv
+ (! f bblt
+ (! u (bv_atom (a_bv v) x n)
+ (! c (^ (bblast_const v (mp_add n (~ 1))) f)
+ (th_holds (bblast_term (a_bv v) f)))))))))
+
+; bit blast variable
+(program bblast_var ((x var_bv) (n mpz)) bblt
+ (mp_ifneg n bbltn
+ (bbltc (bblast x n) (bblast_var x (mp_add n (~ 1))))))
+
+(declare bv_bbl_var (! n mpz
+ (! x var_bv
+ (! f bblt
+ (! u (bv_atom (a_var_bv x) x n)
+ (! c (^ (bblast_var x (mp_add n (~ 1))) f)
+ (th_holds (bblast_term (a_var_bv x) f))))))))
+
+; bit blast x = y
+; for x,y of size n, it will return a conjuction (x.{n-1} = y.{n-1} ^ ( ... ^ (x.0 = y.0 ^ true)))
+(program bblast_eq ((x bblt) (y bblt)) formula
+ (match x
+ (bbltn (match y (bbltn true) (default (fail formula))))
+ ((bbltc fx x') (match y
+ (bbltn (fail formula))
+ ((bbltc fy y') (and (iff fx fy) (bblast_eq x' y')))))))
+
+(declare bv_bbl_eq (! x (term BitVec)
+ (! y (term BitVec)
+ (! fx bblt
+ (! fy bblt
+ (! f formula
+ (! ux (th_holds (bblast_term x fx))
+ (! uy (th_holds (bblast_term y fy))
+ (! c (^ (bblast_eq fx fy) f)
+ (th_holds (impl (= BitVec x y) f)))))))))))
+
+
+; rewrite rule :
+; x + y = y + x
+(declare bvadd_symm (! x (term BitVec)
+ (! y (term BitVec)
+ (! x' var_bv
+ (! y' var_bv
+ (! n mpz
+ (! ux (bv_atom x x' n)
+ (! uy (bv_atom y y' n)
+ (th_holds (= BitVec (bvadd x y) (bvadd y x)))))))))))
+
+
+
+; necessary?
+(program calc_bvand ((a bv) (b bv)) bv
+ (match a
+ (bvn (match b (bvn bvn) (default (fail bv))))
+ ((bvc ba a') (match b
+ ((bvc bb b') (bvc (match ba (b0 b0) (b1 bb)) (calc_bvand a' b')))
+ (default (fail bv))))))
+
+; rewrite rule (w constants) :
+; a & b = c
+(declare bvand_const (! c bv
+ (! a bv
+ (! b bv
+ (! u (^ (calc_bvand a b) c)
+ (th_holds (= BitVec (bvand (a_bv a) (a_bv b)) (a_bv c))))))))
\ No newline at end of file diff --git a/src/Makefile.am b/src/Makefile.am index 805ed6cb7..908e3de6c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -327,6 +327,8 @@ libcvc4_la_SOURCES = \ theory/quantifiers/ambqi_builder.cpp \ theory/quantifiers/quant_conflict_find.h \ theory/quantifiers/quant_conflict_find.cpp \ + theory/quantifiers/conjecture_generator.h \ + theory/quantifiers/conjecture_generator.cpp \ theory/quantifiers/options_handlers.h \ theory/arith/theory_arith_type_rules.h \ theory/arith/type_enumerator.h \ diff --git a/src/bindings/Makefile.am b/src/bindings/Makefile.am index 2214d9b88..e7548bbe1 100644 --- a/src/bindings/Makefile.am +++ b/src/bindings/Makefile.am @@ -63,8 +63,8 @@ java_libcvc4jni_la_LDFLAGS = \ -shrext $(CVC4_JAVA_MODULE_EXT) \ -version-info $(LIBCVC4BINDINGS_VERSION) java_libcvc4jni_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la endif if CVC4_LANGUAGE_BINDING_CSHARP csharplib_LTLIBRARIES += csharp/CVC4.la @@ -72,8 +72,8 @@ csharp_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) csharp_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la endif if CVC4_LANGUAGE_BINDING_PERL perllib_LTLIBRARIES += perl/CVC4.la @@ -81,8 +81,8 @@ perl_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) perl_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la perldata_DATA += perl/CVC4.pm endif if CVC4_LANGUAGE_BINDING_PHP @@ -91,8 +91,8 @@ php_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) php_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la phpdata_DATA += php/CVC4.php endif if CVC4_LANGUAGE_BINDING_PYTHON @@ -102,8 +102,8 @@ python_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) python_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la pythondata_DATA += python/CVC4.py endif if CVC4_LANGUAGE_BINDING_OCAML @@ -117,8 +117,8 @@ ocaml_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) ocaml_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la endif if CVC4_LANGUAGE_BINDING_RUBY rubylib_LTLIBRARIES += ruby/CVC4.la @@ -126,8 +126,8 @@ ruby_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) ruby_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la endif if CVC4_LANGUAGE_BINDING_TCL tcllib_LTLIBRARIES += tcl/CVC4.la @@ -135,8 +135,8 @@ tcl_CVC4_la_LDFLAGS = \ -module \ -version-info $(LIBCVC4BINDINGS_VERSION) tcl_CVC4_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la endif # this endif matches the "if CVC4_HAS_SWIG" above endif diff --git a/src/bindings/compat/c/Makefile.am b/src/bindings/compat/c/Makefile.am index 5a788f2bf..4ec4626c6 100644 --- a/src/bindings/compat/c/Makefile.am +++ b/src/bindings/compat/c/Makefile.am @@ -25,8 +25,8 @@ lib_LTLIBRARIES += libcvc4bindings_c_compat.la libcvc4bindings_c_compat_la_LDFLAGS = \ -version-info $(LIBCVC4BINDINGS_VERSION) libcvc4bindings_c_compat_la_LIBADD = \ - -L@builddir@/../../../compat -lcvc4compat \ - -L@builddir@/../../.. -lcvc4 + @builddir@/../../../compat/libcvc4compat.la \ + @builddir@/../../../libcvc4.la endif diff --git a/src/bindings/compat/java/Makefile.am b/src/bindings/compat/java/Makefile.am index 9eb985822..5b052568d 100644 --- a/src/bindings/compat/java/Makefile.am +++ b/src/bindings/compat/java/Makefile.am @@ -33,8 +33,8 @@ libcvc4compatjni_la_LDFLAGS = \ -shrext $(CVC4_JAVA_MODULE_EXT) \ -version-info $(LIBCVC4BINDINGS_VERSION) libcvc4compatjni_la_LIBADD = \ - -L@builddir@/../../../compat -lcvc4compat \ - -L@builddir@/../../.. -lcvc4 + @builddir@/../../../compat/libcvc4compat.la \ + @builddir@/../../../libcvc4.la BUILT_SOURCES += $(JNI_CPP_FILES) endif diff --git a/src/compat/Makefile.am b/src/compat/Makefile.am index 5a8bd454e..ebb13426d 100644 --- a/src/compat/Makefile.am +++ b/src/compat/Makefile.am @@ -25,8 +25,8 @@ libcvc4compat_la_LDFLAGS = \ -version-info $(LIBCVC4COMPAT_VERSION) libcvc4compat_la_LIBADD = \ - -L@builddir@/.. -lcvc4 \ - -L@builddir@/../parser -lcvc4parser + @builddir@/../libcvc4.la \ + @builddir@/../parser/libcvc4parser.la if CVC4_NEEDS_REPLACEMENT_FUNCTIONS libcvc4compat_la_LIBADD += \ diff --git a/src/expr/command.cpp b/src/expr/command.cpp index 16484a320..33be85d11 100644 --- a/src/expr/command.cpp +++ b/src/expr/command.cpp @@ -744,22 +744,22 @@ Command* DefineNamedFunctionCommand::clone() const { SetUserAttributeCommand::SetUserAttributeCommand( const std::string& attr, Expr expr ) throw() : d_attr( attr ), d_expr( expr ){ } -/* -SetUserAttributeCommand::SetUserAttributeCommand( const std::string& id, Expr expr, + +SetUserAttributeCommand::SetUserAttributeCommand( const std::string& attr, Expr expr, std::vector<Expr>& values ) throw() : - d_id( id ), d_expr( expr ){ + d_attr( attr ), d_expr( expr ){ d_expr_values.insert( d_expr_values.begin(), values.begin(), values.end() ); } -SetUserAttributeCommand::SetUserAttributeCommand( const std::string& id, Expr expr, - std::string& value ) throw() : - d_id( id ), d_expr( expr ), d_str_value( value ){ +SetUserAttributeCommand::SetUserAttributeCommand( const std::string& attr, Expr expr, + const std::string& value ) throw() : + d_attr( attr ), d_expr( expr ), d_str_value( value ){ } -*/ + void SetUserAttributeCommand::invoke(SmtEngine* smtEngine) throw(){ try { if(!d_expr.isNull()) { - smtEngine->setUserAttribute( d_attr, d_expr ); + smtEngine->setUserAttribute( d_attr, d_expr, d_expr_values, d_str_value ); } d_commandStatus = CommandSuccess::instance(); } catch(exception& e) { @@ -769,11 +769,15 @@ void SetUserAttributeCommand::invoke(SmtEngine* smtEngine) throw(){ Command* SetUserAttributeCommand::exportTo(ExprManager* exprManager, ExprManagerMapCollection& variableMap){ Expr expr = d_expr.exportTo(exprManager, variableMap); - return new SetUserAttributeCommand( d_attr, expr ); + SetUserAttributeCommand * c = new SetUserAttributeCommand( d_attr, expr, d_str_value ); + c->d_expr_values.insert( c->d_expr_values.end(), d_expr_values.begin(), d_expr_values.end() ); + return c; } Command* SetUserAttributeCommand::clone() const{ - return new SetUserAttributeCommand( d_attr, d_expr ); + SetUserAttributeCommand * c = new SetUserAttributeCommand( d_attr, d_expr, d_str_value ); + c->d_expr_values.insert( c->d_expr_values.end(), d_expr_values.begin(), d_expr_values.end() ); + return c; } std::string SetUserAttributeCommand::getCommandName() const throw() { diff --git a/src/expr/command.h b/src/expr/command.h index 606618d21..c4e7fbf89 100644 --- a/src/expr/command.h +++ b/src/expr/command.h @@ -439,12 +439,12 @@ class CVC4_PUBLIC SetUserAttributeCommand : public Command { protected: std::string d_attr; Expr d_expr; - //std::vector<Expr> d_expr_values; - //std::string d_str_value; + std::vector<Expr> d_expr_values; + std::string d_str_value; public: SetUserAttributeCommand( const std::string& attr, Expr expr ) throw(); - //SetUserAttributeCommand( const std::string& id, Expr expr, std::vector<Expr>& values ) throw(); - //SetUserAttributeCommand( const std::string& id, Expr expr, std::string& value ) throw(); + SetUserAttributeCommand( const std::string& attr, Expr expr, std::vector<Expr>& values ) throw(); + SetUserAttributeCommand( const std::string& attr, Expr expr, const std::string& value ) throw(); ~SetUserAttributeCommand() throw() {} void invoke(SmtEngine* smtEngine) throw(); Command* exportTo(ExprManager* exprManager, ExprManagerMapCollection& variableMap); diff --git a/src/parser/Makefile.am b/src/parser/Makefile.am index a178f8dd5..c8a8cc941 100644 --- a/src/parser/Makefile.am +++ b/src/parser/Makefile.am @@ -29,7 +29,7 @@ libcvc4parser_la_LIBADD = \ @builddir@/smt2/libparsersmt2.la \ @builddir@/tptp/libparsertptp.la \ @builddir@/cvc/libparsercvc.la \ - -L@builddir@/.. -lcvc4 + @builddir@/../libcvc4.la if CVC4_NEEDS_REPLACEMENT_FUNCTIONS libcvc4parser_la_LIBADD += \ diff --git a/src/parser/smt2/Smt2.g b/src/parser/smt2/Smt2.g index e05ffaebe..bd7c96dce 100644 --- a/src/parser/smt2/Smt2.g +++ b/src/parser/smt2/Smt2.g @@ -1167,6 +1167,26 @@ attribute[CVC4::Expr& expr,CVC4::Expr& retExpr, std::string& attr] attr = std::string(":no-pattern"); PARSER_STATE->attributeNotSupported(attr); } + | ATTRIBUTE_INST_LEVEL INTEGER_LITERAL + { + Expr n = MK_CONST( AntlrInput::tokenToInteger($INTEGER_LITERAL) ); + std::vector<Expr> values; + values.push_back( n ); + std::string attr_name("inst-level"); + Command* c = new SetUserAttributeCommand( attr_name, expr, values ); + c->setMuted(true); + PARSER_STATE->preemptCommand(c); + } + | ATTRIBUTE_RR_PRIORITY_LEVEL INTEGER_LITERAL + { + Expr n = MK_CONST( AntlrInput::tokenToInteger($INTEGER_LITERAL) ); + std::vector<Expr> values; + values.push_back( n ); + std::string attr_name("rr-priority"); + Command* c = new SetUserAttributeCommand( attr_name, expr, values ); + c->setMuted(true); + PARSER_STATE->preemptCommand(c); + } | ATTRIBUTE_NAMED_TOK symbolicExpr[sexpr] { attr = std::string(":named"); @@ -1690,6 +1710,8 @@ INCLUDE_TOK : 'include'; ATTRIBUTE_PATTERN_TOK : ':pattern'; ATTRIBUTE_NO_PATTERN_TOK : ':no-pattern'; ATTRIBUTE_NAMED_TOK : ':named'; +ATTRIBUTE_INST_LEVEL : ':inst-level'; +ATTRIBUTE_RR_PRIORITY : ':rr-priority'; // operators (NOTE: theory symbols go here) AMPERSAND_TOK : '&'; diff --git a/src/prop/bvminisat/bvminisat.cpp b/src/prop/bvminisat/bvminisat.cpp index 7322cd0fa..2121d7366 100644 --- a/src/prop/bvminisat/bvminisat.cpp +++ b/src/prop/bvminisat/bvminisat.cpp @@ -97,6 +97,10 @@ void BVMinisatSatSolver::markUnremovable(SatLiteral lit){ d_minisat->setFrozen(BVMinisat::var(toMinisatLit(lit)), true); } +void BVMinisatSatSolver::spendResource(){ + // do nothing for the BV solver +} + void BVMinisatSatSolver::interrupt(){ d_minisat->interrupt(); } diff --git a/src/prop/bvminisat/bvminisat.h b/src/prop/bvminisat/bvminisat.h index f9d0fbd6a..0101c5d62 100644 --- a/src/prop/bvminisat/bvminisat.h +++ b/src/prop/bvminisat/bvminisat.h @@ -87,6 +87,8 @@ public: void markUnremovable(SatLiteral lit); + void spendResource(); + void interrupt(); SatValue solve(); diff --git a/src/prop/minisat/core/Solver.cc b/src/prop/minisat/core/Solver.cc index 610023b70..b0d710d66 100644 --- a/src/prop/minisat/core/Solver.cc +++ b/src/prop/minisat/core/Solver.cc @@ -106,7 +106,7 @@ Solver::Solver(CVC4::prop::TheoryProxy* proxy, CVC4::context::Context* context, // Statistics: (formerly in 'SolverStats') // - , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0) + , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0), resources_consumed(0) , dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0) , ok (true) @@ -1588,6 +1588,9 @@ CRef Solver::updateLemmas() { Debug("minisat::lemmas") << "Solver::updateLemmas() begin" << std::endl; + // Avoid adding lemmas indefinitely without resource-out + spendResource(); + CRef conflict = CRef_Undef; // Decision level to backtrack to diff --git a/src/prop/minisat/core/Solver.h b/src/prop/minisat/core/Solver.h index 30d72ac75..7831f211b 100644 --- a/src/prop/minisat/core/Solver.h +++ b/src/prop/minisat/core/Solver.h @@ -215,6 +215,7 @@ public: void budgetOff(); void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver. void clearInterrupt(); // Clear interrupt indicator flag. + void spendResource(); // Memory managment: // @@ -252,7 +253,7 @@ public: // Statistics: (read-only member variable) // - uint64_t solves, starts, decisions, rnd_decisions, propagations, conflicts; + uint64_t solves, starts, decisions, rnd_decisions, propagations, conflicts, resources_consumed; uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals; protected: @@ -526,8 +527,9 @@ inline void Solver::clearInterrupt(){ asynch_interrupt = false; } inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; } inline bool Solver::withinBudget() const { return !asynch_interrupt && - (conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) && + (conflict_budget < 0 || conflicts + resources_consumed < (uint64_t)conflict_budget) && (propagation_budget < 0 || propagations < (uint64_t)propagation_budget); } +inline void Solver::spendResource() { ++resources_consumed; } // FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a // pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or diff --git a/src/prop/minisat/minisat.cpp b/src/prop/minisat/minisat.cpp index e4956ecc8..4a192d0d2 100644 --- a/src/prop/minisat/minisat.cpp +++ b/src/prop/minisat/minisat.cpp @@ -168,10 +168,10 @@ SatValue MinisatSatSolver::solve(unsigned long& resource) { d_minisat->setConfBudget(resource); } Minisat::vec<Minisat::Lit> empty; - unsigned long conflictsBefore = d_minisat->conflicts; + unsigned long conflictsBefore = d_minisat->conflicts + d_minisat->resources_consumed; SatValue result = toSatLiteralValue(d_minisat->solveLimited(empty)); d_minisat->clearInterrupt(); - resource = d_minisat->conflicts - conflictsBefore; + resource = d_minisat->conflicts + d_minisat->resources_consumed - conflictsBefore; Trace("limit") << "SatSolver::solve(): it took " << resource << " conflicts" << std::endl; return result; } @@ -182,6 +182,9 @@ SatValue MinisatSatSolver::solve() { return toSatLiteralValue(d_minisat->solve()); } +void MinisatSatSolver::spendResource() { + d_minisat->spendResource(); +} void MinisatSatSolver::interrupt() { d_minisat->interrupt(); diff --git a/src/prop/minisat/minisat.h b/src/prop/minisat/minisat.h index a919bbcc4..b37371d98 100644 --- a/src/prop/minisat/minisat.h +++ b/src/prop/minisat/minisat.h @@ -62,6 +62,7 @@ public: SatValue solve(); SatValue solve(long unsigned int&); + void spendResource(); void interrupt(); SatValue value(SatLiteral l); diff --git a/src/prop/sat_solver.h b/src/prop/sat_solver.h index 929b867c9..8e7e53474 100644 --- a/src/prop/sat_solver.h +++ b/src/prop/sat_solver.h @@ -61,6 +61,9 @@ public: /** Check the satisfiability of the added clauses */ virtual SatValue solve(long unsigned int&) = 0; + /** Instruct the solver that it should bump its consumed resource count. */ + virtual void spendResource() = 0; + /** Interrupt the solver */ virtual void interrupt() = 0; diff --git a/src/smt/smt_engine.cpp b/src/smt/smt_engine.cpp index 105ab9749..77ee362c0 100644 --- a/src/smt/smt_engine.cpp +++ b/src/smt/smt_engine.cpp @@ -1111,10 +1111,8 @@ void SmtEngine::setDefaults() { if (options::arithRewriteEq()) { d_earlyTheoryPP = false; } - // Turn on justification heuristic of the decision engine for QF_BV and QF_AUFBV - // and also use it in stop-only mode for QF_AUFLIA, QF_LRA and Quantifiers - // BUT use neither in ALL_SUPPORTED mode (since it doesn't yet work well - // with incrementality) + + // Set decision mode based on logic (if not set by user) if(!options::decisionMode.wasSetByUser()) { decision::DecisionMode decMode = // ALL_SUPPORTED @@ -3176,6 +3174,14 @@ void SmtEnginePrivate::processAssertions() { // introducing new ones dumpAssertions("post-everything", d_assertionsToCheck); + + //set instantiation level of everything to zero + if( options::instLevelInputOnly() && options::instMaxLevel()!=-1 ){ + for( unsigned i=0; i < d_assertionsToCheck.size(); i++ ) { + theory::QuantifiersEngine::setInstantiationLevelAttr( d_assertionsToCheck[i], 0 ); + } + } + // Push the formula to SAT { @@ -4104,9 +4110,13 @@ SExpr SmtEngine::getStatistic(std::string name) const throw() { return d_statisticsRegistry->getStatistic(name); } -void SmtEngine::setUserAttribute(const std::string& attr, Expr expr) { +void SmtEngine::setUserAttribute(const std::string& attr, Expr expr, std::vector<Expr> expr_values, std::string str_value) { SmtScope smts(this); - d_theoryEngine->setUserAttribute(attr, expr.getNode()); + std::vector<Node> node_values; + for( unsigned i=0; i<expr_values.size(); i++ ){ + node_values.push_back( expr_values[i].getNode() ); + } + d_theoryEngine->setUserAttribute(attr, expr.getNode(), node_values, str_value); } void SmtEngine::setPrintFuncInModel(Expr f, bool p) { diff --git a/src/smt/smt_engine.h b/src/smt/smt_engine.h index 71b42534a..1671654d1 100644 --- a/src/smt/smt_engine.h +++ b/src/smt/smt_engine.h @@ -651,7 +651,7 @@ public: * This function is called when an attribute is set by a user. * In SMT-LIBv2 this is done via the syntax (! expr :attr) */ - void setUserAttribute(const std::string& attr, Expr expr); + void setUserAttribute(const std::string& attr, Expr expr, std::vector<Expr> expr_values, std::string str_value); /** * Set print function in model diff --git a/src/theory/bv/bitblaster_template.h b/src/theory/bv/bitblaster_template.h index ecd7013c7..ea31e3821 100644 --- a/src/theory/bv/bitblaster_template.h +++ b/src/theory/bv/bitblaster_template.h @@ -74,19 +74,22 @@ protected: typedef std::vector<T> Bits; typedef __gnu_cxx::hash_map <Node, Bits, NodeHashFunction> TermDefMap; typedef __gnu_cxx::hash_set<TNode, TNodeHashFunction> TNodeSet; + typedef __gnu_cxx::hash_map<Node, Node, NodeHashFunction> ModelCache; typedef void (*TermBBStrategy) (TNode, Bits&, TBitblaster<T>*); typedef T (*AtomBBStrategy) (TNode, TBitblaster<T>*); // caches and mappings - TermDefMap d_termCache; - + TermDefMap d_termCache; + ModelCache d_modelCache; + void initAtomBBStrategies(); void initTermBBStrategies(); protected: /// function tables for the various bitblasting strategies indexed by node kind TermBBStrategy d_termBBStrategies[kind::LAST_KIND]; AtomBBStrategy d_atomBBStrategies[kind::LAST_KIND]; + virtual Node getModelFromSatSolver(TNode node, bool fullModel) = 0; public: TBitblaster(); virtual ~TBitblaster() {} @@ -97,9 +100,18 @@ public: virtual bool hasBBAtom(TNode atom) const = 0; virtual void storeBBAtom(TNode atom, T atom_bb) = 0; + bool hasBBTerm(TNode node) const; void getBBTerm(TNode node, Bits& bits) const; - void storeBBTerm(TNode term, const Bits& bits); + void storeBBTerm(TNode term, const Bits& bits); + /** + * Return a constant representing the value of a in the model. + * If fullModel is true set unconstrained bits to 0. If not return + * NullNode() for a fully or partially unconstrained. + * + */ + Node getTermModel(TNode node, bool fullModel); + void invalidateModelCache(); }; @@ -109,7 +121,6 @@ class TLazyBitblaster : public TBitblaster<Node> { typedef std::vector<Node> Bits; typedef context::CDList<prop::SatLiteral> AssertionList; typedef context::CDHashMap<prop::SatLiteral, std::vector<prop::SatLiteral> , prop::SatLiteralHashFunction> ExplanationMap; - /** This class gets callbacks from minisat on propagations */ class MinisatNotify : public prop::BVSatSolverInterface::Notify { prop::CnfStream* d_cnf; @@ -143,9 +154,12 @@ class TLazyBitblaster : public TBitblaster<Node> { TNodeSet d_bbAtoms; AbstractionModule* d_abstraction; bool d_emptyNotify; + + context::CDO<bool> d_satSolverFullModel; void addAtom(TNode atom); bool hasValue(TNode a); + Node getModelFromSatSolver(TNode a, bool fullModel); public: void bbTerm(TNode node, Bits& bits); void bbAtom(TNode node); @@ -172,14 +186,7 @@ public: void setAbstraction(AbstractionModule* abs); theory::EqualityStatus getEqualityStatus(TNode a, TNode b); - /** - * Return a constant Node representing the value of a variable - * in the current model. - * @param a - * - * @return - */ - Node getVarValue(TNode a, bool fullModel=true); + /** * Adds a constant value for each bit-blasted variable in the model. * @@ -245,7 +252,7 @@ class EagerBitblaster : public TBitblaster<Node> { TNodeSet d_bbAtoms; TNodeSet d_variables; - Node getVarValue(TNode a, bool fullModel); + Node getModelFromSatSolver(TNode a, bool fullModel); bool isSharedTerm(TNode node); public: @@ -299,7 +306,7 @@ class AigBitblaster : public TBitblaster<Abc_Obj_t*> { bool hasInput(TNode input); void convertToCnfAndAssert(); void assertToSatSolver(Cnf_Dat_t* pCnf); - + Node getModelFromSatSolver(TNode a, bool fullModel) { Unreachable(); } public: AigBitblaster(); ~AigBitblaster(); @@ -387,6 +394,7 @@ template <class T> void TBitblaster<T>::initTermBBStrategies() { template <class T> TBitblaster<T>::TBitblaster() : d_termCache() + , d_modelCache() { initAtomBBStrategies(); initTermBBStrategies(); @@ -407,6 +415,53 @@ void TBitblaster<T>::storeBBTerm(TNode node, const Bits& bits) { d_termCache.insert(std::make_pair(node, bits)); } +template <class T> +void TBitblaster<T>::invalidateModelCache() { + d_modelCache.clear(); +} + +template <class T> +Node TBitblaster<T>::getTermModel(TNode node, bool fullModel) { + if (d_modelCache.find(node) != d_modelCache.end()) + return d_modelCache[node]; + + if (node.isConst()) + return node; + + Node value = getModelFromSatSolver(node, false); + if (!value.isNull()) { + Debug("bv-equality-status")<< "TLazyBitblaster::getTermModel from SatSolver" << node <<" => " << value <<"\n"; + d_modelCache[node] = value; + Assert (value.isConst()); + return value; + } + + if (Theory::isLeafOf(node, theory::THEORY_BV)) { + // if it is a leaf may ask for fullModel + value = getModelFromSatSolver(node, fullModel); + Debug("bv-equality-status")<< "TLazyBitblaster::getTermModel from VarValue" << node <<" => " << value <<"\n"; + Assert (!value.isNull()); + d_modelCache[node] = value; + return value; + } + Assert (node.getType().isBitVector()); + + NodeBuilder<> nb(node.getKind()); + if (node.getMetaKind() == kind::metakind::PARAMETERIZED) { + nb << node.getOperator(); + } + + for (unsigned i = 0; i < node.getNumChildren(); ++i) { + nb << getTermModel(node[i], fullModel); + } + value = nb; + value = Rewriter::rewrite(value); + Assert (value.isConst()); + d_modelCache[node] = value; + Debug("bv-term-model")<< "TLazyBitblaster::getTermModel Building Value" << node <<" => " << value <<"\n"; + return value; +} + } /* bv namespace */ diff --git a/src/theory/bv/bv_quick_check.cpp b/src/theory/bv/bv_quick_check.cpp index 5f35f95e3..b2b4eebdf 100644 --- a/src/theory/bv/bv_quick_check.cpp +++ b/src/theory/bv/bv_quick_check.cpp @@ -115,7 +115,7 @@ BVQuickCheck::vars_iterator BVQuickCheck::endVars() { } Node BVQuickCheck::getVarValue(TNode var) { - return d_bitblaster->getVarValue(var); + return d_bitblaster->getTermModel(var, true); } diff --git a/src/theory/bv/bv_subtheory_bitblast.cpp b/src/theory/bv/bv_subtheory_bitblast.cpp index a2a6e19ac..35542fc68 100644 --- a/src/theory/bv/bv_subtheory_bitblast.cpp +++ b/src/theory/bv/bv_subtheory_bitblast.cpp @@ -103,6 +103,7 @@ void BitblastSolver::bitblastQueue() { // don't bit-blast lemma atoms continue; } + Debug("bitblast-queue") << "Bitblasting atom " << atom <<"\n"; d_bitblaster->bbAtom(atom); } } @@ -218,48 +219,45 @@ void BitblastSolver::collectModelInfo(TheoryModel* m, bool fullModel) { Node BitblastSolver::getModelValue(TNode node) { - if (!d_validModelCache) { - d_modelCache.clear(); - d_validModelCache = true; - } - return getModelValueRec(node); -} - -Node BitblastSolver::getModelValueRec(TNode node) -{ - Node val; - if (node.isConst()) { - return node; - } - NodeMap::iterator it = d_modelCache.find(node); - if (it != d_modelCache.end()) { - val = (*it).second; - Debug("bitvector-model") << node << " => (cached) " << val <<"\n"; - return val; - } - if (d_bv->isLeaf(node)) { - val = d_bitblaster->getVarValue(node); - if (val == Node()) { - // If no value in model, just set to 0 - val = utils::mkConst(utils::getSize(node), (unsigned)0); - } - } else { - NodeBuilder<> valBuilder(node.getKind()); - if (node.getMetaKind() == kind::metakind::PARAMETERIZED) { - valBuilder << node.getOperator(); - } - for (unsigned i = 0; i < node.getNumChildren(); ++i) { - valBuilder << getModelValueRec(node[i]); - } - val = valBuilder; - val = Rewriter::rewrite(val); - } - Assert(val.isConst()); - d_modelCache[node] = val; - Debug("bitvector-model") << node << " => " << val <<"\n"; + Node val = d_bitblaster->getTermModel(node, false); return val; } +// Node BitblastSolver::getModelValueRec(TNode node) +// { +// Node val; +// if (node.isConst()) { +// return node; +// } +// NodeMap::iterator it = d_modelCache.find(node); +// if (it != d_modelCache.end()) { +// val = (*it).second; +// Debug("bitvector-model") << node << " => (cached) " << val <<"\n"; +// return val; +// } +// if (d_bv->isLeaf(node)) { +// val = d_bitblaster->getVarValue(node); +// if (val == Node()) { +// // If no value in model, just set to 0 +// val = utils::mkConst(utils::getSize(node), (unsigned)0); +// } +// } else { +// NodeBuilder<> valBuilder(node.getKind()); +// if (node.getMetaKind() == kind::metakind::PARAMETERIZED) { +// valBuilder << node.getOperator(); +// } +// for (unsigned i = 0; i < node.getNumChildren(); ++i) { +// valBuilder << getModelValueRec(node[i]); +// } +// val = valBuilder; +// val = Rewriter::rewrite(val); +// } +// Assert(val.isConst()); +// d_modelCache[node] = val; +// Debug("bitvector-model") << node << " => " << val <<"\n"; +// return val; +// } + void BitblastSolver::setConflict(TNode conflict) { Node final_conflict = conflict; diff --git a/src/theory/bv/bv_subtheory_bitblast.h b/src/theory/bv/bv_subtheory_bitblast.h index 414abdcce..77461163c 100644 --- a/src/theory/bv/bv_subtheory_bitblast.h +++ b/src/theory/bv/bv_subtheory_bitblast.h @@ -57,7 +57,7 @@ class BitblastSolver : public SubtheorySolver { AbstractionModule* d_abstractionModule; BVQuickCheck* d_quickCheck; QuickXPlain* d_quickXplain; - Node getModelValueRec(TNode node); + // Node getModelValueRec(TNode node); void setConflict(TNode conflict); public: BitblastSolver(context::Context* c, TheoryBV* bv); diff --git a/src/theory/bv/eager_bitblaster.cpp b/src/theory/bv/eager_bitblaster.cpp index e8fee00f5..38b9a1a0a 100644 --- a/src/theory/bv/eager_bitblaster.cpp +++ b/src/theory/bv/eager_bitblaster.cpp @@ -156,11 +156,11 @@ bool EagerBitblaster::solve() { * * @return */ -Node EagerBitblaster::getVarValue(TNode a, bool fullModel) { +Node EagerBitblaster::getModelFromSatSolver(TNode a, bool fullModel) { if (!hasBBTerm(a)) { - Assert(isSharedTerm(a)); - return Node(); + return fullModel? utils::mkConst(utils::getSize(a), 0u) : Node(); } + Bits bits; getBBTerm(a, bits); Integer value(0); @@ -171,7 +171,8 @@ Node EagerBitblaster::getVarValue(TNode a, bool fullModel) { bit_value = d_satSolver->value(bit); Assert (bit_value != prop::SAT_VALUE_UNKNOWN); } else { - // the bit is unconstrainted so we can give it an arbitrary value + if (!fullModel) return Node(); + // unconstrained bits default to false bit_value = prop::SAT_VALUE_FALSE; } Integer bit_int = bit_value == prop::SAT_VALUE_TRUE ? Integer(1) : Integer(0); @@ -182,19 +183,17 @@ Node EagerBitblaster::getVarValue(TNode a, bool fullModel) { void EagerBitblaster::collectModelInfo(TheoryModel* m, bool fullModel) { - TNodeSet::const_iterator it = d_variables.begin(); + TNodeSet::iterator it = d_variables.begin(); for (; it!= d_variables.end(); ++it) { TNode var = *it; - if (Theory::theoryOf(var) == theory::THEORY_BV || isSharedTerm(var)) { - Node const_value = getVarValue(var, fullModel); - if(const_value == Node()) { - if( fullModel ){ - // if the value is unassigned just set it to zero - const_value = utils::mkConst(BitVector(utils::getSize(var), 0u)); - } - } + if (d_bv->isLeaf(var) || isSharedTerm(var)) { + // only shared terms could not have been bit-blasted + Assert (hasBBTerm(var) || isSharedTerm(var)); + + Node const_value = getModelFromSatSolver(var, fullModel); + if(const_value != Node()) { - Debug("bitvector-model") << "TLazyBitblaster::collectModelInfo (assert (= " + Debug("bitvector-model") << "EagerBitblaster::collectModelInfo (assert (= " << var << " " << const_value << "))\n"; m->assertEquality(var, const_value, true); diff --git a/src/theory/bv/lazy_bitblaster.cpp b/src/theory/bv/lazy_bitblaster.cpp index f721a22f0..101d8b082 100644 --- a/src/theory/bv/lazy_bitblaster.cpp +++ b/src/theory/bv/lazy_bitblaster.cpp @@ -41,6 +41,7 @@ TLazyBitblaster::TLazyBitblaster(context::Context* c, bv::TheoryBV* bv, const st , d_bbAtoms() , d_abstraction(NULL) , d_emptyNotify(emptyNotify) + , d_satSolverFullModel(c, false) , d_name(name) , d_statistics(name) { d_satSolver = prop::SatSolverFactory::createMinisat(c, name); @@ -258,6 +259,7 @@ bool TLazyBitblaster::solve() { } } Debug("bitvector") << "TLazyBitblaster::solve() asserted atoms " << d_assertedAtoms->size() <<"\n"; + d_satSolverFullModel.set(true); return prop::SAT_VALUE_TRUE == d_satSolver->solve(); } @@ -354,42 +356,38 @@ void TLazyBitblaster::MinisatNotify::safePoint() { d_bv->d_out->safePoint(); } + EqualityStatus TLazyBitblaster::getEqualityStatus(TNode a, TNode b) { + Debug("bv-equality-status")<< "TLazyBitblaster::getEqualityStatus " << a <<" = " << b <<"\n"; + Debug("bv-equality-status")<< "BVSatSolver has full model? " << d_satSolverFullModel.get() <<"\n"; - // We don't want to bit-blast every possibly expensive term for the sake of equality checking - if (hasBBTerm(a) && hasBBTerm(b)) { - - Bits a_bits, b_bits; - getBBTerm(a, a_bits); - getBBTerm(b, b_bits); - theory::EqualityStatus status = theory::EQUALITY_TRUE_IN_MODEL; - for (unsigned i = 0; i < a_bits.size(); ++ i) { - if (d_cnfStream->hasLiteral(a_bits[i]) && d_cnfStream->hasLiteral(b_bits[i])) { - prop::SatLiteral a_lit = d_cnfStream->getLiteral(a_bits[i]); - prop::SatValue a_lit_value = d_satSolver->value(a_lit); - if (a_lit_value != prop::SAT_VALUE_UNKNOWN) { - prop::SatLiteral b_lit = d_cnfStream->getLiteral(b_bits[i]); - prop::SatValue b_lit_value = d_satSolver->value(b_lit); - if (b_lit_value != prop::SAT_VALUE_UNKNOWN) { - if (a_lit_value != b_lit_value) { - return theory::EQUALITY_FALSE_IN_MODEL; - } - } else { - status = theory::EQUALITY_UNKNOWN; - } - } { - status = theory::EQUALITY_UNKNOWN; - } - } else { - status = theory::EQUALITY_UNKNOWN; - } - } + // First check if it trivially rewrites to false/true + Node a_eq_b = Rewriter::rewrite(utils::mkNode(kind::EQUAL, a, b)); - return status; + if (a_eq_b == utils::mkFalse()) return theory::EQUALITY_FALSE; + if (a_eq_b == utils::mkTrue()) return theory::EQUALITY_TRUE; - } else { - return theory::EQUALITY_UNKNOWN; + if (!d_satSolverFullModel.get()) + return theory::EQUALITY_UNKNOWN; + + // Check if cache is valid (invalidated in check and pops) + if (d_bv->d_invalidateModelCache.get()) { + invalidateModelCache(); } + d_bv->d_invalidateModelCache.set(false); + + Node a_value = getTermModel(a, true); + Node b_value = getTermModel(b, true); + + Assert (a_value.isConst() && + b_value.isConst()); + + if (a_value == b_value) { + Debug("bv-equality-status")<< "theory::EQUALITY_TRUE_IN_MODEL\n"; + return theory::EQUALITY_TRUE_IN_MODEL; + } + Debug("bv-equality-status")<< "theory::EQUALITY_FALSE_IN_MODEL\n"; + return theory::EQUALITY_FALSE_IN_MODEL; } @@ -424,11 +422,11 @@ bool TLazyBitblaster::hasValue(TNode a) { * * @return */ -Node TLazyBitblaster::getVarValue(TNode a, bool fullModel) { +Node TLazyBitblaster::getModelFromSatSolver(TNode a, bool fullModel) { if (!hasBBTerm(a)) { - Assert(isSharedTerm(a)); - return Node(); + return fullModel? utils::mkConst(utils::getSize(a), 0u) : Node(); } + Bits bits; getBBTerm(a, bits); Integer value(0); @@ -439,7 +437,8 @@ Node TLazyBitblaster::getVarValue(TNode a, bool fullModel) { bit_value = d_satSolver->value(bit); Assert (bit_value != prop::SAT_VALUE_UNKNOWN); } else { - // the bit is unconstrainted so we can give it an arbitrary value + if (!fullModel) return Node(); + // unconstrained bits default to false bit_value = prop::SAT_VALUE_FALSE; } Integer bit_int = bit_value == prop::SAT_VALUE_TRUE ? Integer(1) : Integer(0); @@ -449,23 +448,26 @@ Node TLazyBitblaster::getVarValue(TNode a, bool fullModel) { } void TLazyBitblaster::collectModelInfo(TheoryModel* m, bool fullModel) { - TNodeSet::iterator it = d_variables.begin(); - for (; it!= d_variables.end(); ++it) { + std::set<Node> termSet; + d_bv->computeRelevantTerms(termSet); + + for (std::set<Node>::const_iterator it = termSet.begin(); it != termSet.end(); ++it) { TNode var = *it; - if (Theory::theoryOf(var) == theory::THEORY_BV || isSharedTerm(var)) { - Node const_value = getVarValue(var, fullModel); - if(const_value == Node()) { - if( fullModel ){ - // if the value is unassigned just set it to zero - const_value = utils::mkConst(BitVector(utils::getSize(var), 0u)); - } - } - if(const_value != Node()) { - Debug("bitvector-model") << "TLazyBitblaster::collectModelInfo (assert (= " - << var << " " - << const_value << "))\n"; + // not actually a leaf of the bit-vector theory + if (d_variables.find(var) == d_variables.end()) + continue; + + Assert (Theory::theoryOf(var) == theory::THEORY_BV || isSharedTerm(var)); + // only shared terms could not have been bit-blasted + Assert (hasBBTerm(var) || isSharedTerm(var)); + + Node const_value = getModelFromSatSolver(var, fullModel); + Assert (const_value.isNull() || const_value.isConst()); + if(const_value != Node()) { + Debug("bitvector-model") << "TLazyBitblaster::collectModelInfo (assert (= " + << var << " " + << const_value << "))\n"; m->assertEquality(var, const_value, true); - } } } } @@ -481,7 +483,7 @@ void TLazyBitblaster::clearSolver() { d_bbAtoms.clear(); d_variables.clear(); d_termCache.clear(); - + // recreate sat solver d_satSolver = prop::SatSolverFactory::createMinisat(d_ctx); d_cnfStream = new prop::TseitinCnfStream(d_satSolver, diff --git a/src/theory/bv/theory_bv.cpp b/src/theory/bv/theory_bv.cpp index 4abf25bb1..40bc2417b 100644 --- a/src/theory/bv/theory_bv.cpp +++ b/src/theory/bv/theory_bv.cpp @@ -49,6 +49,7 @@ TheoryBV::TheoryBV(context::Context* c, context::UserContext* u, OutputChannel& d_staticLearnCache(), d_lemmasAdded(c, false), d_conflict(c, false), + d_invalidateModelCache(c, true), d_literalsToPropagate(c), d_literalsToPropagateIndex(c, 0), d_propagatedBy(c), @@ -357,7 +358,8 @@ void TheoryBV::checkForLemma(TNode fact) { void TheoryBV::check(Effort e) { Debug("bitvector") << "TheoryBV::check(" << e << ")" << std::endl; - + // we may be getting new assertions so the model cache may not be sound + d_invalidateModelCache.set(true); // if we are using the eager solver if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) { // this can only happen on an empty benchmark diff --git a/src/theory/bv/theory_bv.h b/src/theory/bv/theory_bv.h index 22d9f6775..a37a4019e 100644 --- a/src/theory/bv/theory_bv.h +++ b/src/theory/bv/theory_bv.h @@ -141,6 +141,9 @@ private: // Are we in conflict? context::CDO<bool> d_conflict; + // Invalidate the model cache if check was called + context::CDO<bool> d_invalidateModelCache; + /** The conflict node */ Node d_conflictNode; diff --git a/src/theory/datatypes/theory_datatypes.cpp b/src/theory/datatypes/theory_datatypes.cpp index 544589306..65d307a34 100644 --- a/src/theory/datatypes/theory_datatypes.cpp +++ b/src/theory/datatypes/theory_datatypes.cpp @@ -570,7 +570,12 @@ void TheoryDatatypes::explain(TNode literal, std::vector<TNode>& assumptions){ TNode atom = polarity ? literal : literal[0]; if (atom.getKind() == kind::EQUAL || atom.getKind() == kind::IFF) { explainEquality( atom[0], atom[1], polarity, assumptions ); + } else if( atom.getKind() == kind::AND && polarity ){ + for( unsigned i=0; i<atom.getNumChildren(); i++ ){ + explain( atom[i], assumptions ); + } } else { + Assert( atom.getKind()!=kind::AND ); explainPredicate( atom, polarity, assumptions ); } } @@ -670,7 +675,7 @@ void TheoryDatatypes::merge( Node t1, Node t2 ){ for( unsigned i=0; i<deq_cand.size(); i++ ){ if( d_equalityEngine.areDisequal( deq_cand[i].first, deq_cand[i].second, true ) ){ conf = true; - Node eq = NodeManager::currentNM()->mkNode( deq_cand[i].first.getType().isBoolean() ? kind::IFF : kind::EQUAL, + Node eq = NodeManager::currentNM()->mkNode( deq_cand[i].first.getType().isBoolean() ? kind::IFF : kind::EQUAL, deq_cand[i].first, deq_cand[i].second ); exp.push_back( eq.negate() ); } @@ -1488,6 +1493,7 @@ void TheoryDatatypes::checkCycles() { } //process codatatypes if( cod_eqc.size()>1 ){ + Trace("dt-cod-debug") << "Process " << cod_eqc.size() << " co-datatypes" << std::endl; std::vector< std::vector< Node > > part_out; std::vector< TNode > exp; std::map< Node, Node > cn; @@ -1496,7 +1502,9 @@ void TheoryDatatypes::checkCycles() { cn[cod_eqc[i]] = cod_eqc[i]; } separateBisimilar( cod_eqc, part_out, exp, cn, dni, 0, false ); + Trace("dt-cod-debug") << "Done separate bisimilar." << std::endl; if( !part_out.empty() ){ + Trace("dt-cod-debug") << "Process partition size " << part_out.size() << std::endl; for( unsigned i=0; i<part_out.size(); i++ ){ std::vector< Node > part; part.push_back( part_out[i][0] ); diff --git a/src/theory/quantifiers/bounded_integers.cpp b/src/theory/quantifiers/bounded_integers.cpp index d6f9704b3..57799fd8e 100644 --- a/src/theory/quantifiers/bounded_integers.cpp +++ b/src/theory/quantifiers/bounded_integers.cpp @@ -243,8 +243,13 @@ void BoundedIntegers::process( Node f, Node n, bool pol, } } -void BoundedIntegers::check( Theory::Effort e ) { - if( e==Theory::EFFORT_LAST_CALL ){ +bool BoundedIntegers::needsCheck( Theory::Effort e ) { + return e==Theory::EFFORT_LAST_CALL; +} + +void BoundedIntegers::check( Theory::Effort e, unsigned quant_e ) { + if( quant_e==QuantifiersEngine::QEFFORT_STANDARD ){ + Trace("bint-engine") << "---Bounded Integers---" << std::endl; bool addedLemma = false; //make sure proxies are up-to-date with range for( unsigned i=0; i<d_ranges.size(); i++) { @@ -252,9 +257,7 @@ void BoundedIntegers::check( Theory::Effort e ) { addedLemma = true; } } - if( addedLemma ){ - d_quantEngine->flushLemmas( &d_quantEngine->getOutputChannel() ); - } + Trace("bint-engine") << " addedLemma = " << addedLemma << std::endl; } } diff --git a/src/theory/quantifiers/bounded_integers.h b/src/theory/quantifiers/bounded_integers.h index ac188ca65..355360e41 100644 --- a/src/theory/quantifiers/bounded_integers.h +++ b/src/theory/quantifiers/bounded_integers.h @@ -110,7 +110,8 @@ private: public: BoundedIntegers( context::Context* c, QuantifiersEngine* qe ); - void check( Theory::Effort e ); + bool needsCheck( Theory::Effort e ); + void check( Theory::Effort e, unsigned quant_e ); void registerQuantifier( Node f ); void assertNode( Node n ); Node getNextDecisionRequest(); diff --git a/src/theory/quantifiers/conjecture_generator.cpp b/src/theory/quantifiers/conjecture_generator.cpp new file mode 100644 index 000000000..a7c67a5e4 --- /dev/null +++ b/src/theory/quantifiers/conjecture_generator.cpp @@ -0,0 +1,1952 @@ +/********************* */
+/*! \file conjecture_generator.cpp
+ ** \verbatim
+ ** Original author: Andrew Reynolds
+ ** Major contributors: none
+ ** Minor contributors (to current version): none
+ ** This file is part of the CVC4 project.
+ ** Copyright (c) 2009-2014 New York University and The University of Iowa
+ ** See the file COPYING in the top-level source directory for licensing
+ ** information.\endverbatim
+ **
+ ** \brief conjecture generator class
+ **
+ **/
+
+#include "theory/quantifiers/conjecture_generator.h"
+#include "theory/theory_engine.h"
+#include "theory/quantifiers/options.h"
+#include "theory/quantifiers/term_database.h"
+#include "theory/quantifiers/trigger.h"
+#include "theory/quantifiers/first_order_model.h"
+
+using namespace CVC4;
+using namespace CVC4::kind;
+using namespace CVC4::theory;
+using namespace CVC4::theory::quantifiers;
+using namespace std;
+
+
+namespace CVC4 {
+
+void OpArgIndex::addTerm( ConjectureGenerator * s, TNode n, unsigned index ){
+ if( index==n.getNumChildren() ){
+ Assert( n.hasOperator() );
+ if( std::find( d_ops.begin(), d_ops.end(), n.getOperator() )==d_ops.end() ){
+ d_ops.push_back( n.getOperator() );
+ d_op_terms.push_back( n );
+ }
+ }else{
+ d_child[s->getTermDatabase()->d_arg_reps[n][index]].addTerm( s, n, index+1 );
+ }
+}
+
+Node OpArgIndex::getGroundTerm( ConjectureGenerator * s, std::vector< TNode >& args ) {
+ if( d_ops.empty() ){
+ for( std::map< TNode, OpArgIndex >::iterator it = d_child.begin(); it != d_child.end(); ++it ){
+ std::map< TNode, Node >::iterator itf = s->d_ground_eqc_map.find( it->first );
+ if( itf!=s->d_ground_eqc_map.end() ){
+ args.push_back( itf->second );
+ Node n = it->second.getGroundTerm( s, args );
+ args.pop_back();
+ if( !n.isNull() ){
+ return n;
+ }
+ }
+ }
+ return Node::null();
+ }else{
+ std::vector< TNode > args2;
+ args2.push_back( d_ops[0] );
+ args2.insert( args2.end(), args.begin(), args.end() );
+ return NodeManager::currentNM()->mkNode( d_op_terms[0].getKind(), args2 );
+ }
+}
+
+void OpArgIndex::getGroundTerms( ConjectureGenerator * s, std::vector< TNode >& terms ) {
+ terms.insert( terms.end(), d_op_terms.begin(), d_op_terms.end() );
+ for( std::map< TNode, OpArgIndex >::iterator it = d_child.begin(); it != d_child.end(); ++it ){
+ if( s->isGroundEqc( it->first ) ){
+ it->second.getGroundTerms( s, terms );
+ }
+ }
+}
+
+
+
+ConjectureGenerator::ConjectureGenerator( QuantifiersEngine * qe, context::Context* c ) : QuantifiersModule( qe ),
+d_notify( *this ),
+d_uequalityEngine(d_notify, c, "ConjectureGenerator::ee"),
+d_ee_conjectures( c ){
+ d_fullEffortCount = 0;
+ d_uequalityEngine.addFunctionKind( kind::APPLY_UF );
+ d_uequalityEngine.addFunctionKind( kind::APPLY_CONSTRUCTOR );
+
+}
+
+void ConjectureGenerator::eqNotifyNewClass( TNode t ){
+ Trace("thm-ee-debug") << "UEE : new equivalence class " << t << std::endl;
+ d_upendingAdds.push_back( t );
+}
+
+void ConjectureGenerator::eqNotifyPreMerge(TNode t1, TNode t2) {
+ //get maintained representatives
+ TNode rt1 = t1;
+ TNode rt2 = t2;
+ std::map< Node, EqcInfo* >::iterator it1 = d_eqc_info.find( t1 );
+ if( it1!=d_eqc_info.end() && !it1->second->d_rep.get().isNull() ){
+ rt1 = it1->second->d_rep.get();
+ }
+ std::map< Node, EqcInfo* >::iterator it2 = d_eqc_info.find( t2 );
+ if( it2!=d_eqc_info.end() && !it2->second->d_rep.get().isNull() ){
+ rt2 = it2->second->d_rep.get();
+ }
+ Trace("thm-ee-debug") << "UEE : equality holds : " << t1 << " == " << t2 << std::endl;
+ Trace("thm-ee-debug") << " ureps : " << rt1 << " == " << rt2 << std::endl;
+ Trace("thm-ee-debug") << " normal : " << d_pattern_is_normal[rt1] << " " << d_pattern_is_normal[rt2] << std::endl;
+ Trace("thm-ee-debug") << " size : " << d_pattern_fun_sum[rt1] << " " << d_pattern_fun_sum[rt2] << std::endl;
+
+ if( isUniversalLessThan( rt2, rt1 ) ){
+ EqcInfo * ei;
+ if( it1==d_eqc_info.end() ){
+ ei = getOrMakeEqcInfo( t1, true );
+ }else{
+ ei = it1->second;
+ }
+ ei->d_rep = t2;
+ }
+}
+
+void ConjectureGenerator::eqNotifyPostMerge(TNode t1, TNode t2) {
+
+}
+
+void ConjectureGenerator::eqNotifyDisequal(TNode t1, TNode t2, TNode reason) {
+ Trace("thm-ee-debug") << "UEE : disequality holds : " << t1 << " != " << t2 << std::endl;
+
+}
+
+
+ConjectureGenerator::EqcInfo::EqcInfo( context::Context* c ) : d_rep( c, Node::null() ){
+
+}
+
+ConjectureGenerator::EqcInfo* ConjectureGenerator::getOrMakeEqcInfo( TNode n, bool doMake ) {
+ //Assert( getUniversalRepresentative( n )==n );
+ std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( n );
+ if( eqc_i!=d_eqc_info.end() ){
+ return eqc_i->second;
+ }else if( doMake ){
+ EqcInfo* ei = new EqcInfo( d_quantEngine->getSatContext() );
+ d_eqc_info[n] = ei;
+ return ei;
+ }else{
+ return NULL;
+ }
+}
+
+void ConjectureGenerator::doPendingAddUniversalTerms() {
+ //merge all pending equalities
+ while( !d_upendingAdds.empty() ){
+ Trace("sg-pending") << "Add " << d_upendingAdds.size() << " pending terms..." << std::endl;
+ std::vector< Node > pending;
+ pending.insert( pending.end(), d_upendingAdds.begin(), d_upendingAdds.end() );
+ d_upendingAdds.clear();
+ for( unsigned i=0; i<pending.size(); i++ ){
+ Node t = pending[i];
+ TypeNode tn = t.getType();
+ Trace("thm-ee-add") << "UEE : Add universal term " << t << std::endl;
+ //get all equivalent terms based on theorem database
+ std::vector< Node > eq_terms;
+ d_thm_index.getEquivalentTerms( t, eq_terms );
+ if( !eq_terms.empty() ){
+ Trace("thm-ee-add") << "UEE : Based on theorem database, it is equivalent to " << eq_terms.size() << " terms : " << std::endl;
+ //add equivalent terms as equalities to universal engine
+ for( unsigned i=0; i<eq_terms.size(); i++ ){
+ Trace("thm-ee-add") << " " << eq_terms[i] << std::endl;
+ //if( d_urelevant_terms.find( eq_terms[i] )!=d_urelevant_terms.end() ){
+ bool assertEq = false;
+ if( d_urelevant_terms.find( eq_terms[i] )!=d_urelevant_terms.end() ){
+ assertEq = true;
+ }else{
+ Assert( eq_terms[i].getType()==tn );
+ registerPattern( eq_terms[i], tn );
+ if( isUniversalLessThan( eq_terms[i], t ) ){
+ setUniversalRelevant( eq_terms[i] );
+ assertEq = true;
+ }
+ }
+ if( assertEq ){
+ Node exp;
+ d_uequalityEngine.assertEquality( t.eqNode( eq_terms[i] ), true, exp );
+ }
+ }
+ }else{
+ Trace("thm-ee-add") << "UEE : No equivalent terms." << std::endl;
+ }
+ //if occurs at ground level, merge with representative of ground equality engine
+ /*
+ eq::EqualityEngine * ee = getEqualityEngine();
+ if( ee->hasTerm( t ) ){
+ TNode grt = ee->getRepresentative( t );
+ if( t!=grt ){
+ Node exp;
+ d_uequalityEngine.assertEquality( t.eqNode( grt ), true, exp );
+ }
+ }
+ */
+ }
+ }
+}
+
+void ConjectureGenerator::setUniversalRelevant( TNode n ) {
+ //add pattern information
+ registerPattern( n, n.getType() );
+ d_urelevant_terms[n] = true;
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ setUniversalRelevant( n[i] );
+ }
+}
+
+bool ConjectureGenerator::isUniversalLessThan( TNode rt1, TNode rt2 ) {
+ //prefer the one that is (normal, smaller) lexographically
+ Assert( d_pattern_is_normal.find( rt1 )!=d_pattern_is_normal.end() );
+ Assert( d_pattern_is_normal.find( rt2 )!=d_pattern_is_normal.end() );
+ Assert( d_pattern_fun_sum.find( rt1 )!=d_pattern_fun_sum.end() );
+ Assert( d_pattern_fun_sum.find( rt2 )!=d_pattern_fun_sum.end() );
+
+ if( d_pattern_is_normal[rt1] && !d_pattern_is_normal[rt2] ){
+ Trace("thm-ee-debug") << "UEE : LT due to normal." << std::endl;
+ return true;
+ }else if( d_pattern_is_normal[rt1]==d_pattern_is_normal[rt2] ){
+ if( d_pattern_fun_sum[rt1]<d_pattern_fun_sum[rt2] ){
+ Trace("thm-ee-debug") << "UEE : LT due to size." << std::endl;
+ //decide which representative to use : based on size of the term
+ return true;
+ }else if( d_pattern_fun_sum[rt1]==d_pattern_fun_sum[rt2] ){
+ //same size : tie goes to term that has already been reported
+ return isReportedCanon( rt1 ) && !isReportedCanon( rt2 );
+ }
+ }
+ return false;
+}
+
+
+bool ConjectureGenerator::isReportedCanon( TNode n ) {
+ return std::find( d_ue_canon.begin(), d_ue_canon.end(), n )==d_ue_canon.end();
+}
+
+void ConjectureGenerator::markReportedCanon( TNode n ) {
+ if( !isReportedCanon( n ) ){
+ d_ue_canon.push_back( n );
+ }
+}
+
+bool ConjectureGenerator::areUniversalEqual( TNode n1, TNode n2 ) {
+ return n1==n2 || ( d_uequalityEngine.hasTerm( n1 ) && d_uequalityEngine.hasTerm( n2 ) && d_uequalityEngine.areEqual( n1, n2 ) );
+}
+
+bool ConjectureGenerator::areUniversalDisequal( TNode n1, TNode n2 ) {
+ return n1!=n2 && d_uequalityEngine.hasTerm( n1 ) && d_uequalityEngine.hasTerm( n2 ) && d_uequalityEngine.areDisequal( n1, n2, false );
+}
+
+TNode ConjectureGenerator::getUniversalRepresentative( TNode n, bool add ) {
+ if( add ){
+ if( d_urelevant_terms.find( n )==d_urelevant_terms.end() ){
+ setUniversalRelevant( n );
+ //add term to universal equality engine
+ d_uequalityEngine.addTerm( n );
+ Trace("thm-ee-debug") << "Merge equivalence classes based on terms..." << std::endl;
+ doPendingAddUniversalTerms();
+ }
+ }
+ if( d_uequalityEngine.hasTerm( n ) ){
+ Node r = d_uequalityEngine.getRepresentative( n );
+ EqcInfo * ei = getOrMakeEqcInfo( r );
+ if( ei && !ei->d_rep.get().isNull() ){
+ return ei->d_rep.get();
+ }else{
+ return r;
+ }
+ }else{
+ return n;
+ }
+}
+
+eq::EqualityEngine * ConjectureGenerator::getEqualityEngine() {
+ return d_quantEngine->getTheoryEngine()->getMasterEqualityEngine();
+}
+
+bool ConjectureGenerator::areEqual( TNode n1, TNode n2 ) {
+ eq::EqualityEngine * ee = getEqualityEngine();
+ return n1==n2 || ( ee->hasTerm( n1 ) && ee->hasTerm( n2 ) && ee->areEqual( n1, n2 ) );
+}
+
+bool ConjectureGenerator::areDisequal( TNode n1, TNode n2 ) {
+ eq::EqualityEngine * ee = getEqualityEngine();
+ return n1!=n2 && ee->hasTerm( n1 ) && ee->hasTerm( n2 ) && ee->areDisequal( n1, n2, false );
+}
+
+TNode ConjectureGenerator::getRepresentative( TNode n ) {
+ eq::EqualityEngine * ee = getEqualityEngine();
+ if( ee->hasTerm( n ) ){
+ return ee->getRepresentative( n );
+ }else{
+ return n;
+ }
+}
+
+TermDb * ConjectureGenerator::getTermDatabase() {
+ return d_quantEngine->getTermDatabase();
+}
+
+Node ConjectureGenerator::getFreeVar( TypeNode tn, unsigned i ) {
+ Assert( !tn.isNull() );
+ while( d_free_var[tn].size()<=i ){
+ std::stringstream oss;
+ oss << tn;
+ std::stringstream os;
+ os << oss.str()[0] << i;
+ Node x = NodeManager::currentNM()->mkBoundVar( os.str().c_str(), tn );
+ d_free_var_num[x] = d_free_var[tn].size();
+ d_free_var[tn].push_back( x );
+ }
+ return d_free_var[tn][i];
+}
+
+
+
+Node ConjectureGenerator::getCanonicalTerm( TNode n, std::map< TypeNode, unsigned >& var_count, std::map< TNode, TNode >& subs ) {
+ Trace("ajr-temp") << "get canonical term " << n << " " << n.getKind() << " " << n.hasOperator() << std::endl;
+ if( n.getKind()==BOUND_VARIABLE ){
+ std::map< TNode, TNode >::iterator it = subs.find( n );
+ if( it==subs.end() ){
+ TypeNode tn = n.getType();
+ //allocate variable
+ unsigned vn = var_count[tn];
+ var_count[tn]++;
+ subs[n] = getFreeVar( tn, vn );
+ return subs[n];
+ }else{
+ return it->second;
+ }
+ }else{
+ std::vector< Node > children;
+ if( n.getKind()!=EQUAL ){
+ if( n.hasOperator() ){
+ TNode op = n.getOperator();
+ if( std::find( d_funcs.begin(), d_funcs.end(), op )==d_funcs.end() ){
+ return Node::null();
+ }
+ children.push_back( op );
+ }else{
+ return Node::null();
+ }
+ }
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ Node cn = getCanonicalTerm( n[i], var_count, subs );
+ if( cn.isNull() ){
+ return Node::null();
+ }else{
+ children.push_back( cn );
+ }
+ }
+ return NodeManager::currentNM()->mkNode( n.getKind(), children );
+ }
+}
+
+bool ConjectureGenerator::isHandledTerm( TNode n ){
+ return !n.getAttribute(NoMatchAttribute()) && inst::Trigger::isAtomicTrigger( n ) && ( n.getKind()!=APPLY_UF || n.getOperator().getKind()!=SKOLEM );
+}
+
+Node ConjectureGenerator::getGroundEqc( TNode r ) {
+ std::map< TNode, Node >::iterator it = d_ground_eqc_map.find( r );
+ return it!=d_ground_eqc_map.end() ? it->second : Node::null();
+}
+
+bool ConjectureGenerator::isGroundEqc( TNode r ) {
+ return d_ground_eqc_map.find( r )!=d_ground_eqc_map.end();
+}
+
+bool ConjectureGenerator::isGroundTerm( TNode n ) {
+ return std::find( d_ground_terms.begin(), d_ground_terms.end(), n )!=d_ground_terms.end();
+}
+
+bool ConjectureGenerator::needsCheck( Theory::Effort e ) {
+ return e==Theory::EFFORT_FULL;
+}
+
+void ConjectureGenerator::reset_round( Theory::Effort e ) {
+
+}
+
+void ConjectureGenerator::check( Theory::Effort e, unsigned quant_e ) {
+ if( quant_e==QuantifiersEngine::QEFFORT_STANDARD ){
+ d_fullEffortCount++;
+ if( d_fullEffortCount%optFullCheckFrequency()==0 ){
+ Trace("sg-engine") << "---Conjecture generator, effort = " << e << "--- " << std::endl;
+ eq::EqualityEngine * ee = getEqualityEngine();
+
+ Trace("sg-proc") << "Get eq classes..." << std::endl;
+ d_op_arg_index.clear();
+ d_ground_eqc_map.clear();
+ d_bool_eqc[0] = Node::null();
+ d_bool_eqc[1] = Node::null();
+ std::vector< TNode > eqcs;
+ d_em.clear();
+ eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( ee );
+ while( !eqcs_i.isFinished() ){
+ TNode r = (*eqcs_i);
+ eqcs.push_back( r );
+ if( r.getType().isBoolean() ){
+ if( areEqual( r, getTermDatabase()->d_true ) ){
+ d_ground_eqc_map[r] = getTermDatabase()->d_true;
+ d_bool_eqc[0] = r;
+ }else if( areEqual( r, getTermDatabase()->d_false ) ){
+ d_ground_eqc_map[r] = getTermDatabase()->d_false;
+ d_bool_eqc[1] = r;
+ }
+ }
+ d_em[r] = eqcs.size();
+ eq::EqClassIterator ieqc_i = eq::EqClassIterator( r, ee );
+ while( !ieqc_i.isFinished() ){
+ TNode n = (*ieqc_i);
+ if( isHandledTerm( n ) ){
+ d_op_arg_index[r].addTerm( this, n );
+ }
+ ++ieqc_i;
+ }
+ ++eqcs_i;
+ }
+ Assert( !d_bool_eqc[0].isNull() );
+ Assert( !d_bool_eqc[1].isNull() );
+ d_urelevant_terms.clear();
+ Trace("sg-proc") << "...done get eq classes" << std::endl;
+
+ Trace("sg-proc") << "Determine ground EQC..." << std::endl;
+ bool success;
+ do{
+ success = false;
+ for( unsigned i=0; i<eqcs.size(); i++ ){
+ TNode r = eqcs[i];
+ if( d_ground_eqc_map.find( r )==d_ground_eqc_map.end() ){
+ std::vector< TNode > args;
+ Trace("sg-pat-debug") << "******* Get ground term for " << r << std::endl;
+ Node n;
+ if( getTermDatabase()->isInductionTerm( r ) ){
+ n = d_op_arg_index[r].getGroundTerm( this, args );
+ }else{
+ n = r;
+ }
+ if( !n.isNull() ){
+ Trace("sg-pat") << "Ground term for eqc " << r << " : " << std::endl;
+ Trace("sg-pat") << " " << n << std::endl;
+ d_ground_eqc_map[r] = n;
+ success = true;
+ }else{
+ Trace("sg-pat-debug") << "...could not find ground term." << std::endl;
+ }
+ }
+ }
+ }while( success );
+ //also get ground terms
+ d_ground_terms.clear();
+ for( unsigned i=0; i<eqcs.size(); i++ ){
+ TNode r = eqcs[i];
+ d_op_arg_index[r].getGroundTerms( this, d_ground_terms );
+ }
+ Trace("sg-proc") << "...done determine ground EQC" << std::endl;
+
+ //debug printing
+ if( Trace.isOn("sg-gen-eqc") ){
+ for( unsigned i=0; i<eqcs.size(); i++ ){
+ TNode r = eqcs[i];
+ //print out members
+ bool firstTime = true;
+ bool isFalse = areEqual( r, getTermDatabase()->d_false );
+ eq::EqClassIterator eqc_i = eq::EqClassIterator( r, ee );
+ while( !eqc_i.isFinished() ){
+ TNode n = (*eqc_i);
+ if( !n.getAttribute(NoMatchAttribute()) && ( n.getKind()!=EQUAL || isFalse ) ){
+ if( firstTime ){
+ Trace("sg-gen-eqc") << "e" << d_em[r] << " : { " << std::endl;
+ firstTime = false;
+ }
+ if( n.hasOperator() ){
+ Trace("sg-gen-eqc") << " (" << n.getOperator();
+ getTermDatabase()->computeArgReps( n );
+ for( unsigned i=0; i<getTermDatabase()->d_arg_reps[n].size(); i++ ){
+ Trace("sg-gen-eqc") << " e" << d_em[getTermDatabase()->d_arg_reps[n][i]];
+ }
+ Trace("sg-gen-eqc") << ") :: " << n << std::endl;
+ }else{
+ Trace("sg-gen-eqc") << " " << n << std::endl;
+ }
+ }
+ ++eqc_i;
+ }
+ if( !firstTime ){
+ Trace("sg-gen-eqc") << "}" << std::endl;
+ //print out ground term
+ std::map< TNode, Node >::iterator it = d_ground_eqc_map.find( r );
+ if( it!=d_ground_eqc_map.end() ){
+ Trace("sg-gen-eqc") << "- Ground term : " << it->second << std::endl;
+ }
+ }
+ }
+ }
+
+ Trace("sg-proc") << "Compute relevant eqc..." << std::endl;
+ d_relevant_eqc[0].clear();
+ d_relevant_eqc[1].clear();
+ for( unsigned i=0; i<eqcs.size(); i++ ){
+ TNode r = eqcs[i];
+ std::map< TNode, Node >::iterator it = d_ground_eqc_map.find( r );
+ unsigned index = 1;
+ if( it==d_ground_eqc_map.end() ){
+ index = 0;
+ }
+ //based on unproven conjectures? TODO
+ d_relevant_eqc[index].push_back( r );
+ }
+ Trace("sg-gen-tg-debug") << "Initial relevant eqc : ";
+ for( unsigned i=0; i<d_relevant_eqc[0].size(); i++ ){
+ Trace("sg-gen-tg-debug") << "e" << d_em[d_relevant_eqc[0][i]] << " ";
+ }
+ Trace("sg-gen-tg-debug") << std::endl;
+ Trace("sg-proc") << "...done compute relevant eqc" << std::endl;
+
+
+ Trace("sg-proc") << "Collect signature information..." << std::endl;
+ d_funcs.clear();
+ d_typ_funcs.clear();
+ d_func_kind.clear();
+ d_func_args.clear();
+ TypeNode tnull;
+ for( std::map< Node, TermArgTrie >::iterator it = getTermDatabase()->d_func_map_trie.begin(); it != getTermDatabase()->d_func_map_trie.end(); ++it ){
+ if( !getTermDatabase()->d_op_map[it->first].empty() ){
+ Node nn = getTermDatabase()->d_op_map[it->first][0];
+ if( isHandledTerm( nn ) && nn.getKind()!=APPLY_SELECTOR_TOTAL && !nn.getType().isBoolean() ){
+ d_funcs.push_back( it->first );
+ d_typ_funcs[tnull].push_back( it->first );
+ d_typ_funcs[nn.getType()].push_back( it->first );
+ for( unsigned i=0; i<nn.getNumChildren(); i++ ){
+ d_func_args[it->first].push_back( nn[i].getType() );
+ }
+ d_func_kind[it->first] = nn.getKind();
+ Trace("sg-rel-sig") << "Will enumerate function applications of : " << it->first << ", #args = " << d_func_args[it->first].size() << ", kind = " << nn.getKind() << std::endl;
+ getTermDatabase()->computeUfEqcTerms( it->first );
+ }
+ }
+ }
+ //shuffle functions
+ for( std::map< TypeNode, std::vector< TNode > >::iterator it = d_typ_funcs.begin(); it !=d_typ_funcs.end(); ++it ){
+ std::random_shuffle( it->second.begin(), it->second.end() );
+ if( it->first.isNull() ){
+ Trace("sg-gen-tg-debug") << "In this order : ";
+ for( unsigned i=0; i<it->second.size(); i++ ){
+ Trace("sg-gen-tg-debug") << it->second[i] << " ";
+ }
+ Trace("sg-gen-tg-debug") << std::endl;
+ }
+ }
+ Trace("sg-proc") << "...done collect signature information" << std::endl;
+
+
+ Trace("sg-proc") << "Build theorem index..." << std::endl;
+ d_ue_canon.clear();
+ d_thm_index.clear();
+ std::vector< Node > provenConj;
+ quantifiers::FirstOrderModel* m = d_quantEngine->getModel();
+ for( int i=0; i<m->getNumAssertedQuantifiers(); i++ ){
+ Node q = m->getAssertedQuantifier( i );
+ Trace("thm-db-debug") << "Is " << q << " a relevant theorem?" << std::endl;
+ Node conjEq;
+ if( q[1].getKind()==EQUAL ){
+ bool isSubsume = false;
+ bool inEe = false;
+ for( unsigned r=0; r<2; r++ ){
+ TNode nl = q[1][r==0 ? 0 : 1];
+ TNode nr = q[1][r==0 ? 1 : 0];
+ Node eq = nl.eqNode( nr );
+ if( r==1 || std::find( d_conjectures.begin(), d_conjectures.end(), q )==d_conjectures.end() ){
+ //must make it canonical
+ std::map< TypeNode, unsigned > var_count;
+ std::map< TNode, TNode > subs;
+ Trace("sg-proc-debug") << "get canonical " << eq << std::endl;
+ eq = getCanonicalTerm( eq, var_count, subs );
+ }
+ if( !eq.isNull() ){
+ if( r==0 ){
+ inEe = d_ee_conjectures.find( q[1] )!=d_ee_conjectures.end();
+ if( !inEe ){
+ //add to universal equality engine
+ Node nl = getUniversalRepresentative( eq[0], true );
+ Node nr = getUniversalRepresentative( eq[1], true );
+ if( areUniversalEqual( nl, nr ) ){
+ isSubsume = true;
+ //set inactive (will be ignored by other modules)
+ d_quantEngine->getModel()->setQuantifierActive( q, false );
+ }else{
+ Node exp;
+ d_ee_conjectures[q[1]] = true;
+ d_uequalityEngine.assertEquality( nl.eqNode( nr ), true, exp );
+ }
+ }
+ Trace("sg-conjecture") << "*** CONJECTURE : currently proven" << (isSubsume ? " and subsumed" : "");
+ Trace("sg-conjecture") << " : " << q[1] << std::endl;
+ provenConj.push_back( q );
+ }
+ if( !isSubsume ){
+ Trace("thm-db-debug") << "Adding theorem to database " << eq[0] << " == " << eq[1] << std::endl;
+ d_thm_index.addTheorem( eq[0], eq[1] );
+ }else{
+ break;
+ }
+ }else{
+ break;
+ }
+ }
+ }
+ }
+ //examine status of other conjectures
+ for( unsigned i=0; i<d_conjectures.size(); i++ ){
+ Node q = d_conjectures[i];
+ if( std::find( provenConj.begin(), provenConj.end(), q )==provenConj.end() ){
+ //check each skolem variable
+ bool disproven = true;
+ //std::vector< Node > sk;
+ //getTermDatabase()->getSkolemConstants( q, sk, true );
+ Trace("sg-conjecture") << " CONJECTURE : ";
+ std::vector< Node > ce;
+ for( unsigned j=0; j<getTermDatabase()->d_skolem_constants[q].size(); j++ ){
+ TNode k = getTermDatabase()->d_skolem_constants[q][j];
+ TNode rk = getRepresentative( k );
+ std::map< TNode, Node >::iterator git = d_ground_eqc_map.find( rk );
+ //check if it is a ground term
+ if( git==d_ground_eqc_map.end() ){
+ Trace("sg-conjecture") << "ACTIVE : " << q;
+ if( Trace.isOn("sg-gen-eqc") ){
+ Trace("sg-conjecture") << " { ";
+ for( unsigned k=0; k<getTermDatabase()->d_skolem_constants[q].size(); k++ ){ Trace("sg-conjecture") << getTermDatabase()->d_skolem_constants[q][k] << ( j==k ? "*" : "" ) << " "; }
+ Trace("sg-conjecture") << "}";
+ }
+ Trace("sg-conjecture") << std::endl;
+ disproven = false;
+ break;
+ }else{
+ ce.push_back( git->second );
+ }
+ }
+ if( disproven ){
+ Trace("sg-conjecture") << "disproven : " << q << " : ";
+ for( unsigned i=0; i<ce.size(); i++ ){
+ Trace("sg-conjecture") << q[0][i] << " -> " << ce[i] << " ";
+ }
+ Trace("sg-conjecture") << std::endl;
+ }
+ }
+ }
+ Trace("thm-db") << "Theorem database is : " << std::endl;
+ d_thm_index.debugPrint( "thm-db" );
+ Trace("thm-db") << std::endl;
+ Trace("sg-proc") << "...done build theorem index" << std::endl;
+
+ //clear patterns
+ d_patterns.clear();
+ d_pattern_var_id.clear();
+ d_pattern_var_duplicate.clear();
+ d_pattern_is_normal.clear();
+ d_pattern_fun_id.clear();
+ d_pattern_fun_sum.clear();
+ d_rel_patterns.clear();
+ d_rel_pattern_var_sum.clear();
+ d_rel_pattern_typ_index.clear();
+ d_rel_pattern_subs_index.clear();
+ d_gen_lat_maximal.clear();
+ d_gen_lat_child.clear();
+ d_gen_lat_parent.clear();
+ d_gen_depth.clear();
+
+ //the following generates a set of relevant terms
+ d_use_ccand_eqc = true;
+ for( unsigned i=0; i<2; i++ ){
+ d_ccand_eqc[i].clear();
+ d_ccand_eqc[i].push_back( d_relevant_eqc[i] );
+ }
+ d_rel_term_count = 0;
+ //consider all functions
+ d_typ_tg_funcs.clear();
+ for( std::map< TypeNode, std::vector< TNode > >::iterator it = d_typ_funcs.begin(); it != d_typ_funcs.end(); ++it ){
+ d_typ_tg_funcs[it->first].insert( d_typ_tg_funcs[it->first].end(), it->second.begin(), it->second.end() );
+ }
+ std::map< TypeNode, unsigned > rt_var_max;
+ std::vector< TypeNode > rt_types;
+ //map from generalization depth to maximum depth
+ //std::map< unsigned, unsigned > gdepth_to_tdepth;
+ for( unsigned depth=1; depth<3; depth++ ){
+ Assert( d_tg_alloc.empty() );
+ Trace("sg-proc") << "Generate terms at depth " << depth << "..." << std::endl;
+ Trace("sg-rel-term") << "Relevant terms of depth " << depth << " : " << std::endl;
+ //set up environment
+ d_var_id.clear();
+ d_var_limit.clear();
+ d_tg_id = 0;
+ d_tg_gdepth = 0;
+ d_tg_gdepth_limit = -1;
+ //consider all types
+ d_tg_alloc[0].reset( this, TypeNode::null() );
+ while( d_tg_alloc[0].getNextTerm( this, depth ) ){
+ Assert( d_tg_alloc[0].getGeneralizationDepth( this )==d_tg_gdepth );
+ if( d_tg_alloc[0].getDepth( this )==depth ){
+ //construct term
+ Node nn = d_tg_alloc[0].getTerm( this );
+ if( getUniversalRepresentative( nn )==nn ){
+ d_rel_term_count++;
+ Trace("sg-rel-term") << "*** Relevant term : ";
+ d_tg_alloc[0].debugPrint( this, "sg-rel-term", "sg-rel-term-debug2" );
+ Trace("sg-rel-term") << std::endl;
+
+ for( unsigned r=0; r<2; r++ ){
+ Trace("sg-gen-tg-eqc") << "...from equivalence classes (" << r << ") : ";
+ int index = d_ccand_eqc[r].size()-1;
+ for( unsigned j=0; j<d_ccand_eqc[r][index].size(); j++ ){
+ Trace("sg-gen-tg-eqc") << "e" << d_em[d_ccand_eqc[r][index][j]] << " ";
+ }
+ Trace("sg-gen-tg-eqc") << std::endl;
+ }
+ TypeNode tnn = nn.getType();
+ Trace("sg-gen-tg-debug") << "...term is " << nn << std::endl;
+ Assert( getUniversalRepresentative( nn )==nn );
+
+ //add information about pattern
+ Trace("sg-gen-tg-debug") << "Collect pattern information..." << std::endl;
+ Assert( std::find( d_rel_patterns[tnn].begin(), d_rel_patterns[tnn].end(), nn )==d_rel_patterns[tnn].end() );
+ d_rel_patterns[tnn].push_back( nn );
+ //build information concerning the variables in this pattern
+ unsigned sum = 0;
+ std::map< TypeNode, unsigned > typ_to_subs_index;
+ std::vector< TNode > gsubs_vars;
+ for( std::map< TypeNode, unsigned >::iterator it = d_var_id.begin(); it != d_var_id.end(); ++it ){
+ if( it->second>0 ){
+ typ_to_subs_index[it->first] = sum;
+ sum += it->second;
+ for( unsigned i=0; i<it->second; i++ ){
+ gsubs_vars.push_back( getFreeVar( it->first, i ) );
+ }
+ }
+ }
+ d_rel_pattern_var_sum[nn] = sum;
+ //register the pattern
+ registerPattern( nn, tnn );
+ Assert( d_pattern_is_normal[nn] );
+ Trace("sg-gen-tg-debug") << "...done collect pattern information" << std::endl;
+
+ //compute generalization relation
+ Trace("sg-gen-tg-debug") << "Build generalization information..." << std::endl;
+ std::map< TNode, bool > patProc;
+ int maxGenDepth = -1;
+ unsigned i = d_rel_patterns[tnn].size()-1;
+ for( int j=(int)(i-1); j>=0; j-- ){
+ TNode np = d_rel_patterns[tnn][j];
+ if( patProc.find( np )==patProc.end() ){
+ Trace("sg-gen-tg-debug2") << "Check if generalized by " << np << "..." << std::endl;
+ if( isGeneralization( np, nn ) ){
+ Trace("sg-rel-terms-debug") << " is generalized by : " << np << std::endl;
+ d_gen_lat_child[np].push_back( nn );
+ d_gen_lat_parent[nn].push_back( np );
+ if( d_gen_depth[np]>maxGenDepth ){
+ maxGenDepth = d_gen_depth[np];
+ }
+ //don't consider the transitive closure of generalizes
+ Trace("sg-gen-tg-debug2") << "Add generalizations" << std::endl;
+ addGeneralizationsOf( np, patProc );
+ Trace("sg-gen-tg-debug2") << "Done add generalizations" << std::endl;
+ }else{
+ Trace("sg-gen-tg-debug2") << " is not generalized by : " << np << std::endl;
+ }
+ }
+ }
+ if( d_gen_lat_parent[nn].empty() ){
+ d_gen_lat_maximal[tnn].push_back( nn );
+ }
+ d_gen_depth[nn] = maxGenDepth+1;
+ Trace("sg-rel-term-debug") << " -> generalization depth is " << d_gen_depth[nn] << " <> " << depth << std::endl;
+ Trace("sg-gen-tg-debug") << "...done build generalization information" << std::endl;
+
+ //record information about types
+ Trace("sg-gen-tg-debug") << "Collect type information..." << std::endl;
+ PatternTypIndex * pti = &d_rel_pattern_typ_index;
+ for( std::map< TypeNode, unsigned >::iterator it = d_var_id.begin(); it != d_var_id.end(); ++it ){
+ pti = &pti->d_children[it->first][it->second];
+ //record maximum
+ if( rt_var_max.find( it->first )==rt_var_max.end() || it->second>rt_var_max[it->first] ){
+ rt_var_max[it->first] = it->second;
+ }
+ }
+ if( std::find( rt_types.begin(), rt_types.end(), tnn )==rt_types.end() ){
+ rt_types.push_back( tnn );
+ }
+ pti->d_terms.push_back( nn );
+ Trace("sg-gen-tg-debug") << "...done collect type information" << std::endl;
+
+ Trace("sg-gen-tg-debug") << "Build substitutions for ground EQC..." << std::endl;
+ std::vector< TNode > gsubs_terms;
+ gsubs_terms.resize( gsubs_vars.size() );
+ int index = d_ccand_eqc[1].size()-1;
+ for( unsigned j=0; j<d_ccand_eqc[1][index].size(); j++ ){
+ TNode r = d_ccand_eqc[1][index][j];
+ Trace("sg-gen-tg-eqc") << " Matches for e" << d_em[r] << ", which is ground term " << d_ground_eqc_map[r] << ":" << std::endl;
+ std::map< TypeNode, std::map< unsigned, TNode > > subs;
+ std::map< TNode, bool > rev_subs;
+ //only get ground terms
+ unsigned mode = optFilterConfirmationOnlyGround() ? 2 : 0;
+ d_tg_alloc[0].resetMatching( this, r, mode );
+ while( d_tg_alloc[0].getNextMatch( this, r, subs, rev_subs ) ){
+ //we will be building substitutions
+ bool firstTime = true;
+ for( std::map< TypeNode, std::map< unsigned, TNode > >::iterator it = subs.begin(); it != subs.end(); ++it ){
+ unsigned tindex = typ_to_subs_index[it->first];
+ for( std::map< unsigned, TNode >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ){
+ if( !firstTime ){
+ Trace("sg-gen-tg-eqc") << ", ";
+ }else{
+ firstTime = false;
+ Trace("sg-gen-tg-eqc") << " ";
+ }
+ Trace("sg-gen-tg-eqc") << it->first << ":x" << it2->first << " -> " << it2->second;
+ Assert( tindex+it2->first<gsubs_terms.size() );
+ gsubs_terms[tindex+it2->first] = it2->second;
+ }
+ }
+ Trace("sg-gen-tg-eqc") << std::endl;
+ d_rel_pattern_subs_index[nn].addSubstitution( r, gsubs_vars, gsubs_terms );
+ }
+ }
+ Trace("sg-gen-tg-debug") << "...done build substitutions for ground EQC" << std::endl;
+ }else{
+ Trace("sg-gen-tg-debug") << "> not canonical : " << nn << std::endl;
+ }
+ }else{
+ Trace("sg-gen-tg-debug") << "> produced term at previous depth : ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-tg-debug", "sg-gen-tg-debug" );
+ Trace("sg-gen-tg-debug") << std::endl;
+ }
+ }
+ Trace("sg-proc") << "...done generate terms at depth " << depth << std::endl;
+
+
+ //now generate right hand sides
+
+
+ }
+ Trace("sg-stats") << "--------> Total relevant patterns : " << d_rel_term_count << std::endl;
+
+ Trace("sg-proc") << "Generate properties..." << std::endl;
+ //set up environment
+ d_use_ccand_eqc = false;
+ d_var_id.clear();
+ d_var_limit.clear();
+ for( std::map< TypeNode, unsigned >::iterator it = rt_var_max.begin(); it != rt_var_max.end(); ++it ){
+ d_var_id[ it->first ] = it->second;
+ d_var_limit[ it->first ] = it->second;
+ }
+ //set up environment for candidate conjectures
+ d_cconj_at_depth.clear();
+ for( unsigned i=0; i<2; i++ ){
+ d_cconj[i].clear();
+ }
+ d_cconj_rhs_paired.clear();
+ unsigned totalCount = 0;
+ for( unsigned depth=0; depth<5; depth++ ){
+ //consider types from relevant terms
+ std::random_shuffle( rt_types.begin(), rt_types.end() );
+ for( unsigned i=0; i<rt_types.size(); i++ ){
+ Assert( d_tg_alloc.empty() );
+ Trace("sg-proc") << "Generate relevant RHS terms of type " << rt_types[i] << " at depth " << depth << "..." << std::endl;
+ d_tg_id = 0;
+ d_tg_alloc[0].reset( this, rt_types[i] );
+ while( d_tg_alloc[0].getNextTerm( this, depth ) && totalCount<100 ){
+ if( d_tg_alloc[0].getDepth( this )==depth ){
+ Node rhs = d_tg_alloc[0].getTerm( this );
+ Trace("sg-rel-prop") << "Relevant RHS : " << rhs << std::endl;
+ //register pattern
+ Assert( rhs.getType()==rt_types[i] );
+ registerPattern( rhs, rt_types[i] );
+ //for each maximal node of type rt_types[i] in generalization lattice
+ for( unsigned j=0; j<d_gen_lat_maximal[rt_types[i]].size(); j++ ){
+ //add candidate conjecture
+ addCandidateConjecture( d_gen_lat_maximal[rt_types[i]][j], rhs, 0 );
+ }
+ totalCount++;
+ }
+ }
+ //could have been partial, we must clear
+ d_tg_alloc.clear();
+ }
+ Trace("sg-proc") << "Process candidate conjectures up to RHS term depth " << depth << "..." << std::endl;
+ for( unsigned conj_depth=0; conj_depth<depth; conj_depth++ ){
+ //process all conjectures waiting at depth
+ unsigned sz = d_cconj_at_depth[conj_depth].size();
+ for( int i=(int)(sz-1); i>=0; i-- ){
+ processCandidateConjecture( d_cconj_at_depth[conj_depth][i], conj_depth );
+ }
+ Assert( d_cconj_at_depth[conj_depth].size()==sz );
+ d_cconj_at_depth[conj_depth].clear();
+ }
+ Trace("sg-proc") << "...done process candidate conjectures at RHS term depth " << depth << std::endl;
+ }
+ Trace("sg-proc") << "...done generate properties" << std::endl;
+
+ if( !d_waiting_conjectures.empty() ){
+ Trace("sg-proc") << "Generated " << d_waiting_conjectures.size() << " conjectures." << std::endl;
+ d_conjectures.insert( d_conjectures.end(), d_waiting_conjectures.begin(), d_waiting_conjectures.end() );
+ for( unsigned i=0; i<d_waiting_conjectures.size(); i++ ){
+ Assert( d_waiting_conjectures[i].getKind()==FORALL );
+ Node lem = NodeManager::currentNM()->mkNode( OR, d_waiting_conjectures[i].negate(), d_waiting_conjectures[i] );
+ d_quantEngine->addLemma( lem, false );
+ d_quantEngine->addRequirePhase( d_waiting_conjectures[i], false );
+ }
+ d_waiting_conjectures.clear();
+ }
+
+ Trace("thm-ee") << "Universal equality engine is : " << std::endl;
+ eq::EqClassesIterator ueqcs_i = eq::EqClassesIterator( &d_uequalityEngine );
+ while( !ueqcs_i.isFinished() ){
+ TNode r = (*ueqcs_i);
+ bool firstTime = true;
+ TNode rr = getUniversalRepresentative( r );
+ Trace("thm-ee") << " " << r;
+ if( rr!=r ){ Trace("thm-ee") << " [" << rr << "]"; }
+ Trace("thm-ee") << " : { ";
+ eq::EqClassIterator ueqc_i = eq::EqClassIterator( r, &d_uequalityEngine );
+ while( !ueqc_i.isFinished() ){
+ TNode n = (*ueqc_i);
+ if( r!=n ){
+ if( firstTime ){
+ Trace("thm-ee") << std::endl;
+ firstTime = false;
+ }
+ Trace("thm-ee") << " " << n << std::endl;
+ }
+ ++ueqc_i;
+ }
+ if( !firstTime ){ Trace("thm-ee") << " "; }
+ Trace("thm-ee") << "}" << std::endl;
+ ++ueqcs_i;
+ }
+ Trace("thm-ee") << std::endl;
+ }
+ }
+}
+
+void ConjectureGenerator::registerQuantifier( Node q ) {
+
+}
+
+void ConjectureGenerator::assertNode( Node n ) {
+
+}
+
+
+unsigned ConjectureGenerator::getNumTgVars( TypeNode tn ) {
+ //return d_var_tg.size();
+ return d_var_id[tn];
+}
+
+bool ConjectureGenerator::allowVar( TypeNode tn ) {
+ std::map< TypeNode, unsigned >::iterator it = d_var_limit.find( tn );
+ if( it==d_var_limit.end() ){
+ return true;
+ }else{
+ return d_var_id[tn]<it->second;
+ }
+}
+
+void ConjectureGenerator::addVar( TypeNode tn ) {
+ //d_var_tg.push_back( v );
+ d_var_id[tn]++;
+ //d_var_eq_tg.push_back( std::vector< unsigned >() );
+}
+
+void ConjectureGenerator::removeVar( TypeNode tn ) {
+ d_var_id[tn]--;
+ //d_var_eq_tg.pop_back();
+ //d_var_tg.pop_back();
+}
+
+unsigned ConjectureGenerator::getNumTgFuncs( TypeNode tn ) {
+ return d_typ_tg_funcs[tn].size();
+}
+
+TNode ConjectureGenerator::getTgFunc( TypeNode tn, unsigned i ) {
+ return d_typ_tg_funcs[tn][i];
+}
+
+bool ConjectureGenerator::considerCurrentTerm() {
+ Assert( !d_tg_alloc.empty() );
+
+ //if generalization depth is too large, don't consider it
+ unsigned i = d_tg_alloc.size();
+ Trace("sg-gen-tg-debug") << "Consider term ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-tg-debug", "sg-gen-tg-debug" );
+ Trace("sg-gen-tg-debug") << "? curr term size = " << d_tg_alloc.size() << ", last status = " << d_tg_alloc[i-1].d_status;
+ Trace("sg-gen-tg-debug") << std::endl;
+
+ Assert( d_tg_alloc[0].getGeneralizationDepth( this )==d_tg_gdepth );
+
+ if( d_tg_gdepth_limit>=0 && d_tg_gdepth>(unsigned)d_tg_gdepth_limit ){
+ Trace("sg-gen-consider-term") << "-> generalization depth of ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-consider-term", "sg-gen-tg-debug" );
+ Trace("sg-gen-consider-term") << " is too high " << d_tg_gdepth << " " << d_tg_alloc[0].getGeneralizationDepth( this ) << ", do not consider." << std::endl;
+ return false;
+ }
+
+ //----optimizations
+ if( d_tg_alloc[i-1].d_status==1 ){
+ }else if( d_tg_alloc[i-1].d_status==2 ){
+ }else if( d_tg_alloc[i-1].d_status==5 ){
+ }else{
+ Trace("sg-gen-tg-debug") << "Bad tg: " << &d_tg_alloc[i-1] << std::endl;
+ Assert( false );
+ }
+ //if equated two variables, first check if context-independent TODO
+ //----end optimizations
+
+
+ //check based on which candidate equivalence classes match
+ if( d_use_ccand_eqc ){
+ Trace("sg-gen-tg-debug") << "Filter based on relevant ground EQC";
+ Trace("sg-gen-tg-debug") << ", #eqc to try = " << d_ccand_eqc[0][i-1].size() << "/" << d_ccand_eqc[1][i-1].size() << std::endl;
+
+ Assert( d_ccand_eqc[0].size()>=2 );
+ Assert( d_ccand_eqc[0].size()==d_ccand_eqc[1].size() );
+ Assert( d_ccand_eqc[0].size()==d_tg_id+1 );
+ Assert( d_tg_id==d_tg_alloc.size() );
+ for( unsigned r=0; r<2; r++ ){
+ d_ccand_eqc[r][i].clear();
+ }
+
+ //re-check feasibility of EQC
+ for( unsigned r=0; r<2; r++ ){
+ for( unsigned j=0; j<d_ccand_eqc[r][i-1].size(); j++ ){
+ std::map< TypeNode, std::map< unsigned, TNode > > subs;
+ std::map< TNode, bool > rev_subs;
+ unsigned mode;
+ if( r==0 ){
+ mode = optReqDistinctVarPatterns() ? 1 : 0;
+ }else{
+ mode = (optFilterConfirmation() && optFilterConfirmationOnlyGround() ) ? 2 : 0;
+ }
+ d_tg_alloc[0].resetMatching( this, d_ccand_eqc[r][i-1][j], mode );
+ if( d_tg_alloc[0].getNextMatch( this, d_ccand_eqc[r][i-1][j], subs, rev_subs ) ){
+ d_ccand_eqc[r][i].push_back( d_ccand_eqc[r][i-1][j] );
+ }
+ }
+ }
+ for( unsigned r=0; r<2; r++ ){
+ Trace("sg-gen-tg-debug") << "Current eqc of type " << r << " : ";
+ for( unsigned j=0; j<d_ccand_eqc[r][i].size(); j++ ){
+ Trace("sg-gen-tg-debug") << "e" << d_em[d_ccand_eqc[r][i][j]] << " ";
+ }
+ Trace("sg-gen-tg-debug") << std::endl;
+ }
+ if( d_ccand_eqc[0][i].empty() ){
+ Trace("sg-gen-consider-term") << "Do not consider term of form ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-consider-term", "sg-gen-consider-term-debug" );
+ Trace("sg-gen-consider-term") << " since no relevant EQC matches it." << std::endl;
+ return false;
+ }
+ if( d_ccand_eqc[1][i].empty() && optFilterConfirmation() ){
+ Trace("sg-gen-consider-term") << "Do not consider term of form ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-consider-term", "sg-gen-consider-term-debug" );
+ Trace("sg-gen-consider-term") << " since no ground EQC matches it." << std::endl;
+ return false;
+ }
+ }
+ Trace("sg-gen-tg-debug") << "Will consider term ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-tg-debug", "sg-gen-tg-debug" );
+ Trace("sg-gen-tg-debug") << std::endl;
+ Trace("sg-gen-consider-term-debug") << std::endl;
+ return true;
+}
+
+bool ConjectureGenerator::considerTermCanon( unsigned tg_id ){
+ Assert( tg_id<d_tg_alloc.size() );
+ //check based on a canonicity of the term (if there is one)
+ Trace("sg-gen-tg-debug") << "Consider term canon ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-tg-debug", "sg-gen-tg-debug" );
+ Trace("sg-gen-tg-debug") << ", tg is [" << tg_id << "]..." << std::endl;
+
+ Node ln = d_tg_alloc[tg_id].getTerm( this );
+ Trace("sg-gen-tg-debug") << "Term is " << ln << std::endl;
+ if( !ln.isNull() ){
+ //do not consider if it is non-canonical, and either:
+ // (1) we are not filtering based on matching candidate eqc, or
+ // (2) its canonical form is a generalization.
+ TNode lnr = getUniversalRepresentative( ln, true );
+ if( lnr==ln ){
+ markReportedCanon( ln );
+ }else if( !d_use_ccand_eqc || isGeneralization( lnr, ln ) ){
+ Trace("sg-gen-consider-term") << "Do not consider term of form ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-consider-term", "sg-gen-consider-term-debug" );
+ Trace("sg-gen-consider-term") << " since sub-term " << ln << " is not canonical representation (which is " << lnr << ")." << std::endl;
+ return false;
+ }
+ }
+ Trace("sg-gen-tg-debug") << "Will consider term canon ";
+ d_tg_alloc[0].debugPrint( this, "sg-gen-tg-debug", "sg-gen-tg-debug" );
+ Trace("sg-gen-tg-debug") << std::endl;
+ Trace("sg-gen-consider-term-debug") << std::endl;
+ return true;
+}
+
+void ConjectureGenerator::changeContext( bool add ) {
+ if( add ){
+ for( unsigned r=0; r<2; r++ ){
+ d_ccand_eqc[r].push_back( std::vector< TNode >() );
+ }
+ d_tg_id++;
+ }else{
+ for( unsigned r=0; r<2; r++ ){
+ d_ccand_eqc[r].pop_back();
+ }
+ d_tg_id--;
+ Assert( d_tg_alloc.find( d_tg_id )!=d_tg_alloc.end() );
+ d_tg_alloc.erase( d_tg_id );
+ }
+}
+
+unsigned ConjectureGenerator::collectFunctions( TNode opat, TNode pat, std::map< TNode, unsigned >& funcs,
+ std::map< TypeNode, unsigned >& mnvn, std::map< TypeNode, unsigned >& mxvn ){
+ if( pat.hasOperator() ){
+ funcs[pat.getOperator()]++;
+ unsigned sum = 1;
+ for( unsigned i=0; i<pat.getNumChildren(); i++ ){
+ sum += collectFunctions( opat, pat[i], funcs, mnvn, mxvn );
+ }
+ return sum;
+ }else{
+ Assert( pat.getNumChildren()==0 );
+ funcs[pat]++;
+ //for variables
+ if( pat.getKind()==BOUND_VARIABLE ){
+ if( funcs[pat]>1 ){
+ //duplicate variable
+ d_pattern_var_duplicate[opat]++;
+ }else{
+ //check for max/min
+ TypeNode tn = pat.getType();
+ unsigned vn = d_free_var_num[pat];
+ std::map< TypeNode, unsigned >::iterator it = mnvn.find( tn );
+ if( it!=mnvn.end() ){
+ if( vn<it->second ){
+ d_pattern_is_normal[opat] = false;
+ mnvn[tn] = vn;
+ }else if( vn>mxvn[tn] ){
+ if( vn!=mxvn[tn]+1 ){
+ d_pattern_is_normal[opat] = false;
+ }
+ mxvn[tn] = vn;
+ }
+ }else{
+ //first variable of this type
+ mnvn[tn] = vn;
+ mxvn[tn] = vn;
+ }
+ }
+ }
+ return 1;
+ }
+}
+
+void ConjectureGenerator::registerPattern( Node pat, TypeNode tpat ) {
+ if( std::find( d_patterns[tpat].begin(), d_patterns[tpat].end(), pat )==d_patterns[tpat].end() ){
+ d_patterns[TypeNode::null()].push_back( pat );
+ d_patterns[tpat].push_back( pat );
+
+ Assert( d_pattern_fun_id.find( pat )==d_pattern_fun_id.end() );
+ Assert( d_pattern_var_id.find( pat )==d_pattern_var_id.end() );
+
+ //collect functions
+ std::map< TypeNode, unsigned > mnvn;
+ d_pattern_fun_sum[pat] = collectFunctions( pat, pat, d_pattern_fun_id[pat], mnvn, d_pattern_var_id[pat] );
+ if( d_pattern_is_normal.find( pat )==d_pattern_is_normal.end() ){
+ d_pattern_is_normal[pat] = true;
+ }
+ }
+}
+
+bool ConjectureGenerator::isGeneralization( TNode patg, TNode pat, std::map< TNode, TNode >& subs ) {
+ if( patg.getKind()==BOUND_VARIABLE ){
+ std::map< TNode, TNode >::iterator it = subs.find( patg );
+ if( it!=subs.end() ){
+ return it->second==pat;
+ }else{
+ subs[patg] = pat;
+ return true;
+ }
+ }else{
+ Assert( patg.hasOperator() );
+ if( !pat.hasOperator() || patg.getOperator()!=pat.getOperator() ){
+ return false;
+ }else{
+ Assert( patg.getNumChildren()==pat.getNumChildren() );
+ for( unsigned i=0; i<patg.getNumChildren(); i++ ){
+ if( !isGeneralization( patg[i], pat[i], subs ) ){
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+}
+
+void ConjectureGenerator::addGeneralizationsOf( TNode pat, std::map< TNode, bool >& patProc ) {
+ patProc[pat] = true;
+ for( unsigned k=0; k<d_gen_lat_parent[pat].size(); k++ ){
+ addGeneralizationsOf( d_gen_lat_parent[pat][k], patProc );
+ }
+}
+
+void ConjectureGenerator::addCandidateConjecture( TNode lhs, TNode rhs, unsigned depth ) {
+ if( std::find( d_cconj_rhs_paired[rhs].begin(), d_cconj_rhs_paired[rhs].end(), lhs )==d_cconj_rhs_paired[rhs].end() ){
+ //add conjecture to list to process
+ d_cconj_at_depth[depth].push_back( d_cconj[0].size() );
+ //define conjecture
+ d_cconj[0].push_back( lhs );
+ d_cconj[1].push_back( rhs );
+ d_cconj_rhs_paired[rhs].push_back( lhs );
+ }
+}
+
+void ConjectureGenerator::processCandidateConjecture( unsigned cid, unsigned depth ) {
+ if( d_waiting_conjectures.size()>=optFullCheckConjectures() ){
+ return;
+ }
+ TNode lhs = d_cconj[0][cid];
+ TNode rhs = d_cconj[1][cid];
+ if( !considerCandidateConjecture( lhs, rhs ) ){
+ //push to children of generalization lattice
+ for( unsigned i=0; i<d_gen_lat_child[lhs].size(); i++ ){
+ if( d_gen_depth[lhs]+1==d_gen_depth[d_gen_lat_child[lhs][i]] ){
+ addCandidateConjecture( d_gen_lat_child[lhs][i], rhs, depth+1 );
+ }
+ }
+ }else{
+ Trace("sg-conjecture") << "* Candidate conjecture : " << lhs << " == " << rhs << std::endl;
+ Trace("sg-conjecture-debug") << " LHS generalization depth : " << d_gen_depth[lhs] << std::endl;
+ if( optFilterConfirmation() || optFilterFalsification() ){
+ Trace("sg-conjecture-debug") << " confirmed = " << d_subs_confirmCount << ", #witnesses range = " << d_subs_confirmWitnessRange.size() << "." << std::endl;
+ Trace("sg-conjecture-debug") << " #witnesses for ";
+ bool firstTime = true;
+ for( std::map< TNode, std::vector< TNode > >::iterator it = d_subs_confirmWitnessDomain.begin(); it != d_subs_confirmWitnessDomain.end(); ++it ){
+ if( !firstTime ){
+ Trace("sg-conjecture-debug") << ", ";
+ }
+ Trace("sg-conjecture-debug") << it->first << " : " << it->second.size() << "/" << d_pattern_fun_id[lhs][it->first];
+ if( it->second.size()==1 ){
+ Trace("sg-conjecture-debug") << " (" << it->second[0] << ")";
+ }
+ firstTime = false;
+ }
+ Trace("sg-conjecture-debug") << std::endl;
+ }
+ Assert( getUniversalRepresentative( rhs )==rhs );
+ Assert( getUniversalRepresentative( lhs )==lhs );
+ //make universal quantified formula
+ Assert( std::find( d_eq_conjectures[lhs].begin(), d_eq_conjectures[lhs].end(), rhs )==d_eq_conjectures[lhs].end() );
+ d_eq_conjectures[lhs].push_back( rhs );
+ d_eq_conjectures[rhs].push_back( lhs );
+ std::vector< Node > bvs;
+ for( std::map< TypeNode, unsigned >::iterator it = d_pattern_var_id[lhs].begin(); it != d_pattern_var_id[lhs].end(); ++it ){
+ for( unsigned i=0; i<=it->second; i++ ){
+ bvs.push_back( getFreeVar( it->first, i ) );
+ }
+ }
+ Node bvl = NodeManager::currentNM()->mkNode( BOUND_VAR_LIST, bvs );
+ Node conj = NodeManager::currentNM()->mkNode( FORALL, bvl, lhs.eqNode( rhs ) );
+ conj = Rewriter::rewrite( conj );
+ d_waiting_conjectures.push_back( conj );
+ }
+}
+
+bool ConjectureGenerator::considerCandidateConjecture( TNode lhs, TNode rhs ) {
+ Trace("sg-cconj-debug") << "Consider candidate conjecture : " << lhs << " == " << rhs << "?" << std::endl;
+ if( lhs==rhs ){
+ Trace("sg-cconj-debug") << " -> trivial." << std::endl;
+ return false;
+ }else{
+ if( lhs.getKind()==APPLY_CONSTRUCTOR && rhs.getKind()==APPLY_CONSTRUCTOR ){
+ Trace("sg-cconj-debug") << " -> irrelevant by syntactic analysis." << std::endl;
+ return false;
+ }
+ //variables of LHS must subsume variables of RHS
+ for( std::map< TypeNode, unsigned >::iterator it = d_pattern_var_id[rhs].begin(); it != d_pattern_var_id[rhs].end(); ++it ){
+ std::map< TypeNode, unsigned >::iterator itl = d_pattern_var_id[lhs].find( it->first );
+ if( itl!=d_pattern_var_id[lhs].end() ){
+ if( itl->second<it->second ){
+ Trace("sg-cconj-debug") << " -> variables of sort " << it->first << " are not subsumed." << std::endl;
+ return false;
+ }else{
+ Trace("sg-cconj-debug2") << " variables of sort " << it->first << " are : " << itl->second << " vs " << it->second << std::endl;
+ }
+ }else{
+ Trace("sg-cconj-debug") << " -> has no variables of sort " << it->first << "." << std::endl;
+ return false;
+ }
+ }
+ //currently active conjecture?
+ std::map< Node, std::vector< Node > >::iterator iteq = d_eq_conjectures.find( lhs );
+ if( iteq!=d_eq_conjectures.end() ){
+ if( std::find( iteq->second.begin(), iteq->second.end(), rhs )!=iteq->second.end() ){
+ Trace("sg-cconj-debug") << " -> already are considering this conjecture." << std::endl;
+ return false;
+ }
+ }
+ Trace("sg-cconj") << "Consider possible candidate conjecture : " << lhs << " == " << rhs << "?" << std::endl;
+ //find witness for counterexample, if possible
+ if( optFilterConfirmation() || optFilterFalsification() ){
+ Assert( d_rel_pattern_var_sum.find( lhs )!=d_rel_pattern_var_sum.end() );
+ Trace("sg-cconj-debug") << "Notify substitutions over " << d_rel_pattern_var_sum[lhs] << " variables." << std::endl;
+ std::map< TNode, TNode > subs;
+ d_subs_confirmCount = 0;
+ d_subs_confirmWitnessRange.clear();
+ d_subs_confirmWitnessDomain.clear();
+ if( !d_rel_pattern_subs_index[lhs].notifySubstitutions( this, subs, rhs, d_rel_pattern_var_sum[lhs] ) ){
+ Trace("sg-cconj") << " -> found witness that falsifies the conjecture." << std::endl;
+ return false;
+ }
+ if( optFilterConfirmation() ){
+ if( d_subs_confirmCount==0 ){
+ Trace("sg-cconj") << " -> not confirmed by a ground substitutions." << std::endl;
+ return false;
+ }
+ }
+ if( optFilterConfirmationDomain() ){
+ std::vector< TNode > vars;
+ std::vector< TNode > subs;
+ for( std::map< TNode, std::vector< TNode > >::iterator it = d_subs_confirmWitnessDomain.begin(); it != d_subs_confirmWitnessDomain.end(); ++it ){
+ Assert( d_pattern_fun_id[lhs].find( it->first )!=d_pattern_fun_id[lhs].end() );
+ unsigned req = d_pattern_fun_id[lhs][it->first];
+ std::map< TNode, unsigned >::iterator itrf = d_pattern_fun_id[rhs].find( it->first );
+ if( itrf!=d_pattern_fun_id[rhs].end() ){
+ req = itrf->second>req ? itrf->second : req;
+ }
+ if( it->second.size()<req ){
+ Trace("sg-cconj") << " -> did not find at least " << d_pattern_fun_id[lhs][it->first] << " different values in ground substitutions for variable " << it->first << "." << std::endl;
+ return false;
+ }
+ if( it->second.size()==1 ){
+ vars.push_back( it->first );
+ subs.push_back( it->second[0] );
+ }
+ }
+ if( optFilterConfirmationNonCanonical() && !vars.empty() ){
+ Node slhs = lhs.substitute( vars.begin(), vars.end(), subs.begin(), subs.end() );
+ Node srhs = rhs.substitute( vars.begin(), vars.end(), subs.begin(), subs.end() );
+ TNode slhsr = getUniversalRepresentative( slhs, true );
+ TNode srhsr = getUniversalRepresentative( srhs, true );
+ if( areUniversalEqual( slhsr, srhsr ) ){
+ Trace("sg-cconj") << " -> all ground witnesses can be proven by other theorems." << std::endl;
+ return false;
+ }else{
+ Trace("sg-cconj-debug") << "Checked if " << slhsr << " and " << srhsr << " were equal." << std::endl;
+ }
+ }
+ }
+ }
+
+ Trace("sg-cconj") << " -> SUCCESS." << std::endl;
+ if( optFilterConfirmation() || optFilterFalsification() ){
+ Trace("sg-cconj") << " confirmed = " << d_subs_confirmCount << ", #witnesses range = " << d_subs_confirmWitnessRange.size() << "." << std::endl;
+ for( std::map< TNode, std::vector< TNode > >::iterator it = d_subs_confirmWitnessDomain.begin(); it != d_subs_confirmWitnessDomain.end(); ++it ){
+ Trace("sg-cconj") << " #witnesses for " << it->first << " : " << it->second.size() << std::endl;
+ }
+ }
+
+ /*
+ if( getUniversalRepresentative( lhs )!=lhs ){
+ std::cout << "bad universal representative LHS : " << lhs << " " << getUniversalRepresentative( lhs ) << std::endl;
+ exit(0);
+ }
+ if( getUniversalRepresentative( rhs )!=rhs ){
+ std::cout << "bad universal representative RHS : " << rhs << " " << getUniversalRepresentative( rhs ) << std::endl;
+ exit(0);
+ }
+ */
+
+ //check if still canonical representation (should be, but for efficiency this is not guarenteed)
+ if( getUniversalRepresentative( lhs )!=lhs || getUniversalRepresentative( rhs )!=rhs ){
+ Trace("sg-cconj") << " -> after processing, not canonical." << std::endl;
+ }
+
+ return true;
+ }
+}
+
+bool ConjectureGenerator::notifySubstitution( TNode glhs, std::map< TNode, TNode >& subs, TNode rhs ) {
+ if( Trace.isOn("sg-cconj-debug") ){
+ Trace("sg-cconj-debug") << "Ground eqc for LHS : " << glhs << ", based on substituion: " << std::endl;
+ for( std::map< TNode, TNode >::iterator it = subs.begin(); it != subs.end(); ++it ){
+ Assert( getRepresentative( it->second )==it->second );
+ Trace("sg-cconj-debug") << " " << it->first << " -> " << it->second << std::endl;
+ }
+ }
+ Trace("sg-cconj-debug") << "Evaluate RHS : : " << rhs << std::endl;
+ //get the representative of rhs with substitution subs
+ TNode grhs = getTermDatabase()->evaluateTerm( rhs, subs, true );
+ Trace("sg-cconj-debug") << "...done evaluating term, got : " << grhs << std::endl;
+ if( !grhs.isNull() ){
+ if( glhs!=grhs ){
+ if( optFilterFalsification() ){
+ Trace("sg-cconj-debug") << "Ground eqc for RHS : " << grhs << std::endl;
+ //check based on ground terms
+ std::map< TNode, Node >::iterator itl = d_ground_eqc_map.find( glhs );
+ if( itl!=d_ground_eqc_map.end() ){
+ std::map< TNode, Node >::iterator itr = d_ground_eqc_map.find( grhs );
+ if( itr!=d_ground_eqc_map.end() ){
+ Trace("sg-cconj-debug") << "We have ground terms " << itl->second << " and " << itr->second << "." << std::endl;
+ if( itl->second.isConst() && itr->second.isConst() ){
+ Trace("sg-cconj-debug") << "...disequal constants." << std::endl;
+ Trace("sg-cconj-witness") << " Witness of falsification : " << itl->second << " != " << itr->second << ", substutition is : " << std::endl;
+ for( std::map< TNode, TNode >::iterator it = subs.begin(); it != subs.end(); ++it ){
+ Trace("sg-cconj-witness") << " " << it->first << " -> " << it->second << std::endl;
+ }
+ return false;
+ }
+ }
+ }
+ }
+ /*
+ if( getEqualityEngine()->areDisequal( glhs, grhs, false ) ){
+ Trace("sg-cconj-debug") << "..." << glhs << " and " << grhs << " are disequal." << std::endl;
+ return false;
+ }else{
+ Trace("sg-cconj-debug") << "..." << glhs << " and " << grhs << " are not disequal." << std::endl;
+ }
+ */
+ }else{
+ Trace("sg-cconj-witness") << " Witnessed " << glhs << " == " << grhs << ", substutition is : " << std::endl;
+ for( std::map< TNode, TNode >::iterator it = subs.begin(); it != subs.end(); ++it ){
+ Trace("sg-cconj-witness") << " " << it->first << " -> " << it->second << std::endl;
+ if( std::find( d_subs_confirmWitnessDomain[it->first].begin(), d_subs_confirmWitnessDomain[it->first].end(), it->second )==d_subs_confirmWitnessDomain[it->first].end() ){
+ d_subs_confirmWitnessDomain[it->first].push_back( it->second );
+ }
+ }
+ d_subs_confirmCount++;
+ if( std::find( d_subs_confirmWitnessRange.begin(), d_subs_confirmWitnessRange.end(), glhs )==d_subs_confirmWitnessRange.end() ){
+ d_subs_confirmWitnessRange.push_back( glhs );
+ }
+ Trace("sg-cconj-debug") << "RHS is identical." << std::endl;
+ }
+ }else{
+ Trace("sg-cconj-debug") << "(could not ground eqc for RHS)." << std::endl;
+ }
+ return true;
+}
+
+
+void TermGenerator::reset( ConjectureGenerator * s, TypeNode tn ) {
+ Assert( d_children.empty() );
+ d_typ = tn;
+ d_status = 0;
+ d_status_num = 0;
+ d_children.clear();
+ Trace("sg-gen-tg-debug2") << "...add to context " << this << std::endl;
+ d_id = s->d_tg_id;
+ s->changeContext( true );
+}
+
+bool TermGenerator::getNextTerm( ConjectureGenerator * s, unsigned depth ) {
+ if( Trace.isOn("sg-gen-tg-debug2") ){
+ Trace("sg-gen-tg-debug2") << this << " getNextTerm depth " << depth << " : status = " << d_status << ", num = " << d_status_num;
+ if( d_status==5 ){
+ TNode f = s->getTgFunc( d_typ, d_status_num );
+ Trace("sg-gen-tg-debug2") << ", f = " << f;
+ Trace("sg-gen-tg-debug2") << ", #args = " << s->d_func_args[f].size();
+ Trace("sg-gen-tg-debug2") << ", childNum = " << d_status_child_num;
+ Trace("sg-gen-tg-debug2") << ", #children = " << d_children.size();
+ }
+ Trace("sg-gen-tg-debug2") << std::endl;
+ }
+
+ if( d_status==0 ){
+ d_status++;
+ if( !d_typ.isNull() ){
+ if( s->allowVar( d_typ ) ){
+ //allocate variable
+ d_status_num = s->d_var_id[d_typ];
+ s->addVar( d_typ );
+ Trace("sg-gen-tg-debug2") << this << " ...return unique var #" << d_status_num << std::endl;
+ return s->considerCurrentTerm() ? true : getNextTerm( s, depth );
+ }else{
+ //check allocating new variable
+ d_status++;
+ d_status_num = -1;
+ s->d_tg_gdepth++;
+ return getNextTerm( s, depth );
+ }
+ }else{
+ d_status = 4;
+ d_status_num = -1;
+ return getNextTerm( s, depth );
+ }
+ }else if( d_status==2 ){
+ //cleanup previous information
+ //if( d_status_num>=0 ){
+ // s->d_var_eq_tg[d_status_num].pop_back();
+ //}
+ //check if there is another variable
+ if( (d_status_num+1)<(int)s->getNumTgVars( d_typ ) ){
+ d_status_num++;
+ //we have equated two variables
+ //s->d_var_eq_tg[d_status_num].push_back( d_id );
+ Trace("sg-gen-tg-debug2") << this << "...consider other var #" << d_status_num << std::endl;
+ return s->considerCurrentTerm() ? true : getNextTerm( s, depth );
+ }else{
+ s->d_tg_gdepth--;
+ d_status++;
+ return getNextTerm( s, depth );
+ }
+ }else if( d_status==4 ){
+ d_status++;
+ if( depth>0 && (d_status_num+1)<(int)s->getNumTgFuncs( d_typ ) ){
+ d_status_num++;
+ d_status_child_num = 0;
+ Trace("sg-gen-tg-debug2") << this << "...consider function " << s->getTgFunc( d_typ, d_status_num ) << std::endl;
+ s->d_tg_gdepth++;
+ if( !s->considerCurrentTerm() ){
+ s->d_tg_gdepth--;
+ //don't consider this function
+ d_status--;
+ }else{
+ //we have decided on a function application
+ }
+ return getNextTerm( s, depth );
+ }else{
+ //do not choose function applications at depth 0
+ d_status++;
+ return getNextTerm( s, depth );
+ }
+ }else if( d_status==5 ){
+ //iterating over arguments
+ TNode f = s->getTgFunc( d_typ, d_status_num );
+ if( d_status_child_num<0 ){
+ //no more arguments
+ s->d_tg_gdepth--;
+ d_status--;
+ return getNextTerm( s, depth );
+ }else if( d_status_child_num==(int)s->d_func_args[f].size() ){
+ d_status_child_num--;
+ return s->considerTermCanon( d_id ) ? true : getNextTerm( s, depth );
+ //return true;
+ }else{
+ Assert( d_status_child_num<(int)s->d_func_args[f].size() );
+ if( d_status_child_num==(int)d_children.size() ){
+ d_children.push_back( s->d_tg_id );
+ Assert( s->d_tg_alloc.find( s->d_tg_id )==s->d_tg_alloc.end() );
+ s->d_tg_alloc[d_children[d_status_child_num]].reset( s, s->d_func_args[f][d_status_child_num] );
+ return getNextTerm( s, depth );
+ }else{
+ Assert( d_status_child_num+1==(int)d_children.size() );
+ if( s->d_tg_alloc[d_children[d_status_child_num]].getNextTerm( s, depth-1 ) ){
+ d_status_child_num++;
+ return getNextTerm( s, depth );
+ }else{
+ d_children.pop_back();
+ d_status_child_num--;
+ return getNextTerm( s, depth );
+ }
+ }
+ }
+ }else if( d_status==1 || d_status==3 ){
+ if( d_status==1 ){
+ s->removeVar( d_typ );
+ Assert( d_status_num==(int)s->d_var_id[d_typ] );
+ //check if there is only one feasible equivalence class. if so, don't make pattern any more specific.
+ //unsigned i = s->d_ccand_eqc[0].size()-1;
+ //if( s->d_ccand_eqc[0][i].size()==1 && s->d_ccand_eqc[1][i].empty() ){
+ // Trace("ajr-temp") << "Apply this!" << std::endl;
+ // d_status = 6;
+ // return getNextTerm( s, depth );
+ //}
+ s->d_tg_gdepth++;
+ }
+ d_status++;
+ d_status_num = -1;
+ return getNextTerm( s, depth );
+ }else{
+ //clean up
+ Assert( d_children.empty() );
+ Trace("sg-gen-tg-debug2") << "...remove from context " << this << std::endl;
+ s->changeContext( false );
+ Assert( d_id==s->d_tg_id );
+ return false;
+ }
+}
+
+void TermGenerator::resetMatching( ConjectureGenerator * s, TNode eqc, unsigned mode ) {
+ d_match_status = 0;
+ d_match_status_child_num = 0;
+ d_match_children.clear();
+ d_match_children_end.clear();
+ d_match_mode = mode;
+}
+
+bool TermGenerator::getNextMatch( ConjectureGenerator * s, TNode eqc, std::map< TypeNode, std::map< unsigned, TNode > >& subs, std::map< TNode, bool >& rev_subs ) {
+ if( Trace.isOn("sg-gen-tg-match") ){
+ Trace("sg-gen-tg-match") << "Matching ";
+ debugPrint( s, "sg-gen-tg-match", "sg-gen-tg-match" );
+ Trace("sg-gen-tg-match") << " with eqc e" << s->d_em[eqc] << "..." << std::endl;
+ Trace("sg-gen-tg-match") << " mstatus = " << d_match_status;
+ if( d_status==5 ){
+ TNode f = s->getTgFunc( d_typ, d_status_num );
+ Trace("sg-gen-tg-debug2") << ", f = " << f;
+ Trace("sg-gen-tg-debug2") << ", #args = " << s->d_func_args[f].size();
+ Trace("sg-gen-tg-debug2") << ", mchildNum = " << d_match_status_child_num;
+ Trace("sg-gen-tg-debug2") << ", #mchildren = " << d_match_children.size();
+ }
+ Trace("sg-gen-tg-debug2") << ", current substitution : {";
+ for( std::map< TypeNode, std::map< unsigned, TNode > >::iterator itt = subs.begin(); itt != subs.end(); ++itt ){
+ for( std::map< unsigned, TNode >::iterator it = itt->second.begin(); it != itt->second.end(); ++it ){
+ Trace("sg-gen-tg-debug2") << " " << it->first << " -> e" << s->d_em[it->second];
+ }
+ }
+ Trace("sg-gen-tg-debug2") << " } " << std::endl;
+ }
+ if( d_status==1 ){
+ //a variable
+ if( d_match_status==0 ){
+ d_match_status++;
+ if( d_match_mode>=2 ){
+ //only ground terms
+ if( !s->isGroundEqc( eqc ) ){
+ return false;
+ }
+ }
+ if( d_match_mode%2==1 ){
+ std::map< TNode, bool >::iterator it = rev_subs.find( eqc );
+ if( it==rev_subs.end() ){
+ rev_subs[eqc] = true;
+ }else{
+ return false;
+ }
+ }
+ Assert( subs[d_typ].find( d_status_num )==subs[d_typ].end() );
+ subs[d_typ][d_status_num] = eqc;
+ return true;
+ }else{
+ //clean up
+ subs[d_typ].erase( d_status_num );
+ if( d_match_mode%2==1 ){
+ rev_subs.erase( eqc );
+ }
+ return false;
+ }
+ }else if( d_status==2 ){
+ if( d_match_status==0 ){
+ d_match_status++;
+ Assert( d_status_num<(int)s->getNumTgVars( d_typ ) );
+ std::map< unsigned, TNode >::iterator it = subs[d_typ].find( d_status_num );
+ Assert( it!=subs[d_typ].end() );
+ return it->second==eqc;
+ }else{
+ return false;
+ }
+ }else if( d_status==5 ){
+ //Assert( d_match_children.size()<=d_children.size() );
+ //enumerating over f-applications in eqc
+ if( d_match_status_child_num<0 ){
+ return false;
+ }else if( d_match_status==0 ){
+ //set up next binding
+ if( d_match_status_child_num==(int)d_match_children.size() ){
+ if( d_match_status_child_num==0 ){
+ //initial binding
+ TNode f = s->getTgFunc( d_typ, d_status_num );
+ std::map< TNode, TermArgTrie >::iterator it = s->getTermDatabase()->d_func_map_eqc_trie[f].d_data.find( eqc );
+ if( it!=s->getTermDatabase()->d_func_map_eqc_trie[f].d_data.end() ){
+ d_match_children.push_back( it->second.d_data.begin() );
+ d_match_children_end.push_back( it->second.d_data.end() );
+ }else{
+ d_match_status++;
+ d_match_status_child_num--;
+ return getNextMatch( s, eqc, subs, rev_subs );
+ }
+ }else{
+ d_match_children.push_back( d_match_children[d_match_status_child_num-1]->second.d_data.begin() );
+ d_match_children_end.push_back( d_match_children[d_match_status_child_num-1]->second.d_data.end() );
+ }
+ }
+ d_match_status++;
+ Assert( d_match_status_child_num+1==(int)d_match_children.size() );
+ if( d_match_children[d_match_status_child_num]==d_match_children_end[d_match_status_child_num] ){
+ //no more arguments to bind
+ d_match_children.pop_back();
+ d_match_children_end.pop_back();
+ d_match_status_child_num--;
+ return getNextMatch( s, eqc, subs, rev_subs );
+ }else{
+ if( d_match_status_child_num==(int)d_children.size() ){
+ //successfully matched all children
+ d_match_children.pop_back();
+ d_match_children_end.pop_back();
+ d_match_status_child_num--;
+ return true;//return d_match_children[d_match_status]!=d_match_children_end[d_match_status];
+ }else{
+ //do next binding
+ s->d_tg_alloc[d_children[d_match_status_child_num]].resetMatching( s, d_match_children[d_match_status_child_num]->first, d_match_mode );
+ return getNextMatch( s, eqc, subs, rev_subs );
+ }
+ }
+ }else{
+ Assert( d_match_status==1 );
+ Assert( d_match_status_child_num+1==(int)d_match_children.size() );
+ Assert( d_match_children[d_match_status_child_num]!=d_match_children_end[d_match_status_child_num] );
+ d_match_status--;
+ if( s->d_tg_alloc[d_children[d_match_status_child_num]].getNextMatch( s, d_match_children[d_match_status_child_num]->first, subs, rev_subs ) ){
+ d_match_status_child_num++;
+ return getNextMatch( s, eqc, subs, rev_subs );
+ }else{
+ //iterate
+ d_match_children[d_match_status_child_num]++;
+ return getNextMatch( s, eqc, subs, rev_subs );
+ }
+ }
+ }
+ Assert( false );
+ return false;
+}
+
+unsigned TermGenerator::getDepth( ConjectureGenerator * s ) {
+ if( d_status==5 ){
+ unsigned maxd = 0;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ unsigned d = s->d_tg_alloc[d_children[i]].getDepth( s );
+ if( d>maxd ){
+ maxd = d;
+ }
+ }
+ return 1+maxd;
+ }else{
+ return 0;
+ }
+}
+
+unsigned TermGenerator::getGeneralizationDepth( ConjectureGenerator * s ) {
+ if( d_status==5 ){
+ unsigned sum = 1;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ sum += s->d_tg_alloc[d_children[i]].getGeneralizationDepth( s );
+ }
+ return sum;
+ }else if( d_status==2 ){
+ return 1;
+ }else{
+ Assert( d_status==1 );
+ return 0;
+ }
+}
+
+Node TermGenerator::getTerm( ConjectureGenerator * s ) {
+ if( d_status==1 || d_status==2 ){
+ Assert( !d_typ.isNull() );
+ return s->getFreeVar( d_typ, d_status_num );
+ }else if( d_status==5 ){
+ Node f = s->getTgFunc( d_typ, d_status_num );
+ if( d_children.size()==s->d_func_args[f].size() ){
+ std::vector< Node > children;
+ children.push_back( f );
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ Node nc = s->d_tg_alloc[d_children[i]].getTerm( s );
+ if( nc.isNull() ){
+ return Node::null();
+ }else{
+ //Assert( nc.getType()==s->d_func_args[f][i] );
+ children.push_back( nc );
+ }
+ }
+ return NodeManager::currentNM()->mkNode( s->d_func_kind[f], children );
+ }
+ }else{
+ Assert( false );
+ }
+ return Node::null();
+}
+
+void TermGenerator::debugPrint( ConjectureGenerator * s, const char * c, const char * cd ) {
+ Trace(cd) << "[*" << d_id << "," << d_status << "]:";
+ if( d_status==1 || d_status==2 ){
+ Trace(c) << s->getFreeVar( d_typ, d_status_num );
+ }else if( d_status==5 ){
+ TNode f = s->getTgFunc( d_typ, d_status_num );
+ Trace(c) << "(" << f;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ Trace(c) << " ";
+ s->d_tg_alloc[d_children[i]].debugPrint( s, c, cd );
+ }
+ if( d_children.size()<s->d_func_args[f].size() ){
+ Trace(c) << " ...";
+ }
+ Trace(c) << ")";
+ }else{
+ Trace(c) << "???";
+ }
+}
+
+
+void SubstitutionIndex::addSubstitution( TNode eqc, std::vector< TNode >& vars, std::vector< TNode >& terms, unsigned i ) {
+ if( i==vars.size() ){
+ d_var = eqc;
+ }else{
+ Assert( d_var.isNull() || d_var==vars[i] );
+ d_var = vars[i];
+ d_children[terms[i]].addSubstitution( eqc, vars, terms, i+1 );
+ }
+}
+
+bool SubstitutionIndex::notifySubstitutions( ConjectureGenerator * s, std::map< TNode, TNode >& subs, TNode rhs, unsigned numVars, unsigned i ) {
+ if( i==numVars ){
+ Assert( d_children.empty() );
+ return s->notifySubstitution( d_var, subs, rhs );
+ }else{
+ Assert( i==0 || !d_children.empty() );
+ for( std::map< TNode, SubstitutionIndex >::iterator it = d_children.begin(); it != d_children.end(); ++it ){
+ Trace("sg-cconj-debug2") << "Try " << d_var << " -> " << it->first << " (" << i << "/" << numVars << ")" << std::endl;
+ subs[d_var] = it->first;
+ if( !it->second.notifySubstitutions( s, subs, rhs, numVars, i+1 ) ){
+ return false;
+ }
+ }
+ return true;
+ }
+}
+
+
+void TheoremIndex::addTheorem( std::vector< TNode >& lhs_v, std::vector< unsigned >& lhs_arg, TNode rhs ){
+ if( lhs_v.empty() ){
+ if( std::find( d_terms.begin(), d_terms.end(), rhs )==d_terms.end() ){
+ d_terms.push_back( rhs );
+ }
+ }else{
+ unsigned index = lhs_v.size()-1;
+ if( lhs_arg[index]==lhs_v[index].getNumChildren() ){
+ lhs_v.pop_back();
+ lhs_arg.pop_back();
+ addTheorem( lhs_v, lhs_arg, rhs );
+ }else{
+ lhs_arg[index]++;
+ addTheoremNode( lhs_v[index][lhs_arg[index]-1], lhs_v, lhs_arg, rhs );
+ }
+ }
+}
+
+void TheoremIndex::addTheoremNode( TNode curr, std::vector< TNode >& lhs_v, std::vector< unsigned >& lhs_arg, TNode rhs ){
+ Trace("thm-db-debug") << "Adding conjecture for subterm " << curr << "..." << std::endl;
+ if( curr.hasOperator() ){
+ lhs_v.push_back( curr );
+ lhs_arg.push_back( 0 );
+ d_children[curr.getOperator()].addTheorem( lhs_v, lhs_arg, rhs );
+ }else{
+ Assert( curr.getKind()==kind::BOUND_VARIABLE );
+ Assert( d_var.isNull() || d_var==curr );
+ d_var = curr;
+ d_children[curr].addTheorem( lhs_v, lhs_arg, rhs );
+ }
+}
+
+void TheoremIndex::getEquivalentTerms( std::vector< TNode >& n_v, std::vector< unsigned >& n_arg,
+ std::map< TNode, TNode >& smap, std::vector< TNode >& vars, std::vector< TNode >& subs,
+ std::vector< Node >& terms ) {
+ Trace("thm-db-debug") << "Get equivalent terms " << n_v.size() << " " << n_arg.size() << std::endl;
+ if( n_v.empty() ){
+ Trace("thm-db-debug") << "Number of terms : " << d_terms.size() << std::endl;
+ //apply substutitions to RHS's
+ for( unsigned i=0; i<d_terms.size(); i++ ){
+ Node n = d_terms[i].substitute( vars.begin(), vars.end(), subs.begin(), subs.end() );
+ terms.push_back( n );
+ }
+ }else{
+ unsigned index = n_v.size()-1;
+ if( n_arg[index]==n_v[index].getNumChildren() ){
+ n_v.pop_back();
+ n_arg.pop_back();
+ getEquivalentTerms( n_v, n_arg, smap, vars, subs, terms );
+ }else{
+ n_arg[index]++;
+ getEquivalentTermsNode( n_v[index][n_arg[index]-1], n_v, n_arg, smap, vars, subs, terms );
+ }
+ }
+}
+
+void TheoremIndex::getEquivalentTermsNode( Node curr, std::vector< TNode >& n_v, std::vector< unsigned >& n_arg,
+ std::map< TNode, TNode >& smap, std::vector< TNode >& vars, std::vector< TNode >& subs,
+ std::vector< Node >& terms ) {
+ Trace("thm-db-debug") << "Get equivalent based on subterm " << curr << "..." << std::endl;
+ if( curr.hasOperator() ){
+ Trace("thm-db-debug") << "Check based on operator..." << std::endl;
+ std::map< TNode, TheoremIndex >::iterator it = d_children.find( curr.getOperator() );
+ if( it!=d_children.end() ){
+ n_v.push_back( curr );
+ n_arg.push_back( 0 );
+ it->second.getEquivalentTerms( n_v, n_arg, smap, vars, subs, terms );
+ }
+ Trace("thm-db-debug") << "...done check based on operator" << std::endl;
+ }
+ if( !d_var.isNull() ){
+ Trace("thm-db-debug") << "Check for substitution with " << d_var << "..." << std::endl;
+ if( curr.getType()==d_var.getType() ){
+ //add to substitution if possible
+ bool success = false;
+ std::map< TNode, TNode >::iterator it = smap.find( d_var );
+ if( it==smap.end() ){
+ smap[d_var] = curr;
+ vars.push_back( d_var );
+ subs.push_back( curr );
+ success = true;
+ }else if( it->second==curr ){
+ success = true;
+ }else{
+ //also check modulo equality (in universal equality engine)
+ }
+ Trace("thm-db-debug") << "...check for substitution with " << d_var << ", success = " << success << "." << std::endl;
+ if( success ){
+ d_children[d_var].getEquivalentTerms( n_v, n_arg, smap, vars, subs, terms );
+ }
+ }
+ }
+}
+
+void TheoremIndex::debugPrint( const char * c, unsigned ind ) {
+ for( std::map< TNode, TheoremIndex >::iterator it = d_children.begin(); it != d_children.end(); ++it ){
+ for( unsigned i=0; i<ind; i++ ){ Trace(c) << " "; }
+ Trace(c) << it->first << std::endl;
+ it->second.debugPrint( c, ind+1 );
+ }
+ if( !d_terms.empty() ){
+ for( unsigned i=0; i<ind; i++ ){ Trace(c) << " "; }
+ Trace(c) << "{";
+ for( unsigned i=0; i<d_terms.size(); i++ ){
+ Trace(c) << " " << d_terms[i];
+ }
+ Trace(c) << " }" << std::endl;
+ }
+ //if( !d_var.isNull() ){
+ // for( unsigned i=0; i<ind; i++ ){ Trace(c) << " "; }
+ // Trace(c) << "var:" << d_var << std::endl;
+ //}
+}
+
+bool ConjectureGenerator::optReqDistinctVarPatterns() { return false; }
+bool ConjectureGenerator::optFilterFalsification() { return true; }
+bool ConjectureGenerator::optFilterConfirmation() { return true; }
+bool ConjectureGenerator::optFilterConfirmationDomain() { return true; }
+bool ConjectureGenerator::optFilterConfirmationOnlyGround() { return true; }//false; }
+bool ConjectureGenerator::optFilterConfirmationNonCanonical() { return false; }//true; }
+unsigned ConjectureGenerator::optFullCheckFrequency() { return 1; }
+unsigned ConjectureGenerator::optFullCheckConjectures() { return 1; }
+
+}
+
+
diff --git a/src/theory/quantifiers/conjecture_generator.h b/src/theory/quantifiers/conjecture_generator.h new file mode 100644 index 000000000..afdd9e018 --- /dev/null +++ b/src/theory/quantifiers/conjecture_generator.h @@ -0,0 +1,402 @@ +/********************* */
+/*! \file conjecture_generator.h
+ ** \verbatim
+ ** Original author: Andrew Reynolds
+ ** Major contributors: none
+ ** Minor contributors (to current version): none
+ ** This file is part of the CVC4 project.
+ ** Copyright (c) 2009-2014 New York University and The University of Iowa
+ ** See the file COPYING in the top-level source directory for licensing
+ ** information.\endverbatim
+ **
+ ** \brief conjecture generator class
+ **/
+
+#include "cvc4_private.h"
+
+#ifndef CONJECTURE_GENERATOR_H
+#define CONJECTURE_GENERATOR_H
+
+#include "context/cdhashmap.h"
+#include "context/cdchunk_list.h"
+#include "theory/quantifiers_engine.h"
+
+namespace CVC4 {
+namespace theory {
+namespace quantifiers {
+
+class TermArgTrie;
+
+//algorithm for computing candidate subgoals
+
+class ConjectureGenerator;
+
+// operator independent index of arguments for an EQC
+class OpArgIndex
+{
+public:
+ std::map< TNode, OpArgIndex > d_child;
+ std::vector< TNode > d_ops;
+ std::vector< TNode > d_op_terms;
+ void addTerm( ConjectureGenerator * s, TNode n, unsigned index = 0 );
+ Node getGroundTerm( ConjectureGenerator * s, std::vector< TNode >& args );
+ void getGroundTerms( ConjectureGenerator * s, std::vector< TNode >& terms );
+};
+
+class PatternTypIndex
+{
+public:
+ std::vector< TNode > d_terms;
+ std::map< TypeNode, std::map< unsigned, PatternTypIndex > > d_children;
+ void clear() {
+ d_terms.clear();
+ d_children.clear();
+ }
+};
+
+class SubstitutionIndex
+{
+public:
+ //current variable, or ground EQC if d_children.empty()
+ TNode d_var;
+ std::map< TNode, SubstitutionIndex > d_children;
+ //add substitution
+ void addSubstitution( TNode eqc, std::vector< TNode >& vars, std::vector< TNode >& terms, unsigned i = 0 );
+ //notify substitutions
+ bool notifySubstitutions( ConjectureGenerator * s, std::map< TNode, TNode >& subs, TNode rhs, unsigned numVars, unsigned i = 0 );
+};
+
+class TermGenerator
+{
+public:
+ TermGenerator(){}
+ TypeNode d_typ;
+ unsigned d_id;
+ //1 : consider as unique variable
+ //2 : consider equal to another variable
+ //5 : consider a function application
+ unsigned d_status;
+ int d_status_num;
+ //for function applications: the number of children you have built
+ int d_status_child_num;
+ //children (pointers to TermGenerators)
+ std::vector< unsigned > d_children;
+ //possible eqc for this term
+ //std::vector< TNode > d_eqc;
+
+ //match status
+ unsigned d_match_status;
+ int d_match_status_child_num;
+ //match mode
+ //1 : different variables must have different matches
+ //2 : variables must map to ground terms
+ //3 : both 1 and 2
+ unsigned d_match_mode;
+ //children
+ std::vector< std::map< TNode, TermArgTrie >::iterator > d_match_children;
+ std::vector< std::map< TNode, TermArgTrie >::iterator > d_match_children_end;
+
+ void reset( ConjectureGenerator * s, TypeNode tn );
+ bool getNextTerm( ConjectureGenerator * s, unsigned depth );
+ void resetMatching( ConjectureGenerator * s, TNode eqc, unsigned mode );
+ bool getNextMatch( ConjectureGenerator * s, TNode eqc, std::map< TypeNode, std::map< unsigned, TNode > >& subs, std::map< TNode, bool >& rev_subs );
+
+ unsigned getDepth( ConjectureGenerator * s );
+ unsigned getGeneralizationDepth( ConjectureGenerator * s );
+ Node getTerm( ConjectureGenerator * s );
+
+ void debugPrint( ConjectureGenerator * s, const char * c, const char * cd );
+};
+
+
+class TheoremIndex
+{
+private:
+ void addTheorem( std::vector< TNode >& lhs_v, std::vector< unsigned >& lhs_arg, TNode rhs );
+ void addTheoremNode( TNode curr, std::vector< TNode >& lhs_v, std::vector< unsigned >& lhs_arg, TNode rhs );
+ void getEquivalentTerms( std::vector< TNode >& n_v, std::vector< unsigned >& n_arg,
+ std::map< TNode, TNode >& smap, std::vector< TNode >& vars, std::vector< TNode >& subs,
+ std::vector< Node >& terms );
+ void getEquivalentTermsNode( Node curr, std::vector< TNode >& n_v, std::vector< unsigned >& n_arg,
+ std::map< TNode, TNode >& smap, std::vector< TNode >& vars, std::vector< TNode >& subs,
+ std::vector< Node >& terms );
+public:
+ TNode d_var;
+ std::map< TNode, TheoremIndex > d_children;
+ std::vector< Node > d_terms;
+
+ void addTheorem( TNode lhs, TNode rhs ) {
+ std::vector< TNode > v;
+ std::vector< unsigned > a;
+ addTheoremNode( lhs, v, a, rhs );
+ }
+ void getEquivalentTerms( TNode n, std::vector< Node >& terms ) {
+ std::vector< TNode > nv;
+ std::vector< unsigned > na;
+ std::map< TNode, TNode > smap;
+ std::vector< TNode > vars;
+ std::vector< TNode > subs;
+ getEquivalentTermsNode( n, nv, na, smap, vars, subs, terms );
+ }
+ void clear(){
+ d_var = Node::null();
+ d_children.clear();
+ d_terms.clear();
+ }
+ void debugPrint( const char * c, unsigned ind = 0 );
+};
+
+
+
+class ConjectureGenerator : public QuantifiersModule
+{
+ friend class OpArgIndex;
+ friend class PatGen;
+ friend class PatternGenEqc;
+ friend class PatternGen;
+ friend class SubsEqcIndex;
+ friend class TermGenerator;
+ typedef context::CDChunkList<Node> NodeList;
+ typedef context::CDHashMap< Node, Node, NodeHashFunction > NodeMap;
+ typedef context::CDHashMap< Node, bool, NodeHashFunction > BoolMap;
+//this class maintains a congruence closure for *universal* facts
+private:
+ //notification class for equality engine
+ class NotifyClass : public eq::EqualityEngineNotify {
+ ConjectureGenerator& d_sg;
+ public:
+ NotifyClass(ConjectureGenerator& sg): d_sg(sg) {}
+ bool eqNotifyTriggerEquality(TNode equality, bool value) { return true; }
+ bool eqNotifyTriggerPredicate(TNode predicate, bool value) { return true; }
+ bool eqNotifyTriggerTermEquality(TheoryId tag, TNode t1, TNode t2, bool value) { return true; }
+ void eqNotifyConstantTermMerge(TNode t1, TNode t2) { }
+ void eqNotifyNewClass(TNode t) { d_sg.eqNotifyNewClass(t); }
+ void eqNotifyPreMerge(TNode t1, TNode t2) { d_sg.eqNotifyPreMerge(t1, t2); }
+ void eqNotifyPostMerge(TNode t1, TNode t2) { d_sg.eqNotifyPostMerge(t1, t2); }
+ void eqNotifyDisequal(TNode t1, TNode t2, TNode reason) {d_sg.eqNotifyDisequal(t1, t2, reason); }
+ };/* class ConjectureGenerator::NotifyClass */
+ /** The notify class */
+ NotifyClass d_notify;
+ class EqcInfo{
+ public:
+ EqcInfo( context::Context* c );
+ //representative
+ context::CDO< Node > d_rep;
+ };
+ /** get or make eqc info */
+ EqcInfo* getOrMakeEqcInfo( TNode n, bool doMake = false );
+ /** (universal) equaltity engine */
+ eq::EqualityEngine d_uequalityEngine;
+ /** pending adds */
+ std::vector< Node > d_upendingAdds;
+ /** relevant terms */
+ std::map< Node, bool > d_urelevant_terms;
+ /** information necessary for equivalence classes */
+ std::map< Node, EqcInfo* > d_eqc_info;
+ /** called when a new equivalance class is created */
+ void eqNotifyNewClass(TNode t);
+ /** called when two equivalance classes will merge */
+ void eqNotifyPreMerge(TNode t1, TNode t2);
+ /** called when two equivalance classes have merged */
+ void eqNotifyPostMerge(TNode t1, TNode t2);
+ /** called when two equivalence classes are made disequal */
+ void eqNotifyDisequal(TNode t1, TNode t2, TNode reason);
+ /** add pending universal terms, merge equivalence classes */
+ void doPendingAddUniversalTerms();
+ /** are universal equal */
+ bool areUniversalEqual( TNode n1, TNode n2 );
+ /** are universal disequal */
+ bool areUniversalDisequal( TNode n1, TNode n2 );
+ /** get universal representative */
+ TNode getUniversalRepresentative( TNode n, bool add = false );
+ /** set relevant */
+ void setUniversalRelevant( TNode n );
+ /** ordering for universal terms */
+ bool isUniversalLessThan( TNode rt1, TNode rt2 );
+
+ /** the nodes we have reported as canonical representative */
+ std::vector< TNode > d_ue_canon;
+ /** is reported canon */
+ bool isReportedCanon( TNode n );
+ /** mark that term has been reported as canonical rep */
+ void markReportedCanon( TNode n );
+
+private: //information regarding the conjectures
+ /** list of all conjectures */
+ std::vector< Node > d_conjectures;
+ /** list of all waiting conjectures */
+ std::vector< Node > d_waiting_conjectures;
+ /** map of equality conjectures */
+ std::map< Node, std::vector< Node > > d_eq_conjectures;
+ /** currently existing conjectures in equality engine */
+ BoolMap d_ee_conjectures;
+ /** conjecture index */
+ TheoremIndex d_thm_index;
+ /** the relevant equivalence classes based on the conjectures */
+ std::vector< TNode > d_relevant_eqc[2];
+private: //information regarding the signature we are enumerating conjectures for
+ //all functions
+ std::vector< TNode > d_funcs;
+ //functions per type
+ std::map< TypeNode, std::vector< TNode > > d_typ_funcs;
+ //function to kind map
+ std::map< TNode, Kind > d_func_kind;
+ //type of each argument of the function
+ std::map< TNode, std::vector< TypeNode > > d_func_args;
+ //free variables
+ std::map< TypeNode, std::vector< Node > > d_free_var;
+ //map from free variable to FV#
+ std::map< TNode, unsigned > d_free_var_num;
+ // get canonical free variable #i of type tn
+ Node getFreeVar( TypeNode tn, unsigned i );
+ // get maximum free variable numbers
+ void getMaxFreeVarNum( TNode n, std::map< TypeNode, unsigned >& mvn );
+ // get canonical term, return null if it contains a term apart from handled signature
+ Node getCanonicalTerm( TNode n, std::map< TypeNode, unsigned >& var_count, std::map< TNode, TNode >& subs );
+private: //information regarding the terms
+ //relevant patterns (the LHS's)
+ std::map< TypeNode, std::vector< Node > > d_rel_patterns;
+ //total number of unique variables
+ std::map< TNode, unsigned > d_rel_pattern_var_sum;
+ //by types
+ PatternTypIndex d_rel_pattern_typ_index;
+ // substitution to ground EQC index
+ std::map< TNode, SubstitutionIndex > d_rel_pattern_subs_index;
+ //patterns (the RHS's)
+ std::map< TypeNode, std::vector< Node > > d_patterns;
+ //patterns to # variables per type
+ std::map< TNode, std::map< TypeNode, unsigned > > d_pattern_var_id;
+ // # duplicated variables
+ std::map< TNode, unsigned > d_pattern_var_duplicate;
+ // is normal pattern? (variables allocated in canonical way left to right)
+ std::map< TNode, bool > d_pattern_is_normal;
+ // patterns to a count of # operators (variables and functions)
+ std::map< TNode, std::map< TNode, unsigned > > d_pattern_fun_id;
+ // term size
+ std::map< TNode, unsigned > d_pattern_fun_sum;
+ // collect functions
+ unsigned collectFunctions( TNode opat, TNode pat, std::map< TNode, unsigned >& funcs,
+ std::map< TypeNode, unsigned >& mnvn, std::map< TypeNode, unsigned >& mxvn );
+ // add pattern
+ void registerPattern( Node pat, TypeNode tpat );
+private: //for debugging
+ unsigned d_rel_term_count;
+ std::map< TNode, unsigned > d_em;
+public: //environment for term enumeration
+ //the current number of enumerated variables per type
+ std::map< TypeNode, unsigned > d_var_id;
+ //the limit of number of variables per type to enumerate
+ std::map< TypeNode, unsigned > d_var_limit;
+ //the functions we can currently generate
+ std::map< TypeNode, std::vector< TNode > > d_typ_tg_funcs;
+ //the equivalence classes (if applicable) that match the currently generated term
+ bool d_use_ccand_eqc;
+ std::vector< std::vector< TNode > > d_ccand_eqc[2];
+ //the term generation objects
+ unsigned d_tg_id;
+ std::map< unsigned, TermGenerator > d_tg_alloc;
+ unsigned d_tg_gdepth;
+ int d_tg_gdepth_limit;
+ //std::vector< std::vector< unsigned > > d_var_eq_tg;
+ //access functions
+ unsigned getNumTgVars( TypeNode tn );
+ bool allowVar( TypeNode tn );
+ void addVar( TypeNode tn );
+ void removeVar( TypeNode tn );
+ unsigned getNumTgFuncs( TypeNode tn );
+ TNode getTgFunc( TypeNode tn, unsigned i );
+ bool considerCurrentTerm();
+ bool considerTermCanon( unsigned tg_id );
+ void changeContext( bool add );
+public: //for generalization lattice
+ //id of maximal nodes
+ std::map< TypeNode, std::vector< TNode > > d_gen_lat_maximal;
+ //generalization lattice
+ std::map< TNode, std::vector< TNode > > d_gen_lat_child;
+ std::map< TNode, std::vector< TNode > > d_gen_lat_parent;
+ //generalization depth
+ std::map< TNode, int > d_gen_depth;
+ //generalizations
+ bool isGeneralization( TNode patg, TNode pat ) {
+ std::map< TNode, TNode > subs;
+ return isGeneralization( patg, pat, subs );
+ }
+ bool isGeneralization( TNode patg, TNode pat, std::map< TNode, TNode >& subs );
+ void addGeneralizationsOf( TNode pat, std::map< TNode, bool >& patProc );
+
+ //from generalization depth to relevant patterns
+ std::map< TypeNode, std::map< unsigned, std::vector< TNode > > > d_rel_patterns_at_depth;
+
+
+public: //for property enumeration
+ //conjectures to process at a particular depth
+ std::map< unsigned, std::vector< unsigned > > d_cconj_at_depth;
+ //RHS, LHS
+ std::vector< TNode > d_cconj[2];
+ // RHS paired
+ std::map< TNode, std::vector< TNode > > d_cconj_rhs_paired;
+ //add candidate conjecture
+ void addCandidateConjecture( TNode lhs, TNode rhs, unsigned depth );
+ //process candidate conjecture at depth
+ void processCandidateConjecture( unsigned cid, unsigned depth );
+ //whether it should be considered
+ bool considerCandidateConjecture( TNode lhs, TNode rhs );
+ //notified of a substitution
+ bool notifySubstitution( TNode glhs, std::map< TNode, TNode >& subs, TNode rhs );
+ //confirmation count
+ unsigned d_subs_confirmCount;
+ //individual witnesses (for range)
+ std::vector< TNode > d_subs_confirmWitnessRange;
+ //individual witnesses (for domain)
+ std::map< TNode, std::vector< TNode > > d_subs_confirmWitnessDomain;
+public: //for ground equivalence classes
+ eq::EqualityEngine * getEqualityEngine();
+ bool areDisequal( TNode n1, TNode n2 );
+ bool areEqual( TNode n1, TNode n2 );
+ TNode getRepresentative( TNode n );
+ TermDb * getTermDatabase();
+private: //information about ground equivalence classes
+ TNode d_bool_eqc[2];
+ std::map< TNode, Node > d_ground_eqc_map;
+ std::vector< TNode > d_ground_terms;
+ //operator independent term index
+ std::map< TNode, OpArgIndex > d_op_arg_index;
+ //is handled term
+ bool isHandledTerm( TNode n );
+ Node getGroundEqc( TNode r );
+ bool isGroundEqc( TNode r );
+ bool isGroundTerm( TNode n );
+ // count of full effort checks
+ unsigned d_fullEffortCount;
+public:
+ ConjectureGenerator( QuantifiersEngine * qe, context::Context* c );
+ /* needs check */
+ bool needsCheck( Theory::Effort e );
+ /* reset at a round */
+ void reset_round( Theory::Effort e );
+ /* Call during quantifier engine's check */
+ void check( Theory::Effort e, unsigned quant_e );
+ /* Called for new quantifiers */
+ void registerQuantifier( Node q );
+ void assertNode( Node n );
+ /** Identify this module (for debugging, dynamic configuration, etc..) */
+ std::string identify() const { return "ConjectureGenerator"; }
+
+//options
+private:
+ bool optReqDistinctVarPatterns();
+ bool optFilterFalsification();
+ bool optFilterConfirmation();
+ bool optFilterConfirmationDomain();
+ bool optFilterConfirmationOnlyGround();
+ bool optFilterConfirmationNonCanonical(); //filter if all ground confirmations are non-canonical
+ unsigned optFullCheckFrequency();
+ unsigned optFullCheckConjectures();
+};
+
+
+}
+}
+}
+
+#endif
diff --git a/src/theory/quantifiers/first_order_model.cpp b/src/theory/quantifiers/first_order_model.cpp index 1421c639f..0a0d4eba8 100644 --- a/src/theory/quantifiers/first_order_model.cpp +++ b/src/theory/quantifiers/first_order_model.cpp @@ -115,6 +115,24 @@ Node FirstOrderModel::getSomeDomainElement(TypeNode tn){ return d_rep_set.d_type_reps[tn][0]; } +void FirstOrderModel::reset_round() { + d_quant_active.clear(); +} + +void FirstOrderModel::setQuantifierActive( TNode q, bool active ) { + d_quant_active[q] = active; +} + +bool FirstOrderModel::isQuantifierActive( TNode q ) { + std::map< TNode, bool >::iterator it = d_quant_active.find( q ); + if( it==d_quant_active.end() ){ + return true; + }else{ + return it->second; + } +} + + FirstOrderModelIG::FirstOrderModelIG(QuantifiersEngine * qe, context::Context* c, std::string name) : FirstOrderModel(qe, c,name) { diff --git a/src/theory/quantifiers/first_order_model.h b/src/theory/quantifiers/first_order_model.h index 76c3946ce..6ad04a1e6 100644 --- a/src/theory/quantifiers/first_order_model.h +++ b/src/theory/quantifiers/first_order_model.h @@ -92,6 +92,19 @@ public: } /** get some domain element */ Node getSomeDomainElement(TypeNode tn); +private: + //list of inactive quantified formulas + std::map< TNode, bool > d_quant_active; +public: + /** reset round */ + void reset_round(); + /** set quantified formula active/inactive + * a quantified formula may be set inactive if for instance: + * - it is entailed by other quantified formulas + */ + void setQuantifierActive( TNode q, bool active ); + /** is quantified formula active */ + bool isQuantifierActive( TNode q ); };/* class FirstOrderModel */ diff --git a/src/theory/quantifiers/full_model_check.cpp b/src/theory/quantifiers/full_model_check.cpp index d5ed5589b..64ebb6cda 100644 --- a/src/theory/quantifiers/full_model_check.cpp +++ b/src/theory/quantifiers/full_model_check.cpp @@ -811,9 +811,11 @@ bool FullModelChecker::exhaustiveInstantiate(FirstOrderModelFmc * fm, Node f, No Trace("fmc-exh-debug") << std::endl; int index = riter.increment(); Trace("fmc-exh-debug") << "Incremented index " << index << std::endl; - if (index>=0 && riter.d_index[index]>0 && addedLemmas>0 && riter.d_enum_type[index]==RepSetIterator::ENUM_RANGE) { - Trace("fmc-exh-debug") << "Since this is a range enumeration, skip to the next..." << std::endl; - riter.increment2( index-1 ); + if( !riter.isFinished() ){ + if (index>=0 && riter.d_index[index]>0 && addedLemmas>0 && riter.d_enum_type[index]==RepSetIterator::ENUM_RANGE) { + Trace("fmc-exh-debug") << "Since this is a range enumeration, skip to the next..." << std::endl; + riter.increment2( index-1 ); + } } } d_addedLemmas += addedLemmas; @@ -871,7 +873,7 @@ void FullModelChecker::doCheck(FirstOrderModelFmc * fm, Node f, Def & d, Node n Trace("fmc-debug") << "Can't process base array " << r << std::endl; //can't process this array d.reset(); - d.addEntry(fm, defC, Node::null()); + d.addEntry(fm, mkCondDefault(fm, f), Node::null()); } } else if( n.getNumChildren()==0 ){ diff --git a/src/theory/quantifiers/inst_match_generator.cpp b/src/theory/quantifiers/inst_match_generator.cpp index c024d0bab..6faa5ffca 100644 --- a/src/theory/quantifiers/inst_match_generator.cpp +++ b/src/theory/quantifiers/inst_match_generator.cpp @@ -618,13 +618,7 @@ int InstMatchGeneratorSimple::addInstantiations( Node f, InstMatch& baseMatch, Q m.add( baseMatch ); int addedLemmas = 0; - if( d_match_pattern.getType()==NodeManager::currentNM()->booleanType() ){ - for( int i=0; i<2; i++ ){ - addInstantiations( m, qe, addedLemmas, 0, &(qe->getTermDatabase()->d_pred_map_trie[i][ d_op ]) ); - } - }else{ - addInstantiations( m, qe, addedLemmas, 0, &(qe->getTermDatabase()->d_func_map_trie[ d_op ]) ); - } + addInstantiations( m, qe, addedLemmas, 0, &(qe->getTermDatabase()->d_func_map_trie[ d_op ]) ); return addedLemmas; } @@ -646,7 +640,7 @@ void InstMatchGeneratorSimple::addInstantiations( InstMatch& m, QuantifiersEngin }else{ if( d_match_pattern[argIndex].getKind()==INST_CONSTANT ){ int v = d_var_num[argIndex]; - for( std::map< Node, quantifiers::TermArgTrie >::iterator it = tat->d_data.begin(); it != tat->d_data.end(); ++it ){ + for( std::map< TNode, quantifiers::TermArgTrie >::iterator it = tat->d_data.begin(); it != tat->d_data.end(); ++it ){ Node t = it->first; Node prev = m.get( v ); //using representatives, just check if equal @@ -658,7 +652,7 @@ void InstMatchGeneratorSimple::addInstantiations( InstMatch& m, QuantifiersEngin } }else{ Node r = qe->getEqualityQuery()->getRepresentative( d_match_pattern[argIndex] ); - std::map< Node, quantifiers::TermArgTrie >::iterator it = tat->d_data.find( r ); + std::map< TNode, quantifiers::TermArgTrie >::iterator it = tat->d_data.find( r ); if( it!=tat->d_data.end() ){ addInstantiations( m, qe, addedLemmas, argIndex+1, &(it->second) ); } diff --git a/src/theory/quantifiers/instantiation_engine.cpp b/src/theory/quantifiers/instantiation_engine.cpp index 3dd4423de..684831773 100644 --- a/src/theory/quantifiers/instantiation_engine.cpp +++ b/src/theory/quantifiers/instantiation_engine.cpp @@ -31,7 +31,7 @@ using namespace CVC4::theory::quantifiers; using namespace CVC4::theory::inst; InstantiationEngine::InstantiationEngine( QuantifiersEngine* qe, bool setIncomplete ) : -QuantifiersModule( qe ), d_isup(NULL), d_i_ag(NULL), d_setIncomplete( setIncomplete ), d_ierCounter( 0 ), d_performCheck( false ){ +QuantifiersModule( qe ), d_isup(NULL), d_i_ag(NULL), d_setIncomplete( setIncomplete ), d_ierCounter( 0 ){ } @@ -41,41 +41,45 @@ InstantiationEngine::~InstantiationEngine() { } void InstantiationEngine::finishInit(){ - //for UF terms if( !options::finiteModelFind() || options::fmfInstEngine() ){ - //if( options::cbqi() ){ - // addInstStrategy( new InstStrategyCheckCESolved( this, d_quantEngine ) ); - //} - //these are the instantiation strategies for basic E-matching + + //these are the instantiation strategies for E-matching + + //user-provided patterns if( options::userPatternsQuant()!=USER_PAT_MODE_IGNORE ){ d_isup = new InstStrategyUserPatterns( d_quantEngine ); addInstStrategy( d_isup ); }else{ d_isup = NULL; } - d_i_ag = new InstStrategyAutoGenTriggers( d_quantEngine, Trigger::TS_ALL, 3 ); + + //auto-generated patterns + int tstrt = Trigger::TS_ALL; + if( options::triggerSelMode()==TRIGGER_SEL_MIN ){ + tstrt = Trigger::TS_MIN_TRIGGER; + }else if( options::triggerSelMode()==TRIGGER_SEL_MAX ){ + tstrt = Trigger::TS_MAX_TRIGGER; + } + d_i_ag = new InstStrategyAutoGenTriggers( d_quantEngine, tstrt, 3 ); d_i_ag->setGenerateAdditional( true ); addInstStrategy( d_i_ag ); - //addInstStrategy( new InstStrategyAddFailSplits( this, ie ) ); + + //full saturation : instantiate from relevant domain, then arbitrary terms if( !options::finiteModelFind() && options::fullSaturateQuant() ){ addInstStrategy( new InstStrategyFreeVariable( d_quantEngine ) ); } - //d_isup->setPriorityOver( d_i_ag ); - //d_isup->setPriorityOver( i_agm ); - //i_ag->setPriorityOver( i_agm ); } - //for arithmetic + + //counterexample-based quantifier instantiation if( options::cbqi() ){ addInstStrategy( new InstStrategySimplex( (arith::TheoryArith*)d_quantEngine->getTheoryEngine()->theoryOf( THEORY_ARITH ), d_quantEngine ) ); - } - //for datatypes - //if( options::cbqi() ){ // addInstStrategy( new InstStrategyDatatypesValue( d_quantEngine ) ); - //} + } } bool InstantiationEngine::doInstantiationRound( Theory::Effort effort ){ + unsigned lastWaiting = d_quantEngine->d_lemmas_waiting.size(); //if counterexample-based quantifier instantiation is active if( options::cbqi() ){ //check if any cbqi lemma has not been added yet @@ -149,7 +153,7 @@ bool InstantiationEngine::doInstantiationRound( Theory::Effort effort ){ } } //do not consider another level if already added lemma at this level - if( d_quantEngine->hasAddedLemma() ){ + if( d_quantEngine->d_lemmas_waiting.size()>lastWaiting ){ d_inst_round_status = InstStrategy::STATUS_UNKNOWN; } e++; @@ -158,14 +162,11 @@ bool InstantiationEngine::doInstantiationRound( Theory::Effort effort ){ Debug("inst-engine") << (int)d_quantEngine->d_lemmas_waiting.size() << std::endl; //Notice() << "All instantiators finished, # added lemmas = " << (int)d_lemmas_waiting.size() << std::endl; if( !d_quantEngine->hasAddedLemma() ){ - Debug("inst-engine-stuck") << "No instantiations produced at this state." << std::endl; Debug("inst-engine-ctrl") << "---Fail." << std::endl; return false; }else{ - Debug("inst-engine-ctrl") << "---Done. " << (int)d_quantEngine->d_lemmas_waiting.size() << std::endl; - Trace("inst-engine") << "Added lemmas = " << (int)d_quantEngine->d_lemmas_waiting.size() << std::endl; - //flush lemmas to output channel - d_quantEngine->flushLemmas( &d_quantEngine->getOutputChannel() ); + Debug("inst-engine-ctrl") << "---Done. " << (int)(d_quantEngine->d_lemmas_waiting.size()-lastWaiting) << std::endl; + Trace("inst-engine") << "Added lemmas = " << (int)(d_quantEngine->d_lemmas_waiting.size()-lastWaiting) << std::endl; return true; } } @@ -175,17 +176,17 @@ bool InstantiationEngine::needsCheck( Theory::Effort e ){ d_ierCounter++; } //determine if we should perform check, based on instWhenMode - d_performCheck = false; + bool performCheck = false; if( options::instWhenMode()==INST_WHEN_FULL ){ - d_performCheck = ( e >= Theory::EFFORT_FULL ); + performCheck = ( e >= Theory::EFFORT_FULL ); }else if( options::instWhenMode()==INST_WHEN_FULL_DELAY ){ - d_performCheck = ( e >= Theory::EFFORT_FULL ) && !d_quantEngine->getTheoryEngine()->needCheck(); + performCheck = ( e >= Theory::EFFORT_FULL ) && !d_quantEngine->getTheoryEngine()->needCheck(); }else if( options::instWhenMode()==INST_WHEN_FULL_LAST_CALL ){ - d_performCheck = ( ( e==Theory::EFFORT_FULL && d_ierCounter%2==0 ) || e==Theory::EFFORT_LAST_CALL ); + performCheck = ( ( e==Theory::EFFORT_FULL && d_ierCounter%2==0 ) || e==Theory::EFFORT_LAST_CALL ); }else if( options::instWhenMode()==INST_WHEN_LAST_CALL ){ - d_performCheck = ( e >= Theory::EFFORT_LAST_CALL ); + performCheck = ( e >= Theory::EFFORT_LAST_CALL ); }else{ - d_performCheck = true; + performCheck = true; } static int ierCounter2 = 0; if( e==Theory::EFFORT_LAST_CALL ){ @@ -193,15 +194,14 @@ bool InstantiationEngine::needsCheck( Theory::Effort e ){ //with bounded integers, skip every other last call, // since matching loops may occur with infinite quantification if( ierCounter2%2==0 && options::fmfBoundInt() ){ - d_performCheck = false; + performCheck = false; } } - - return d_performCheck; + return performCheck; } -void InstantiationEngine::check( Theory::Effort e ){ - if( d_performCheck && !d_quantEngine->hasAddedLemma() ){ +void InstantiationEngine::check( Theory::Effort e, unsigned quant_e ){ + if( quant_e==QuantifiersEngine::QEFFORT_STANDARD ){ Debug("inst-engine") << "IE: Check " << e << " " << d_ierCounter << std::endl; double clSet = 0; if( Trace.isOn("inst-engine") ){ @@ -211,12 +211,15 @@ void InstantiationEngine::check( Theory::Effort e ){ ++(d_statistics.d_instantiation_rounds); bool quantActive = false; Debug("quantifiers") << "quantifiers: check: asserted quantifiers size=" - << d_quantEngine->getModel()->getNumAssertedQuantifiers() << std::endl; + << d_quantEngine->getModel()->getNumAssertedQuantifiers() << std::endl; for( int i=0; i<(int)d_quantEngine->getModel()->getNumAssertedQuantifiers(); i++ ){ Node n = d_quantEngine->getModel()->getAssertedQuantifier( i ); - //it is not active if we have found the skolemized negation is unsat + //it is not active if it corresponds to a rewrite rule: we will process in rewrite engine if( TermDb::isRewriteRule( n ) ){ d_quant_active[n] = false; + }else if( !d_quantEngine->getModel()->isQuantifierActive( n ) ){ + d_quant_active[n] = false; + //it is not active if we have found the skolemized negation is unsat }else if( options::cbqi() && hasAddedCbqiLemma( n ) ){ Node cel = d_quantEngine->getTermDatabase()->getCounterexampleLiteral( n ); bool active, value; @@ -248,7 +251,6 @@ void InstantiationEngine::check( Theory::Effort e ){ Debug("quantifiers") << ", ce is asserted"; } Debug("quantifiers") << std::endl; - //it is not active if it corresponds to a rewrite rule: we will process in rewrite engine }else{ d_quant_active[n] = true; if( !TermDb::hasInstConstAttr(n) ){ diff --git a/src/theory/quantifiers/instantiation_engine.h b/src/theory/quantifiers/instantiation_engine.h index 7a3528217..393f53897 100644 --- a/src/theory/quantifiers/instantiation_engine.h +++ b/src/theory/quantifiers/instantiation_engine.h @@ -99,7 +99,6 @@ private: bool d_setIncomplete; /** inst round counter */ int d_ierCounter; - bool d_performCheck; /** whether each quantifier is active */ std::map< Node, bool > d_quant_active; /** whether we have added cbqi lemma */ @@ -131,7 +130,7 @@ public: void finishInit(); bool needsCheck( Theory::Effort e ); - void check( Theory::Effort e ); + void check( Theory::Effort e, unsigned quant_e ); void registerQuantifier( Node f ); void assertNode( Node f ); Node explain(TNode n){ return Node::null(); } diff --git a/src/theory/quantifiers/model_engine.cpp b/src/theory/quantifiers/model_engine.cpp index d68c66535..f3d3e4bc9 100644 --- a/src/theory/quantifiers/model_engine.cpp +++ b/src/theory/quantifiers/model_engine.cpp @@ -35,7 +35,12 @@ using namespace CVC4::theory::inst; //Model Engine constructor ModelEngine::ModelEngine( context::Context* c, QuantifiersEngine* qe ) : -QuantifiersModule( qe ){ +QuantifiersModule( qe ), +d_incomplete_check(false), +d_addedLemmas(0), +d_triedLemmas(0), +d_totalLemmas(0) +{ Trace("model-engine-debug") << "Initialize model engine, mbqi : " << options::mbqiMode() << " " << options::fmfBoundInt() << std::endl; if( options::mbqiMode()==MBQI_FMC || options::mbqiMode()==quantifiers::MBQI_FMC_INTERVAL || @@ -61,8 +66,12 @@ ModelEngine::~ModelEngine() { delete d_builder; } -void ModelEngine::check( Theory::Effort e ){ - if( e==Theory::EFFORT_LAST_CALL && !d_quantEngine->hasAddedLemma() ){ +bool ModelEngine::needsCheck( Theory::Effort e ) { + return e==Theory::EFFORT_LAST_CALL; +} + +void ModelEngine::check( Theory::Effort e, unsigned quant_e ){ + if( quant_e==QuantifiersEngine::QEFFORT_MODEL ){ int addedLemmas = 0; bool needsBuild = true; FirstOrderModel* fm = d_quantEngine->getModel(); @@ -140,7 +149,6 @@ void ModelEngine::check( Theory::Effort e ){ } }else{ //otherwise, the search will continue - d_quantEngine->flushLemmas( &d_quantEngine->getOutputChannel() ); } } } diff --git a/src/theory/quantifiers/model_engine.h b/src/theory/quantifiers/model_engine.h index caf27f691..890af1643 100644 --- a/src/theory/quantifiers/model_engine.h +++ b/src/theory/quantifiers/model_engine.h @@ -52,7 +52,8 @@ public: //get the builder QModelBuilder* getModelBuilder() { return d_builder; } public: - void check( Theory::Effort e ); + bool needsCheck( Theory::Effort e ); + void check( Theory::Effort e, unsigned quant_e ); void registerQuantifier( Node f ); void assertNode( Node f ); Node explain(TNode n){ return Node::null(); } diff --git a/src/theory/quantifiers/modes.h b/src/theory/quantifiers/modes.h index 112e052c2..26978c8f9 100644 --- a/src/theory/quantifiers/modes.h +++ b/src/theory/quantifiers/modes.h @@ -107,6 +107,15 @@ typedef enum { USER_PAT_MODE_IGNORE, } UserPatMode; +typedef enum { + /** default for trigger selection */ + TRIGGER_SEL_DEFAULT, + /** only consider minimal terms for triggers */ + TRIGGER_SEL_MIN, + /** only consider maximal terms for triggers */ + TRIGGER_SEL_MAX, +} TriggerSelMode; + }/* CVC4::theory::quantifiers namespace */ }/* CVC4::theory namespace */ diff --git a/src/theory/quantifiers/options b/src/theory/quantifiers/options index 1cdf5e8bd..bdd852adb 100644 --- a/src/theory/quantifiers/options +++ b/src/theory/quantifiers/options @@ -63,6 +63,8 @@ option relevantTriggers --relevant-triggers bool :default false prefer triggers that are more relevant based on SInE style analysis option relationalTriggers --relational-triggers bool :default false choose relational triggers such as x = f(y), x >= f(y) +option triggerSelMode --trigger-sel CVC4::theory::quantifiers::TriggerSelMode :default CVC4::theory::quantifiers::TRIGGER_SEL_DEFAULT :read-write :include "theory/quantifiers/modes.h" :handler CVC4::theory::quantifiers::stringToTriggerSelMode :handler-include "theory/quantifiers/options_handlers.h" + selection mode for triggers # Whether to consider terms in the bodies of quantifiers for matching option registerQuantBodyTerms --register-quant-body-terms bool :default false @@ -72,10 +74,15 @@ option instWhenMode --inst-when=MODE CVC4::theory::quantifiers::InstWhenMode :de when to apply instantiation option instMaxLevel --inst-max-level=N int :default -1 maximum inst level of terms used to instantiate quantified formulas with (-1 == no limit, default) +option instLevelInputOnly --inst-level-input-only bool :default true + only input terms are assigned instantiation level zero option eagerInstQuant --eager-inst-quant bool :default false apply quantifier instantiation eagerly +option instNoEntail --inst-no-entail bool :read-write :default false + do not consider instances of quantified formulas that are currently entailed + option fullSaturateQuant --full-saturate-quant bool :default false when all other quantifier instantiation strategies fail, instantiate with ground terms from relevant domain, then arbitrary ground terms before answering unknown @@ -141,5 +148,9 @@ option rrOneInstPerRound --rr-one-inst-per-round bool :default false option dtStcInduction --dt-stc-ind bool :default false apply strengthening for existential quantification over datatypes based on structural induction +option intWfInduction --int-wf-ind bool :default false + apply strengthening for integers based on well-founded induction +option conjectureGen --conjecture-gen bool :default false + generate candidate conjectures for inductive proofs endmodule diff --git a/src/theory/quantifiers/options_handlers.h b/src/theory/quantifiers/options_handlers.h index 38567d166..97eaf4aaa 100644 --- a/src/theory/quantifiers/options_handlers.h +++ b/src/theory/quantifiers/options_handlers.h @@ -152,6 +152,19 @@ ignore \n\ + Ignore user-provided patterns. \n\ \n\ "; +static const std::string triggerSelModeHelp = "\ +Trigger selection modes currently supported by the --trigger-sel option:\n\ +\n\ +default \n\ ++ Default, consider all subterms of quantified formulas for trigger selection.\n\ +\n\ +min \n\ ++ Consider only minimal subterms that meet criteria for triggers.\n\ +\n\ +max \n\ ++ Consider only maximal subterms that meet criteria for triggers. \n\ +\n\ +"; inline InstWhenMode stringToInstWhenMode(std::string option, std::string optarg, SmtEngine* smt) throw(OptionException) { if(optarg == "pre-full") { return INST_WHEN_PRE_FULL; @@ -296,6 +309,21 @@ inline UserPatMode stringToUserPatMode(std::string option, std::string optarg, S optarg + "'. Try --user-pat help."); } } +inline TriggerSelMode stringToTriggerSelMode(std::string option, std::string optarg, SmtEngine* smt) throw(OptionException) { + if(optarg == "default" || optarg == "all" ) { + return TRIGGER_SEL_DEFAULT; + } else if(optarg == "min") { + return TRIGGER_SEL_MIN; + } else if(optarg == "max") { + return TRIGGER_SEL_MAX; + } else if(optarg == "help") { + puts(triggerSelModeHelp.c_str()); + exit(1); + } else { + throw OptionException(std::string("unknown option for --trigger-sel: `") + + optarg + "'. Try --trigger-sel help."); + } +} }/* CVC4::theory::quantifiers namespace */ }/* CVC4::theory namespace */ }/* CVC4 namespace */ diff --git a/src/theory/quantifiers/quant_conflict_find.cpp b/src/theory/quantifiers/quant_conflict_find.cpp index c6e881986..504c3dcff 100644..100755 --- a/src/theory/quantifiers/quant_conflict_find.cpp +++ b/src/theory/quantifiers/quant_conflict_find.cpp @@ -1,2529 +1,2246 @@ -/********************* */ -/*! \file quant_conflict_find.cpp - ** \verbatim - ** Original author: Andrew Reynolds - ** Major contributors: Morgan Deters - ** Minor contributors (to current version): none - ** This file is part of the CVC4 project. - ** Copyright (c) 2009-2014 New York University and The University of Iowa - ** See the file COPYING in the top-level source directory for licensing - ** information.\endverbatim - ** - ** \brief quant conflict find class - ** - **/ - -#include <vector> - -#include "theory/quantifiers/quant_conflict_find.h" -#include "theory/quantifiers/quant_util.h" -#include "theory/theory_engine.h" -#include "theory/quantifiers/options.h" -#include "theory/quantifiers/term_database.h" -#include "theory/quantifiers/trigger.h" - -using namespace CVC4; -using namespace CVC4::kind; -using namespace CVC4::theory; -using namespace CVC4::theory::quantifiers; -using namespace std; - -namespace CVC4 { - -Node QcfNodeIndex::existsTerm( TNode n, std::vector< TNode >& reps, int index ) { - if( index==(int)reps.size() ){ - if( d_children.empty() ){ - return Node::null(); - }else{ - return d_children.begin()->first; - } - }else{ - std::map< TNode, QcfNodeIndex >::iterator it = d_children.find( reps[index] ); - if( it==d_children.end() ){ - return Node::null(); - }else{ - return it->second.existsTerm( n, reps, index+1 ); - } - } -} - -Node QcfNodeIndex::addTerm( TNode n, std::vector< TNode >& reps, int index ) { - if( index==(int)reps.size() ){ - if( d_children.empty() ){ - d_children[ n ].clear(); - return n; - }else{ - return d_children.begin()->first; - } - }else{ - return d_children[reps[index]].addTerm( n, reps, index+1 ); - } -} - - -void QcfNodeIndex::debugPrint( const char * c, int t ) { - for( std::map< TNode, QcfNodeIndex >::iterator it = d_children.begin(); it != d_children.end(); ++it ){ - if( !it->first.isNull() ){ - for( int j=0; j<t; j++ ){ Trace(c) << " "; } - Trace(c) << it->first << " : " << std::endl; - it->second.debugPrint( c, t+1 ); - } - } -} - - -void QuantInfo::initialize( Node q, Node qn ) { - d_q = q; - for( unsigned i=0; i<q[0].getNumChildren(); i++ ){ - d_match.push_back( TNode::null() ); - d_match_term.push_back( TNode::null() ); - } - - //register the variables - for( unsigned i=0; i<q[0].getNumChildren(); i++ ){ - d_var_num[q[0][i]] = i; - d_vars.push_back( q[0][i] ); - } - - registerNode( qn, true, true ); - - - Trace("qcf-qregister") << "- Make match gen structure..." << std::endl; - d_mg = new MatchGen( this, qn ); - - if( d_mg->isValid() ){ - /* - for( unsigned j=0; j<q[0].getNumChildren(); j++ ){ - if( d_inMatchConstraint.find( q[0][j] )==d_inMatchConstraint.end() ){ - Trace("qcf-invalid") << "QCF invalid : variable " << q[0][j] << " does not exist in a matching constraint." << std::endl; - d_mg->setInvalid(); - break; - } - } - */ - if( d_mg->isValid() ){ - for( unsigned j=q[0].getNumChildren(); j<d_vars.size(); j++ ){ - if( d_vars[j].getKind()!=BOUND_VARIABLE ){ - d_var_mg[j] = NULL; - bool is_tsym = false; - if( !MatchGen::isHandledUfTerm( d_vars[j] ) && d_vars[j].getKind()!=ITE ){ - is_tsym = true; - d_tsym_vars.push_back( j ); - } - if( !is_tsym || options::qcfTConstraint() ){ - d_var_mg[j] = new MatchGen( this, d_vars[j], true ); - } - if( !d_var_mg[j] || !d_var_mg[j]->isValid() ){ - Trace("qcf-invalid") << "QCF invalid : cannot match for " << d_vars[j] << std::endl; - d_mg->setInvalid(); - break; - }else{ - std::vector< int > bvars; - d_var_mg[j]->determineVariableOrder( this, bvars ); - } - } - } - if( d_mg->isValid() ){ - std::vector< int > bvars; - d_mg->determineVariableOrder( this, bvars ); - } - } - }else{ - Trace("qcf-invalid") << "QCF invalid : body of formula cannot be processed." << std::endl; - } - Trace("qcf-qregister-summary") << "QCF register : " << ( d_mg->isValid() ? "VALID " : "INVALID" ) << " : " << q << std::endl; -} - -void QuantInfo::registerNode( Node n, bool hasPol, bool pol, bool beneathQuant ) { - Trace("qcf-qregister-debug2") << "Register : " << n << std::endl; - if( n.getKind()==FORALL ){ - registerNode( n[1], hasPol, pol, true ); - }else{ - if( !MatchGen::isHandledBoolConnective( n ) ){ - if( n.hasBoundVar() ){ - //literals - if( n.getKind()==EQUAL ){ - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - flatten( n[i], beneathQuant ); - } - }else if( MatchGen::isHandledUfTerm( n ) ){ - flatten( n, beneathQuant ); - }else if( n.getKind()==ITE ){ - for( unsigned i=1; i<=2; i++ ){ - flatten( n[i], beneathQuant ); - } - registerNode( n[0], false, pol, beneathQuant ); - }else if( options::qcfTConstraint() ){ - //a theory-specific predicate - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - flatten( n[i], beneathQuant ); - } - } - } - }else{ - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - bool newHasPol; - bool newPol; - QuantPhaseReq::getPolarity( n, i, hasPol, pol, newHasPol, newPol ); - //QcfNode * qcfc = new QcfNode( d_c ); - //qcfc->d_parent = qcf; - //qcf->d_child[i] = qcfc; - registerNode( n[i], newHasPol, newPol, beneathQuant ); - } - } - } -} - -void QuantInfo::flatten( Node n, bool beneathQuant ) { - Trace("qcf-qregister-debug2") << "Flatten : " << n << std::endl; - if( n.hasBoundVar() ){ - if( n.getKind()==BOUND_VARIABLE ){ - d_inMatchConstraint[n] = true; - } - //if( MatchGen::isHandledUfTerm( n ) || n.getKind()==ITE ){ - if( d_var_num.find( n )==d_var_num.end() ){ - Trace("qcf-qregister-debug2") << "Add FLATTEN VAR : " << n << std::endl; - d_var_num[n] = d_vars.size(); - d_vars.push_back( n ); - d_match.push_back( TNode::null() ); - d_match_term.push_back( TNode::null() ); - if( n.getKind()==ITE ){ - registerNode( n, false, false ); - }else{ - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - flatten( n[i], beneathQuant ); - } - } - }else{ - Trace("qcf-qregister-debug2") << "...already processed" << std::endl; - } - }else{ - Trace("qcf-qregister-debug2") << "...is ground." << std::endl; - } -} - - -void QuantInfo::reset_round( QuantConflictFind * p ) { - for( unsigned i=0; i<d_match.size(); i++ ){ - d_match[i] = TNode::null(); - d_match_term[i] = TNode::null(); - } - d_curr_var_deq.clear(); - d_tconstraints.clear(); - //add built-in variable constraints - for( unsigned r=0; r<2; r++ ){ - for( std::map< int, std::vector< Node > >::iterator it = d_var_constraint[r].begin(); - it != d_var_constraint[r].end(); ++it ){ - for( unsigned j=0; j<it->second.size(); j++ ){ - Node rr = it->second[j]; - if( !isVar( rr ) ){ - rr = p->getRepresentative( rr ); - } - if( addConstraint( p, it->first, rr, r==0 )==-1 ){ - d_var_constraint[0].clear(); - d_var_constraint[1].clear(); - //quantified formula is actually equivalent to true - Trace("qcf-qregister") << "Quantifier is equivalent to true!!!" << std::endl; - d_mg->d_children.clear(); - d_mg->d_n = NodeManager::currentNM()->mkConst( true ); - d_mg->d_type = MatchGen::typ_ground; - return; - } - } - } - } - d_mg->reset_round( p ); - for( std::map< int, MatchGen * >::iterator it = d_var_mg.begin(); it != d_var_mg.end(); ++it ){ - it->second->reset_round( p ); - } - //now, reset for matching - d_mg->reset( p, false, this ); -} - -int QuantInfo::getCurrentRepVar( int v ) { - if( v!=-1 && !d_match[v].isNull() ){ - int vn = getVarNum( d_match[v] ); - if( vn!=-1 ){ - //int vr = getCurrentRepVar( vn ); - //d_match[v] = d_vars[vr]; - //return vr; - return getCurrentRepVar( vn ); - } - } - return v; -} - -TNode QuantInfo::getCurrentValue( TNode n ) { - int v = getVarNum( n ); - if( v==-1 ){ - return n; - }else{ - if( d_match[v].isNull() ){ - return n; - }else{ - Assert( getVarNum( d_match[v] )!=v ); - return getCurrentValue( d_match[v] ); - } - } -} - -TNode QuantInfo::getCurrentExpValue( TNode n ) { - int v = getVarNum( n ); - if( v==-1 ){ - return n; - }else{ - if( d_match[v].isNull() ){ - return n; - }else{ - Assert( getVarNum( d_match[v] )!=v ); - if( d_match_term[v].isNull() ){ - return getCurrentValue( d_match[v] ); - }else{ - return d_match_term[v]; - } - } - } -} - -bool QuantInfo::getCurrentCanBeEqual( QuantConflictFind * p, int v, TNode n, bool chDiseq ) { - //check disequalities - std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( v ); - if( itd!=d_curr_var_deq.end() ){ - for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){ - Node cv = getCurrentValue( it->first ); - Debug("qcf-ccbe") << "compare " << cv << " " << n << std::endl; - if( cv==n ){ - return false; - }else if( chDiseq && !isVar( n ) && !isVar( cv ) ){ - //they must actually be disequal if we are looking for conflicts - if( !p->areDisequal( n, cv ) ){ - //TODO : check for entailed disequal - - return false; - } - } - } - } - return true; -} - -int QuantInfo::addConstraint( QuantConflictFind * p, int v, TNode n, bool polarity ) { - v = getCurrentRepVar( v ); - int vn = getVarNum( n ); - vn = vn==-1 ? -1 : getCurrentRepVar( vn ); - n = getCurrentValue( n ); - return addConstraint( p, v, n, vn, polarity, false ); -} - -int QuantInfo::addConstraint( QuantConflictFind * p, int v, TNode n, int vn, bool polarity, bool doRemove ) { - //for handling equalities between variables, and disequalities involving variables - Debug("qcf-match-debug") << "- " << (doRemove ? "un" : "" ) << "constrain : " << v << " -> " << n << " (cv=" << getCurrentValue( n ) << ")"; - Debug("qcf-match-debug") << ", (vn=" << vn << "), polarity = " << polarity << std::endl; - Assert( doRemove || n==getCurrentValue( n ) ); - Assert( doRemove || v==getCurrentRepVar( v ) ); - Assert( doRemove || vn==getCurrentRepVar( getVarNum( n ) ) ); - if( polarity ){ - if( vn!=v ){ - if( doRemove ){ - if( vn!=-1 ){ - //if set to this in the opposite direction, clean up opposite instead - // std::map< int, TNode >::iterator itmn = d_match.find( vn ); - if( d_match[vn]==d_vars[v] ){ - return addConstraint( p, vn, d_vars[v], v, true, true ); - }else{ - //unsetting variables equal - std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( vn ); - if( itd!=d_curr_var_deq.end() ){ - //remove disequalities owned by this - std::vector< TNode > remDeq; - for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){ - if( it->second==v ){ - remDeq.push_back( it->first ); - } - } - for( unsigned i=0; i<remDeq.size(); i++ ){ - d_curr_var_deq[vn].erase( remDeq[i] ); - } - } - } - } - d_match[v] = TNode::null(); - return 1; - }else{ - //std::map< int, TNode >::iterator itm = d_match.find( v ); - - if( vn!=-1 ){ - Debug("qcf-match-debug") << " ...Variable bound to variable" << std::endl; - //std::map< int, TNode >::iterator itmn = d_match.find( vn ); - if( d_match[v].isNull() ){ - //setting variables equal - bool alreadySet = false; - if( !d_match[vn].isNull() ){ - alreadySet = true; - Assert( !isVar( d_match[vn] ) ); - } - - //copy or check disequalities - std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( v ); - if( itd!=d_curr_var_deq.end() ){ - for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){ - Node dv = getCurrentValue( it->first ); - if( !alreadySet ){ - if( d_curr_var_deq[vn].find( dv )==d_curr_var_deq[vn].end() ){ - d_curr_var_deq[vn][dv] = v; - } - }else{ - if( !p->areMatchDisequal( d_match[vn], dv ) ){ - Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl; - return -1; - } - } - } - } - if( alreadySet ){ - n = getCurrentValue( n ); - } - }else{ - if( d_match[vn].isNull() ){ - Debug("qcf-match-debug") << " ...Reverse direction" << std::endl; - //set the opposite direction - return addConstraint( p, vn, d_vars[v], v, true, false ); - }else{ - Debug("qcf-match-debug") << " -> Both variables bound, compare" << std::endl; - //are they currently equal - return p->areMatchEqual( d_match[v], d_match[vn] ) ? 0 : -1; - } - } - }else{ - Debug("qcf-match-debug") << " ...Variable bound to ground" << std::endl; - if( d_match[v].isNull() ){ - }else{ - //compare ground values - Debug("qcf-match-debug") << " -> Ground value, compare " << d_match[v] << " "<< n << std::endl; - return p->areMatchEqual( d_match[v], n ) ? 0 : -1; - } - } - if( setMatch( p, v, n ) ){ - Debug("qcf-match-debug") << " -> success" << std::endl; - return 1; - }else{ - Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl; - return -1; - } - } - }else{ - Debug("qcf-match-debug") << " -> redundant, variable identity" << std::endl; - return 0; - } - }else{ - if( vn==v ){ - Debug("qcf-match-debug") << " -> fail, variable identity" << std::endl; - return -1; - }else{ - if( doRemove ){ - Assert( d_curr_var_deq[v].find( n )!=d_curr_var_deq[v].end() ); - d_curr_var_deq[v].erase( n ); - return 1; - }else{ - if( d_curr_var_deq[v].find( n )==d_curr_var_deq[v].end() ){ - //check if it respects equality - //std::map< int, TNode >::iterator itm = d_match.find( v ); - if( !d_match[v].isNull() ){ - TNode nv = getCurrentValue( n ); - if( !p->areMatchDisequal( nv, d_match[v] ) ){ - Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl; - return -1; - } - } - d_curr_var_deq[v][n] = v; - Debug("qcf-match-debug") << " -> success" << std::endl; - return 1; - }else{ - Debug("qcf-match-debug") << " -> redundant disequality" << std::endl; - return 0; - } - } - } - } -} - -bool QuantInfo::isConstrainedVar( int v ) { - if( d_curr_var_deq.find( v )!=d_curr_var_deq.end() && !d_curr_var_deq[v].empty() ){ - return true; - }else{ - Node vv = getVar( v ); - //for( std::map< int, TNode >::iterator it = d_match.begin(); it != d_match.end(); ++it ){ - for( unsigned i=0; i<d_match.size(); i++ ){ - if( d_match[i]==vv ){ - return true; - } - } - for( std::map< int, std::map< TNode, int > >::iterator it = d_curr_var_deq.begin(); it != d_curr_var_deq.end(); ++it ){ - for( std::map< TNode, int >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ){ - if( it2->first==vv ){ - return true; - } - } - } - return false; - } -} - -bool QuantInfo::setMatch( QuantConflictFind * p, int v, TNode n ) { - if( getCurrentCanBeEqual( p, v, n ) ){ - Debug("qcf-match-debug") << "-- bind : " << v << " -> " << n << ", checked " << d_curr_var_deq[v].size() << " disequalities" << std::endl; - d_match[v] = n; - return true; - }else{ - return false; - } -} - -bool QuantInfo::isMatchSpurious( QuantConflictFind * p ) { - for( int i=0; i<getNumVars(); i++ ){ - //std::map< int, TNode >::iterator it = d_match.find( i ); - if( !d_match[i].isNull() ){ - if( !getCurrentCanBeEqual( p, i, d_match[i], p->d_effort==QuantConflictFind::effort_conflict ) ){ - return true; - } - } - } - return false; -} - -bool QuantInfo::isTConstraintSpurious( QuantConflictFind * p, std::vector< Node >& terms ) { - if( !d_tconstraints.empty() ){ - //check constraints - for( std::map< Node, bool >::iterator it = d_tconstraints.begin(); it != d_tconstraints.end(); ++it ){ - //apply substitution to the tconstraint - Node cons = it->first.substitute( p->getQuantifiersEngine()->getTermDatabase()->d_vars[d_q].begin(), - p->getQuantifiersEngine()->getTermDatabase()->d_vars[d_q].end(), - terms.begin(), terms.end() ); - cons = it->second ? cons : cons.negate(); - if( !entailmentTest( p, cons, p->d_effort==QuantConflictFind::effort_conflict ) ){ - return true; - } - } - } - return false; -} - -bool QuantInfo::entailmentTest( QuantConflictFind * p, Node lit, bool chEnt ) { - Trace("qcf-tconstraint-debug") << "Check : " << lit << std::endl; - Node rew = Rewriter::rewrite( lit ); - if( rew==p->d_false ){ - Trace("qcf-tconstraint-debug") << "...constraint " << lit << " is disentailed (rewrites to false)." << std::endl; - return false; - }else if( rew!=p->d_true ){ - //if checking for conflicts, we must be sure that the constraint is entailed - if( chEnt ){ - //check if it is entailed - Trace("qcf-tconstraint-debug") << "Check entailment of " << rew << "..." << std::endl; - std::pair<bool, Node> et = p->getQuantifiersEngine()->getTheoryEngine()->entailmentCheck(THEORY_OF_TYPE_BASED, rew ); - ++(p->d_statistics.d_entailment_checks); - Trace("qcf-tconstraint-debug") << "ET result : " << et.first << " " << et.second << std::endl; - if( !et.first ){ - Trace("qcf-tconstraint-debug") << "...cannot show entailment of " << rew << "." << std::endl; - return false; - }else{ - return true; - } - }else{ - Trace("qcf-tconstraint-debug") << "...does not need to be entailed." << std::endl; - return true; - } - }else{ - Trace("qcf-tconstraint-debug") << "...rewrites to true." << std::endl; - return true; - } -} - -bool QuantInfo::completeMatch( QuantConflictFind * p, std::vector< int >& assigned, bool doContinue ) { - //assign values for variables that were unassigned (usually not necessary, but handles corner cases) - bool doFail = false; - bool success = true; - if( doContinue ){ - doFail = true; - success = false; - }else{ - //solve for interpreted symbol matches - // this breaks the invariant that all introduced constraints are over existing terms - for( int i=(int)(d_tsym_vars.size()-1); i>=0; i-- ){ - int index = d_tsym_vars[i]; - TNode v = getCurrentValue( d_vars[index] ); - int slv_v = -1; - if( v==d_vars[index] ){ - slv_v = index; - } - Trace("qcf-tconstraint-debug") << "Solve " << d_vars[index] << " = " << v << " " << d_vars[index].getKind() << std::endl; - if( d_vars[index].getKind()==PLUS || d_vars[index].getKind()==MULT ){ - Kind k = d_vars[index].getKind(); - std::vector< TNode > children; - for( unsigned j=0; j<d_vars[index].getNumChildren(); j++ ){ - int vn = getVarNum( d_vars[index][j] ); - if( vn!=-1 ){ - TNode vv = getCurrentValue( d_vars[index][j] ); - if( vv==d_vars[index][j] ){ - //we will assign this - if( slv_v==-1 ){ - Trace("qcf-tconstraint-debug") << "...will solve for var #" << vn << std::endl; - slv_v = vn; - if( p->d_effort!=QuantConflictFind::effort_conflict ){ - break; - } - }else{ - Node z = p->getZero( k ); - if( !z.isNull() ){ - Trace("qcf-tconstraint-debug") << "...set " << d_vars[vn] << " = " << z << std::endl; - assigned.push_back( vn ); - if( !setMatch( p, vn, z ) ){ - success = false; - break; - } - } - } - }else{ - Trace("qcf-tconstraint-debug") << "...sum value " << vv << std::endl; - children.push_back( vv ); - } - }else{ - Trace("qcf-tconstraint-debug") << "...sum " << d_vars[index][j] << std::endl; - children.push_back( d_vars[index][j] ); - } - } - if( success ){ - if( slv_v!=-1 ){ - Node lhs; - if( children.empty() ){ - lhs = p->getZero( k ); - }else if( children.size()==1 ){ - lhs = children[0]; - }else{ - lhs = NodeManager::currentNM()->mkNode( k, children ); - } - Node sum; - if( v==d_vars[index] ){ - sum = lhs; - }else{ - if( p->d_effort==QuantConflictFind::effort_conflict ){ - Kind kn = k; - if( d_vars[index].getKind()==PLUS ){ - kn = MINUS; - } - if( kn!=k ){ - sum = NodeManager::currentNM()->mkNode( kn, v, lhs ); - } - } - } - if( !sum.isNull() ){ - assigned.push_back( slv_v ); - Trace("qcf-tconstraint-debug") << "...set " << d_vars[slv_v] << " = " << sum << std::endl; - if( !setMatch( p, slv_v, sum ) ){ - success = false; - } - p->d_tempCache.push_back( sum ); - } - }else{ - //must show that constraint is met - Node sum = NodeManager::currentNM()->mkNode( k, children ); - Node eq = sum.eqNode( v ); - if( !entailmentTest( p, eq ) ){ - success = false; - } - p->d_tempCache.push_back( sum ); - } - } - } - - if( !success ){ - break; - } - } - if( success ){ - //check what is left to assign - d_unassigned.clear(); - d_unassigned_tn.clear(); - std::vector< int > unassigned[2]; - std::vector< TypeNode > unassigned_tn[2]; - for( int i=0; i<getNumVars(); i++ ){ - if( d_match[i].isNull() ){ - int rindex = d_var_mg.find( i )==d_var_mg.end() ? 1 : 0; - unassigned[rindex].push_back( i ); - unassigned_tn[rindex].push_back( getVar( i ).getType() ); - assigned.push_back( i ); - } - } - d_unassigned_nvar = unassigned[0].size(); - for( unsigned i=0; i<2; i++ ){ - d_unassigned.insert( d_unassigned.end(), unassigned[i].begin(), unassigned[i].end() ); - d_unassigned_tn.insert( d_unassigned_tn.end(), unassigned_tn[i].begin(), unassigned_tn[i].end() ); - } - d_una_eqc_count.clear(); - d_una_index = 0; - } - } - - if( !d_unassigned.empty() && ( success || doContinue ) ){ - Trace("qcf-check") << "Assign to unassigned..." << std::endl; - do { - if( doFail ){ - Trace("qcf-check-unassign") << "Failure, try again..." << std::endl; - } - bool invalidMatch = false; - while( ( d_una_index>=0 && (int)d_una_index<(int)d_unassigned.size() ) || invalidMatch || doFail ){ - invalidMatch = false; - if( !doFail && d_una_index==(int)d_una_eqc_count.size() ){ - //check if it has now been assigned - if( d_una_index<d_unassigned_nvar ){ - if( !isConstrainedVar( d_unassigned[d_una_index] ) ){ - d_una_eqc_count.push_back( -1 ); - }else{ - d_var_mg[ d_unassigned[d_una_index] ]->reset( p, true, this ); - d_una_eqc_count.push_back( 0 ); - } - }else{ - d_una_eqc_count.push_back( 0 ); - } - }else{ - bool failed = false; - if( !doFail ){ - if( d_una_index<d_unassigned_nvar ){ - if( !isConstrainedVar( d_unassigned[d_una_index] ) ){ - Trace("qcf-check-unassign") << "Succeeded, variable unconstrained at " << d_una_index << std::endl; - d_una_index++; - }else if( d_var_mg[d_unassigned[d_una_index]]->getNextMatch( p, this ) ){ - Trace("qcf-check-unassign") << "Succeeded match with mg at " << d_una_index << std::endl; - d_una_index++; - }else{ - failed = true; - Trace("qcf-check-unassign") << "Failed match with mg at " << d_una_index << std::endl; - } - }else{ - Assert( doFail || d_una_index==(int)d_una_eqc_count.size()-1 ); - if( d_una_eqc_count[d_una_index]<(int)p->d_eqcs[d_unassigned_tn[d_una_index]].size() ){ - int currIndex = d_una_eqc_count[d_una_index]; - d_una_eqc_count[d_una_index]++; - Trace("qcf-check-unassign") << d_unassigned[d_una_index] << "->" << p->d_eqcs[d_unassigned_tn[d_una_index]][currIndex] << std::endl; - if( setMatch( p, d_unassigned[d_una_index], p->d_eqcs[d_unassigned_tn[d_una_index]][currIndex] ) ){ - d_match_term[d_unassigned[d_una_index]] = TNode::null(); - Trace("qcf-check-unassign") << "Succeeded match " << d_una_index << std::endl; - d_una_index++; - }else{ - Trace("qcf-check-unassign") << "Failed match " << d_una_index << std::endl; - invalidMatch = true; - } - }else{ - failed = true; - Trace("qcf-check-unassign") << "No more matches " << d_una_index << std::endl; - } - } - } - if( doFail || failed ){ - do{ - if( !doFail ){ - d_una_eqc_count.pop_back(); - }else{ - doFail = false; - } - d_una_index--; - }while( d_una_index>=0 && d_una_eqc_count[d_una_index]==-1 ); - } - } - } - success = d_una_index>=0; - if( success ){ - doFail = true; - Trace("qcf-check-unassign") << " Try: " << std::endl; - for( unsigned i=0; i<d_unassigned.size(); i++ ){ - int ui = d_unassigned[i]; - if( !d_match[ui].isNull() ){ - Trace("qcf-check-unassign") << " Assigned #" << ui << " : " << d_vars[ui] << " -> " << d_match[ui] << std::endl; - } - } - } - }while( success && isMatchSpurious( p ) ); - } - if( success ){ - for( unsigned i=0; i<d_unassigned.size(); i++ ){ - int ui = d_unassigned[i]; - if( !d_match[ui].isNull() ){ - Trace("qcf-check") << " Assigned #" << ui << " : " << d_vars[ui] << " -> " << d_match[ui] << std::endl; - } - } - return true; - }else{ - for( unsigned i=0; i<assigned.size(); i++ ){ - d_match[ assigned[i] ] = TNode::null(); - } - assigned.clear(); - return false; - } -} - -void QuantInfo::getMatch( std::vector< Node >& terms ){ - for( unsigned i=0; i<d_q[0].getNumChildren(); i++ ){ - //Node cv = qi->getCurrentValue( qi->d_match[i] ); - int repVar = getCurrentRepVar( i ); - Node cv; - //std::map< int, TNode >::iterator itmt = qi->d_match_term.find( repVar ); - if( !d_match_term[repVar].isNull() ){ - cv = d_match_term[repVar]; - }else{ - cv = d_match[repVar]; - } - Debug("qcf-check-inst") << "INST : " << i << " -> " << cv << ", from " << d_match[i] << std::endl; - terms.push_back( cv ); - } -} - -void QuantInfo::revertMatch( std::vector< int >& assigned ) { - for( unsigned i=0; i<assigned.size(); i++ ){ - d_match[ assigned[i] ] = TNode::null(); - } -} - -void QuantInfo::debugPrintMatch( const char * c ) { - for( int i=0; i<getNumVars(); i++ ){ - Trace(c) << " " << d_vars[i] << " -> "; - if( !d_match[i].isNull() ){ - Trace(c) << d_match[i]; - }else{ - Trace(c) << "(unassigned) "; - } - if( !d_curr_var_deq[i].empty() ){ - Trace(c) << ", DEQ{ "; - for( std::map< TNode, int >::iterator it = d_curr_var_deq[i].begin(); it != d_curr_var_deq[i].end(); ++it ){ - Trace(c) << it->first << " "; - } - Trace(c) << "}"; - } - if( !d_match_term[i].isNull() && d_match_term[i]!=d_match[i] ){ - Trace(c) << ", EXP : " << d_match_term[i]; - } - Trace(c) << std::endl; - } - if( !d_tconstraints.empty() ){ - Trace(c) << "ADDITIONAL CONSTRAINTS : " << std::endl; - for( std::map< Node, bool >::iterator it = d_tconstraints.begin(); it != d_tconstraints.end(); ++it ){ - Trace(c) << " " << it->first << " -> " << it->second << std::endl; - } - } -} - -MatchGen::MatchGen( QuantInfo * qi, Node n, bool isVar ){ - Trace("qcf-qregister-debug") << "Make match gen for " << n << ", isVar = " << isVar << std::endl; - std::vector< Node > qni_apps; - d_qni_size = 0; - if( isVar ){ - Assert( qi->d_var_num.find( n )!=qi->d_var_num.end() ); - if( n.getKind()==ITE ){ - d_type = typ_ite_var; - d_type_not = false; - d_n = n; - d_children.push_back( MatchGen( qi, d_n[0] ) ); - if( d_children[0].isValid() ){ - d_type = typ_ite_var; - for( unsigned i=1; i<=2; i++ ){ - Node nn = n.eqNode( n[i] ); - d_children.push_back( MatchGen( qi, nn ) ); - d_children[d_children.size()-1].d_qni_bound_except.push_back( 0 ); - if( !d_children[d_children.size()-1].isValid() ){ - setInvalid(); - break; - } - } - }else{ - d_type = typ_invalid; - } - }else{ - d_type = isHandledUfTerm( n ) ? typ_var : typ_tsym; - d_qni_var_num[0] = qi->getVarNum( n ); - d_qni_size++; - d_type_not = false; - d_n = n; - //Node f = getOperator( n ); - for( unsigned j=0; j<d_n.getNumChildren(); j++ ){ - Node nn = d_n[j]; - Trace("qcf-qregister-debug") << " " << d_qni_size; - if( qi->isVar( nn ) ){ - int v = qi->d_var_num[nn]; - Trace("qcf-qregister-debug") << " is var #" << v << std::endl; - d_qni_var_num[d_qni_size] = v; - //qi->addFuncParent( v, f, j ); - }else{ - Trace("qcf-qregister-debug") << " is gterm " << nn << std::endl; - d_qni_gterm[d_qni_size] = nn; - } - d_qni_size++; - } - } - }else{ - if( n.hasBoundVar() ){ - d_type_not = false; - d_n = n; - if( d_n.getKind()==NOT ){ - d_n = d_n[0]; - d_type_not = !d_type_not; - } - - if( isHandledBoolConnective( d_n ) ){ - //non-literals - d_type = typ_formula; - for( unsigned i=0; i<d_n.getNumChildren(); i++ ){ - if( d_n.getKind()!=FORALL || i==1 ){ - d_children.push_back( MatchGen( qi, d_n[i], false ) ); - if( !d_children[d_children.size()-1].isValid() ){ - setInvalid(); - break; - } - } - /* - else if( isTop && n.getKind()==OR && d_children[d_children.size()-1].d_type==typ_var_eq ){ - Trace("qcf-qregister-debug") << "Remove child, make built-in constraint" << std::endl; - //if variable equality/disequality at top level, remove immediately - bool cIsNot = d_children[d_children.size()-1].d_type_not; - Node cn = d_children[d_children.size()-1].d_n; - Assert( cn.getKind()==EQUAL ); - Assert( p->d_qinfo[q].isVar( cn[0] ) || p->d_qinfo[q].isVar( cn[1] ) ); - //make it a built-in constraint instead - for( unsigned i=0; i<2; i++ ){ - if( p->d_qinfo[q].isVar( cn[i] ) ){ - int v = p->d_qinfo[q].getVarNum( cn[i] ); - Node cno = cn[i==0 ? 1 : 0]; - p->d_qinfo[q].d_var_constraint[ cIsNot ? 0 : 1 ][v].push_back( cno ); - break; - } - } - d_children.pop_back(); - } - */ - } - }else{ - d_type = typ_invalid; - //literals - if( isHandledUfTerm( d_n ) ){ - Assert( qi->isVar( d_n ) ); - d_type = typ_pred; - }else if( d_n.getKind()==BOUND_VARIABLE ){ - Assert( d_n.getType().isBoolean() ); - d_type = typ_bool_var; - }else if( d_n.getKind()==EQUAL || options::qcfTConstraint() ){ - for( unsigned i=0; i<d_n.getNumChildren(); i++ ){ - if( d_n[i].hasBoundVar() ){ - if( !qi->isVar( d_n[i] ) ){ - Trace("qcf-qregister-debug") << "ERROR : not var " << d_n[i] << std::endl; - } - Assert( qi->isVar( d_n[i] ) ); - if( d_n.getKind()!=EQUAL && qi->isVar( d_n[i] ) ){ - d_qni_var_num[i+1] = qi->d_var_num[d_n[i]]; - } - }else{ - d_qni_gterm[i] = d_n[i]; - } - } - d_type = d_n.getKind()==EQUAL ? typ_eq : typ_tconstraint; - Trace("qcf-tconstraint") << "T-Constraint : " << d_n << std::endl; - } - } - }else{ - //we will just evaluate - d_n = n; - d_type = typ_ground; - } - //if( d_type!=typ_invalid ){ - //determine an efficient children ordering - //if( !d_children.empty() ){ - //for( unsigned i=0; i<d_children.size(); i++ ){ - // d_children_order.push_back( i ); - //} - //if( !d_n.isNull() && ( d_n.getKind()==OR || d_n.getKind()==AND || d_n.getKind()==IFF ) ){ - //sort based on the type of the constraint : ground comes first, then literals, then others - //MatchGenSort mgs; - //mgs.d_mg = this; - //std::sort( d_children_order.begin(), d_children_order.end(), mgs ); - //} - //} - //} - } - Trace("qcf-qregister-debug") << "Done make match gen " << n << ", type = "; - debugPrintType( "qcf-qregister-debug", d_type, true ); - Trace("qcf-qregister-debug") << std::endl; - //Assert( d_children.size()==d_children_order.size() ); - -} - -void MatchGen::collectBoundVar( QuantInfo * qi, Node n, std::vector< int >& cbvars ) { - int v = qi->getVarNum( n ); - if( v!=-1 && std::find( cbvars.begin(), cbvars.end(), v )==cbvars.end() ){ - cbvars.push_back( v ); - } - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - collectBoundVar( qi, n[i], cbvars ); - } -} - -void MatchGen::determineVariableOrder( QuantInfo * qi, std::vector< int >& bvars ) { - Trace("qcf-qregister-debug") << "Determine variable order " << d_n << std::endl; - bool isCom = d_type==typ_formula && ( d_n.getKind()==OR || d_n.getKind()==AND || d_n.getKind()==IFF ); - std::map< int, std::vector< int > > c_to_vars; - std::map< int, std::vector< int > > vars_to_c; - std::map< int, int > vb_count; - std::map< int, int > vu_count; - std::vector< bool > assigned; - Trace("qcf-qregister-debug") << "Calculate bound variables..." << std::endl; - for( unsigned i=0; i<d_children.size(); i++ ){ - collectBoundVar( qi, d_children[i].d_n, c_to_vars[i] ); - assigned.push_back( false ); - vb_count[i] = 0; - vu_count[i] = 0; - for( unsigned j=0; j<c_to_vars[i].size(); j++ ){ - int v = c_to_vars[i][j]; - vars_to_c[v].push_back( i ); - if( std::find( bvars.begin(), bvars.end(), v )==bvars.end() ){ - vu_count[i]++; - if( !isCom ){ - bvars.push_back( v ); - } - }else{ - vb_count[i]++; - } - } - } - if( isCom ){ - //children that bind the least number of unbound variables go first - do { - int min_score = -1; - int min_score_index = -1; - for( unsigned i=0; i<d_children.size(); i++ ){ - if( !assigned[i] ){ - int score = vu_count[i]; - if( min_score==-1 || score<min_score ){ - min_score = score; - min_score_index = i; - } - } - } - Trace("qcf-qregister-debug") << "...assign child " << min_score_index << "/" << d_children.size() << std::endl; - Assert( min_score_index!=-1 ); - //add to children order - d_children_order.push_back( min_score_index ); - assigned[min_score_index] = true; - //if( vb_count[min_score_index]==0 ){ - // d_independent.push_back( min_score_index ); - //} - //determine order internal to children - d_children[min_score_index].determineVariableOrder( qi, bvars ); - Trace("qcf-qregister-debug") << "...bind variables" << std::endl; - //now, make it a bound variable - for( unsigned i=0; i<c_to_vars[min_score_index].size(); i++ ){ - int v = c_to_vars[min_score_index][i]; - if( std::find( bvars.begin(), bvars.end(), v )==bvars.end() ){ - for( unsigned j=0; j<vars_to_c[v].size(); j++ ){ - int vc = vars_to_c[v][j]; - vu_count[vc]--; - vb_count[vc]++; - } - bvars.push_back( v ); - } - } - Trace("qcf-qregister-debug") << "...done assign child " << min_score_index << std::endl; - }while( d_children_order.size()!=d_children.size() ); - Trace("qcf-qregister-debug") << "Done assign variable ordering for " << d_n << std::endl; - }else{ - for( unsigned i=0; i<d_children.size(); i++ ){ - d_children_order.push_back( i ); - d_children[i].determineVariableOrder( qi, bvars ); - } - } -} - - -void MatchGen::reset_round( QuantConflictFind * p ) { - d_wasSet = false; - for( unsigned i=0; i<d_children.size(); i++ ){ - d_children[i].reset_round( p ); - } - for( std::map< int, TNode >::iterator it = d_qni_gterm.begin(); it != d_qni_gterm.end(); ++it ){ - d_qni_gterm_rep[it->first] = p->getRepresentative( it->second ); - } - if( d_type==typ_ground ){ - int e = p->evaluate( d_n ); - if( e==1 ){ - d_ground_eval[0] = p->d_true; - }else if( e==-1 ){ - d_ground_eval[0] = p->d_false; - } - }else if( d_type==typ_eq ){ - for( unsigned i=0; i<d_n.getNumChildren(); i++ ){ - if( !d_n[i].hasBoundVar() ){ - d_ground_eval[i] = p->evaluateTerm( d_n[i] ); - } - } - } - d_qni_bound_cons.clear(); - d_qni_bound_cons_var.clear(); - d_qni_bound.clear(); -} - -void MatchGen::reset( QuantConflictFind * p, bool tgt, QuantInfo * qi ) { - d_tgt = d_type_not ? !tgt : tgt; - Debug("qcf-match") << " Reset for : " << d_n << ", type : "; - debugPrintType( "qcf-match", d_type ); - Debug("qcf-match") << ", tgt = " << d_tgt << ", children = " << d_children.size() << " " << d_children_order.size() << std::endl; - d_qn.clear(); - d_qni.clear(); - d_qni_bound.clear(); - d_child_counter = -1; - d_tgt_orig = d_tgt; - - //set up processing matches - if( d_type==typ_invalid ){ - //do nothing - }else if( d_type==typ_ground ){ - if( d_ground_eval[0]==( d_tgt ? p->d_true : p->d_false ) ){ - d_child_counter = 0; - } - }else if( d_type==typ_bool_var ){ - //get current value of the variable - TNode n = qi->getCurrentValue( d_n ); - int vn = qi->getCurrentRepVar( qi->getVarNum( n ) ); - if( vn==-1 ){ - //evaluate the value, see if it is compatible - int e = p->evaluate( n ); - if( ( e==1 && d_tgt ) || ( e==0 && !d_tgt ) ){ - d_child_counter = 0; - } - }else{ - //unassigned, set match to true/false - d_qni_bound[0] = vn; - qi->setMatch( p, vn, d_tgt ? p->d_true : p->d_false ); - d_child_counter = 0; - } - if( d_child_counter==0 ){ - d_qn.push_back( NULL ); - } - }else if( d_type==typ_var ){ - Assert( isHandledUfTerm( d_n ) ); - Node f = getOperator( p, d_n ); - Debug("qcf-match-debug") << " reset: Var will match operators of " << f << std::endl; - QcfNodeIndex * qni = p->getQcfNodeIndex( Node::null(), f ); - if( qni!=NULL ){ - d_qn.push_back( qni ); - } - d_matched_basis = false; - }else if( d_type==typ_tsym || d_type==typ_tconstraint ){ - for( std::map< int, int >::iterator it = d_qni_var_num.begin(); it != d_qni_var_num.end(); ++it ){ - int repVar = qi->getCurrentRepVar( it->second ); - if( qi->d_match[repVar].isNull() ){ - Debug("qcf-match-debug") << "Force matching on child #" << it->first << ", which is var #" << repVar << std::endl; - d_qni_bound[it->first] = repVar; - } - } - d_qn.push_back( NULL ); - }else if( d_type==typ_pred || d_type==typ_eq ){ - //add initial constraint - Node nn[2]; - int vn[2]; - if( d_type==typ_pred ){ - nn[0] = qi->getCurrentValue( d_n ); - vn[0] = qi->getCurrentRepVar( qi->getVarNum( nn[0] ) ); - nn[1] = p->getRepresentative( d_tgt ? p->d_true : p->d_false ); - vn[1] = -1; - d_tgt = true; - }else{ - for( unsigned i=0; i<2; i++ ){ - TNode nc; - std::map< int, TNode >::iterator it = d_qni_gterm_rep.find( i ); - if( it!=d_qni_gterm_rep.end() ){ - nc = it->second; - }else{ - nc = d_n[i]; - } - nn[i] = qi->getCurrentValue( nc ); - vn[i] = qi->getCurrentRepVar( qi->getVarNum( nn[i] ) ); - } - } - bool success; - if( vn[0]==-1 && vn[1]==-1 ){ - //Trace("qcf-explain") << " reset : " << d_n << " check ground values " << nn[0] << " " << nn[1] << " (tgt=" << d_tgt << ")" << std::endl; - Debug("qcf-match-debug") << " reset: check ground values " << nn[0] << " " << nn[1] << " (" << d_tgt << ")" << std::endl; - //just compare values - if( d_tgt ){ - success = p->areMatchEqual( nn[0], nn[1] ); - }else{ - if( p->d_effort==QuantConflictFind::effort_conflict ){ - success = p->areDisequal( nn[0], nn[1] ); - }else{ - success = p->areMatchDisequal( nn[0], nn[1] ); - } - } - }else{ - //otherwise, add a constraint to a variable - if( vn[1]!=-1 && vn[0]==-1 ){ - //swap - Node t = nn[1]; - nn[1] = nn[0]; - nn[0] = t; - vn[0] = vn[1]; - vn[1] = -1; - } - Debug("qcf-match-debug") << " reset: add constraint " << vn[0] << " -> " << nn[1] << " (vn=" << vn[1] << ")" << std::endl; - //add some constraint - int addc = qi->addConstraint( p, vn[0], nn[1], vn[1], d_tgt, false ); - success = addc!=-1; - //if successful and non-redundant, store that we need to cleanup this - if( addc==1 ){ - //Trace("qcf-explain") << " reset: " << d_n << " add constraint " << vn[0] << " -> " << nn[1] << " (vn=" << vn[1] << ")" << ", d_tgt = " << d_tgt << std::endl; - for( unsigned i=0; i<2; i++ ){ - if( vn[i]!=-1 && std::find( d_qni_bound_except.begin(), d_qni_bound_except.end(), i )==d_qni_bound_except.end() ){ - d_qni_bound[vn[i]] = vn[i]; - } - } - d_qni_bound_cons[vn[0]] = nn[1]; - d_qni_bound_cons_var[vn[0]] = vn[1]; - } - } - //if successful, we will bind values to variables - if( success ){ - d_qn.push_back( NULL ); - } - }else{ - if( d_children.empty() ){ - //add dummy - d_qn.push_back( NULL ); - }else{ - if( d_tgt && d_n.getKind()==FORALL ){ - //do nothing - }else{ - //reset the first child to d_tgt - d_child_counter = 0; - getChild( d_child_counter )->reset( p, d_tgt, qi ); - } - } - } - d_binding = false; - d_wasSet = true; - Debug("qcf-match") << " reset: Finished reset for " << d_n << ", success = " << ( !d_qn.empty() || d_child_counter!=-1 ) << std::endl; -} - -bool MatchGen::getNextMatch( QuantConflictFind * p, QuantInfo * qi ) { - Debug("qcf-match") << " Get next match for : " << d_n << ", type = "; - debugPrintType( "qcf-match", d_type ); - Debug("qcf-match") << ", children = " << d_children.size() << ", binding = " << d_binding << std::endl; - if( d_type==typ_invalid || d_type==typ_ground ){ - if( d_child_counter==0 ){ - d_child_counter = -1; - return true; - }else{ - d_wasSet = false; - return false; - } - }else if( d_type==typ_var || d_type==typ_eq || d_type==typ_pred || d_type==typ_bool_var || d_type==typ_tconstraint || d_type==typ_tsym ){ - bool success = false; - bool terminate = false; - do { - bool doReset = false; - bool doFail = false; - if( !d_binding ){ - if( doMatching( p, qi ) ){ - Debug("qcf-match-debug") << " - Matching succeeded" << std::endl; - d_binding = true; - d_binding_it = d_qni_bound.begin(); - doReset = true; - //for tconstraint, add constraint - if( d_type==typ_tconstraint ){ - std::map< Node, bool >::iterator it = qi->d_tconstraints.find( d_n ); - if( it==qi->d_tconstraints.end() ){ - qi->d_tconstraints[d_n] = d_tgt; - //store that we added this constraint - d_qni_bound_cons[0] = d_n; - }else if( d_tgt!=it->second ){ - success = false; - terminate = true; - } - } - }else{ - Debug("qcf-match-debug") << " - Matching failed" << std::endl; - success = false; - terminate = true; - } - }else{ - doFail = true; - } - if( d_binding ){ - //also need to create match for each variable we bound - success = true; - Debug("qcf-match-debug") << " Produce matches for bound variables by " << d_n << ", type = "; - debugPrintType( "qcf-match-debug", d_type ); - Debug("qcf-match-debug") << "..." << std::endl; - - while( ( success && d_binding_it!=d_qni_bound.end() ) || doFail ){ - std::map< int, MatchGen * >::iterator itm; - if( !doFail ){ - Debug("qcf-match-debug") << " check variable " << d_binding_it->second << std::endl; - itm = qi->d_var_mg.find( d_binding_it->second ); - } - if( doFail || ( d_binding_it->first!=0 && itm!=qi->d_var_mg.end() ) ){ - Debug("qcf-match-debug") << " we had bound variable " << d_binding_it->second << ", reset = " << doReset << std::endl; - if( doReset ){ - itm->second->reset( p, true, qi ); - } - if( doFail || !itm->second->getNextMatch( p, qi ) ){ - do { - if( d_binding_it==d_qni_bound.begin() ){ - Debug("qcf-match-debug") << " failed." << std::endl; - success = false; - }else{ - --d_binding_it; - Debug("qcf-match-debug") << " decrement..." << std::endl; - } - }while( success && ( d_binding_it->first==0 || qi->d_var_mg.find( d_binding_it->second )==qi->d_var_mg.end() ) ); - doReset = false; - doFail = false; - }else{ - Debug("qcf-match-debug") << " increment..." << std::endl; - ++d_binding_it; - doReset = true; - } - }else{ - Debug("qcf-match-debug") << " skip..." << d_binding_it->second << std::endl; - ++d_binding_it; - doReset = true; - } - } - if( !success ){ - d_binding = false; - }else{ - terminate = true; - if( d_binding_it==d_qni_bound.begin() ){ - d_binding = false; - } - } - } - }while( !terminate ); - //if not successful, clean up the variables you bound - if( !success ){ - if( d_type==typ_eq || d_type==typ_pred ){ - //clean up the constraints you added - for( std::map< int, TNode >::iterator it = d_qni_bound_cons.begin(); it != d_qni_bound_cons.end(); ++it ){ - if( !it->second.isNull() ){ - Debug("qcf-match") << " Clean up bound var " << it->first << (d_tgt ? "!" : "") << " = " << it->second << std::endl; - std::map< int, int >::iterator itb = d_qni_bound_cons_var.find( it->first ); - int vn = itb!=d_qni_bound_cons_var.end() ? itb->second : -1; - //Trace("qcf-explain") << " cleanup: " << d_n << " remove constraint " << it->first << " -> " << it->second << " (vn=" << vn << ")" << ", d_tgt = " << d_tgt << std::endl; - qi->addConstraint( p, it->first, it->second, vn, d_tgt, true ); - } - } - d_qni_bound_cons.clear(); - d_qni_bound_cons_var.clear(); - d_qni_bound.clear(); - }else{ - //clean up the matches you set - for( std::map< int, int >::iterator it = d_qni_bound.begin(); it != d_qni_bound.end(); ++it ){ - Debug("qcf-match") << " Clean up bound var " << it->second << std::endl; - Assert( it->second<qi->getNumVars() ); - qi->d_match[ it->second ] = TNode::null(); - qi->d_match_term[ it->second ] = TNode::null(); - } - d_qni_bound.clear(); - } - if( d_type==typ_tconstraint ){ - //remove constraint if applicable - if( d_qni_bound_cons.find( 0 )!=d_qni_bound_cons.end() ){ - qi->d_tconstraints.erase( d_n ); - d_qni_bound_cons.clear(); - } - } - /* - if( d_type==typ_var && p->d_effort==QuantConflictFind::effort_mc && !d_matched_basis ){ - d_matched_basis = true; - Node f = getOperator( d_n ); - TNode mbo = p->getQuantifiersEngine()->getTermDatabase()->getModelBasisOpTerm( f ); - if( qi->setMatch( p, d_qni_var_num[0], mbo ) ){ - success = true; - d_qni_bound[0] = d_qni_var_num[0]; - } - } - */ - } - Debug("qcf-match") << " ...finished matching for " << d_n << ", success = " << success << std::endl; - d_wasSet = success; - return success; - }else if( d_type==typ_formula || d_type==typ_ite_var ){ - bool success = false; - if( d_child_counter<0 ){ - if( d_child_counter<-1 ){ - success = true; - d_child_counter = -1; - } - }else{ - while( !success && d_child_counter>=0 ){ - //transition system based on d_child_counter - if( d_n.getKind()==OR || d_n.getKind()==AND ){ - if( (d_n.getKind()==AND)==d_tgt ){ - //all children must match simultaneously - if( getChild( d_child_counter )->getNextMatch( p, qi ) ){ - if( d_child_counter<(int)(getNumChildren()-1) ){ - d_child_counter++; - Debug("qcf-match-debug") << " Reset child " << d_child_counter << " of " << d_n << std::endl; - getChild( d_child_counter )->reset( p, d_tgt, qi ); - }else{ - success = true; - } - }else{ - //if( std::find( d_independent.begin(), d_independent.end(), d_child_counter )!=d_independent.end() ){ - // d_child_counter--; - //}else{ - d_child_counter--; - //} - } - }else{ - //one child must match - if( !getChild( d_child_counter )->getNextMatch( p, qi ) ){ - if( d_child_counter<(int)(getNumChildren()-1) ){ - d_child_counter++; - Debug("qcf-match-debug") << " Reset child " << d_child_counter << " of " << d_n << ", one match" << std::endl; - getChild( d_child_counter )->reset( p, d_tgt, qi ); - }else{ - d_child_counter = -1; - } - }else{ - success = true; - } - } - }else if( d_n.getKind()==IFF ){ - //construct match based on both children - if( d_child_counter%2==0 ){ - if( getChild( 0 )->getNextMatch( p, qi ) ){ - d_child_counter++; - getChild( 1 )->reset( p, d_child_counter==1, qi ); - }else{ - if( d_child_counter==0 ){ - d_child_counter = 2; - getChild( 0 )->reset( p, !d_tgt, qi ); - }else{ - d_child_counter = -1; - } - } - } - if( d_child_counter>=0 && d_child_counter%2==1 ){ - if( getChild( 1 )->getNextMatch( p, qi ) ){ - success = true; - }else{ - d_child_counter--; - } - } - }else if( d_n.getKind()==ITE ){ - if( d_child_counter%2==0 ){ - int index1 = d_child_counter==4 ? 1 : 0; - if( getChild( index1 )->getNextMatch( p, qi ) ){ - d_child_counter++; - getChild( d_child_counter==5 ? 2 : (d_tgt==(d_child_counter==1) ? 1 : 2) )->reset( p, d_tgt, qi ); - }else{ - if( d_child_counter==4 || ( d_type==typ_ite_var && d_child_counter==2 ) ){ - d_child_counter = -1; - }else{ - d_child_counter +=2; - getChild( d_child_counter==2 ? 0 : 1 )->reset( p, d_child_counter==2 ? !d_tgt : d_tgt, qi ); - } - } - } - if( d_child_counter>=0 && d_child_counter%2==1 ){ - int index2 = d_child_counter==5 ? 2 : (d_tgt==(d_child_counter==1) ? 1 : 2); - if( getChild( index2 )->getNextMatch( p, qi ) ){ - success = true; - }else{ - d_child_counter--; - } - } - }else if( d_n.getKind()==FORALL ){ - if( getChild( d_child_counter )->getNextMatch( p, qi ) ){ - success = true; - }else{ - d_child_counter = -1; - } - } - } - d_wasSet = success; - Debug("qcf-match") << " ...finished construct match for " << d_n << ", success = " << success << std::endl; - return success; - } - } - Debug("qcf-match") << " ...already finished for " << d_n << std::endl; - return false; -} - -bool MatchGen::getExplanation( QuantConflictFind * p, QuantInfo * qi, std::vector< Node >& exp ) { - if( d_type==typ_eq ){ - Node n[2]; - for( unsigned i=0; i<2; i++ ){ - Trace("qcf-explain") << "Explain term " << d_n[i] << "..." << std::endl; - n[i] = getExplanationTerm( p, qi, d_n[i], exp ); - } - Node eq = n[0].eqNode( n[1] ); - if( !d_tgt_orig ){ - eq = eq.negate(); - } - exp.push_back( eq ); - Trace("qcf-explain") << "Explanation for " << d_n << " (tgt=" << d_tgt_orig << ") is " << eq << ", set = " << d_wasSet << std::endl; - return true; - }else if( d_type==typ_pred ){ - Trace("qcf-explain") << "Explain term " << d_n << "..." << std::endl; - Node n = getExplanationTerm( p, qi, d_n, exp ); - if( !d_tgt_orig ){ - n = n.negate(); - } - exp.push_back( n ); - Trace("qcf-explain") << "Explanation for " << d_n << " (tgt=" << d_tgt_orig << ") is " << n << ", set = " << d_wasSet << std::endl; - return true; - }else if( d_type==typ_formula ){ - Trace("qcf-explain") << "Explanation get for " << d_n << ", counter = " << d_child_counter << ", tgt = " << d_tgt_orig << ", set = " << d_wasSet << std::endl; - if( d_n.getKind()==OR || d_n.getKind()==AND ){ - if( (d_n.getKind()==AND)==d_tgt ){ - for( unsigned i=0; i<getNumChildren(); i++ ){ - if( !getChild( i )->getExplanation( p, qi, exp ) ){ - return false; - } - } - }else{ - return getChild( d_child_counter )->getExplanation( p, qi, exp ); - } - }else if( d_n.getKind()==IFF ){ - for( unsigned i=0; i<2; i++ ){ - if( !getChild( i )->getExplanation( p, qi, exp ) ){ - return false; - } - } - }else if( d_n.getKind()==ITE ){ - for( unsigned i=0; i<3; i++ ){ - bool isActive = ( ( i==0 && d_child_counter!=5 ) || - ( i==1 && d_child_counter!=( d_tgt ? 3 : 1 ) ) || - ( i==2 && d_child_counter!=( d_tgt ? 1 : 3 ) ) ); - if( isActive ){ - if( !getChild( i )->getExplanation( p, qi, exp ) ){ - return false; - } - } - } - }else{ - return false; - } - return true; - }else{ - return false; - } -} - -Node MatchGen::getExplanationTerm( QuantConflictFind * p, QuantInfo * qi, Node t, std::vector< Node >& exp ) { - Node v = qi->getCurrentExpValue( t ); - if( isHandledUfTerm( t ) ){ - for( unsigned i=0; i<t.getNumChildren(); i++ ){ - Node vi = getExplanationTerm( p, qi, t[i], exp ); - if( vi!=v[i] ){ - Node eq = vi.eqNode( v[i] ); - if( std::find( exp.begin(), exp.end(), eq )==exp.end() ){ - Trace("qcf-explain") << " add : " << eq << "." << std::endl; - exp.push_back( eq ); - } - } - } - } - return v; -} - -bool MatchGen::doMatching( QuantConflictFind * p, QuantInfo * qi ) { - if( !d_qn.empty() ){ - if( d_qn[0]==NULL ){ - d_qn.clear(); - return true; - }else{ - Assert( d_type==typ_var ); - Assert( d_qni_size>0 ); - bool invalidMatch; - do { - invalidMatch = false; - Debug("qcf-match-debug") << " Do matching " << d_n << " " << d_qn.size() << " " << d_qni.size() << std::endl; - if( d_qn.size()==d_qni.size()+1 ) { - int index = (int)d_qni.size(); - //initialize - TNode val; - std::map< int, int >::iterator itv = d_qni_var_num.find( index ); - if( itv!=d_qni_var_num.end() ){ - //get the representative variable this variable is equal to - int repVar = qi->getCurrentRepVar( itv->second ); - Debug("qcf-match-debug") << " Match " << index << " is a variable " << itv->second << ", which is repVar " << repVar << std::endl; - //get the value the rep variable - //std::map< int, TNode >::iterator itm = qi->d_match.find( repVar ); - if( !qi->d_match[repVar].isNull() ){ - val = qi->d_match[repVar]; - Debug("qcf-match-debug") << " Variable is already bound to " << val << std::endl; - }else{ - //binding a variable - d_qni_bound[index] = repVar; - std::map< TNode, QcfNodeIndex >::iterator it = d_qn[index]->d_children.begin(); - if( it != d_qn[index]->d_children.end() ) { - d_qni.push_back( it ); - //set the match - if( qi->setMatch( p, d_qni_bound[index], it->first ) ){ - Debug("qcf-match-debug") << " Binding variable" << std::endl; - if( d_qn.size()<d_qni_size ){ - d_qn.push_back( &it->second ); - } - }else{ - Debug("qcf-match") << " Binding variable, currently fail." << std::endl; - invalidMatch = true; - } - }else{ - Debug("qcf-match-debug") << " Binding variable, fail, no more variables to bind" << std::endl; - d_qn.pop_back(); - } - } - }else{ - Debug("qcf-match-debug") << " Match " << index << " is ground term" << std::endl; - Assert( d_qni_gterm.find( index )!=d_qni_gterm.end() ); - Assert( d_qni_gterm_rep.find( index )!=d_qni_gterm_rep.end() ); - val = d_qni_gterm_rep[index]; - Assert( !val.isNull() ); - } - if( !val.isNull() ){ - //constrained by val - std::map< TNode, QcfNodeIndex >::iterator it = d_qn[index]->d_children.find( val ); - if( it!=d_qn[index]->d_children.end() ){ - Debug("qcf-match-debug") << " Match" << std::endl; - d_qni.push_back( it ); - if( d_qn.size()<d_qni_size ){ - d_qn.push_back( &it->second ); - } - }else{ - Debug("qcf-match-debug") << " Failed to match" << std::endl; - d_qn.pop_back(); - } - } - }else{ - Assert( d_qn.size()==d_qni.size() ); - int index = d_qni.size()-1; - //increment if binding this variable - bool success = false; - std::map< int, int >::iterator itb = d_qni_bound.find( index ); - if( itb!=d_qni_bound.end() ){ - d_qni[index]++; - if( d_qni[index]!=d_qn[index]->d_children.end() ){ - success = true; - if( qi->setMatch( p, itb->second, d_qni[index]->first ) ){ - Debug("qcf-match-debug") << " Bind next variable" << std::endl; - if( d_qn.size()<d_qni_size ){ - d_qn.push_back( &d_qni[index]->second ); - } - }else{ - Debug("qcf-match-debug") << " Bind next variable, currently fail" << std::endl; - invalidMatch = true; - } - }else{ - qi->d_match[ itb->second ] = TNode::null(); - qi->d_match_term[ itb->second ] = TNode::null(); - Debug("qcf-match-debug") << " Bind next variable, no more variables to bind" << std::endl; - } - }else{ - //TODO : if it equal to something else, also try that - } - //if not incrementing, move to next - if( !success ){ - d_qn.pop_back(); - d_qni.pop_back(); - } - } - }while( ( !d_qn.empty() && d_qni.size()!=d_qni_size ) || invalidMatch ); - if( d_qni.size()==d_qni_size ){ - //Assert( !d_qni[d_qni.size()-1]->second.d_children.empty() ); - //Debug("qcf-match-debug") << " We matched " << d_qni[d_qni.size()-1]->second.d_children.begin()->first << std::endl; - Assert( !d_qni[d_qni.size()-1]->second.d_children.empty() ); - TNode t = d_qni[d_qni.size()-1]->second.d_children.begin()->first; - Debug("qcf-match-debug") << " " << d_n << " matched " << t << std::endl; - qi->d_match_term[d_qni_var_num[0]] = t; - //set the match terms - for( std::map< int, int >::iterator it = d_qni_bound.begin(); it != d_qni_bound.end(); ++it ){ - Debug("qcf-match-debug") << " position " << it->first << " bounded " << it->second << " / " << qi->d_q[0].getNumChildren() << std::endl; - //if( it->second<(int)qi->d_q[0].getNumChildren() ){ //if it is an actual variable, we are interested in knowing the actual term - if( it->first>0 ){ - Assert( !qi->d_match[ it->second ].isNull() ); - Assert( p->areEqual( t[it->first-1], qi->d_match[ it->second ] ) ); - qi->d_match_term[it->second] = t[it->first-1]; - } - //} - } - } - } - } - return !d_qn.empty(); -} - -void MatchGen::debugPrintType( const char * c, short typ, bool isTrace ) { - if( isTrace ){ - switch( typ ){ - case typ_invalid: Trace(c) << "invalid";break; - case typ_ground: Trace(c) << "ground";break; - case typ_eq: Trace(c) << "eq";break; - case typ_pred: Trace(c) << "pred";break; - case typ_formula: Trace(c) << "formula";break; - case typ_var: Trace(c) << "var";break; - case typ_ite_var: Trace(c) << "ite_var";break; - case typ_bool_var: Trace(c) << "bool_var";break; - } - }else{ - switch( typ ){ - case typ_invalid: Debug(c) << "invalid";break; - case typ_ground: Debug(c) << "ground";break; - case typ_eq: Debug(c) << "eq";break; - case typ_pred: Debug(c) << "pred";break; - case typ_formula: Debug(c) << "formula";break; - case typ_var: Debug(c) << "var";break; - case typ_ite_var: Debug(c) << "ite_var";break; - case typ_bool_var: Debug(c) << "bool_var";break; - } - } -} - -void MatchGen::setInvalid() { - d_type = typ_invalid; - d_children.clear(); -} - -bool MatchGen::isHandledBoolConnective( TNode n ) { - return n.getType().isBoolean() && ( n.getKind()==OR || n.getKind()==AND || n.getKind()==IFF || n.getKind()==ITE || n.getKind()==FORALL || n.getKind()==NOT ); -} - -bool MatchGen::isHandledUfTerm( TNode n ) { - //return n.getKind()==APPLY_UF || n.getKind()==STORE || n.getKind()==SELECT || - // n.getKind()==APPLY_CONSTRUCTOR || n.getKind()==APPLY_SELECTOR_TOTAL || n.getKind()==APPLY_TESTER; - return inst::Trigger::isAtomicTriggerKind( n.getKind() ); -} - -Node MatchGen::getOperator( QuantConflictFind * p, Node n ) { - if( isHandledUfTerm( n ) ){ - return p->getQuantifiersEngine()->getTermDatabase()->getOperator( n ); - }else{ - return Node::null(); - } -} - -bool MatchGen::isHandled( TNode n ) { - if( n.getKind()!=BOUND_VARIABLE && n.hasBoundVar() ){ - if( !isHandledBoolConnective( n ) && !isHandledUfTerm( n ) && n.getKind()!=EQUAL && n.getKind()!=ITE ){ - return false; - } - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - if( !isHandled( n[i] ) ){ - return false; - } - } - } - return true; -} - - -QuantConflictFind::QuantConflictFind( QuantifiersEngine * qe, context::Context* c ) : -QuantifiersModule( qe ), -d_c( c ), -d_conflict( c, false ), -d_qassert( c ) { - d_fid_count = 0; - d_true = NodeManager::currentNM()->mkConst<bool>(true); - d_false = NodeManager::currentNM()->mkConst<bool>(false); -} - -Node QuantConflictFind::mkEqNode( Node a, Node b ) { - if( a.getType().isBoolean() ){ - return a.iffNode( b ); - }else{ - return a.eqNode( b ); - } -} - -//-------------------------------------------------- registration - -void QuantConflictFind::registerQuantifier( Node q ) { - if( !TermDb::isRewriteRule( q ) ){ - d_quants.push_back( q ); - d_quant_id[q] = d_quants.size(); - Trace("qcf-qregister") << "Register "; - debugPrintQuant( "qcf-qregister", q ); - Trace("qcf-qregister") << " : " << q << std::endl; - //make QcfNode structure - Trace("qcf-qregister") << "- Get relevant equality/disequality pairs, calculate flattening..." << std::endl; - d_qinfo[q].initialize( q, q[1] ); - - //debug print - Trace("qcf-qregister") << "- Flattened structure is :" << std::endl; - Trace("qcf-qregister") << " "; - debugPrintQuantBody( "qcf-qregister", q, q[1] ); - Trace("qcf-qregister") << std::endl; - if( d_qinfo[q].d_vars.size()>q[0].getNumChildren() ){ - Trace("qcf-qregister") << " with additional constraints : " << std::endl; - for( unsigned j=q[0].getNumChildren(); j<d_qinfo[q].d_vars.size(); j++ ){ - Trace("qcf-qregister") << " ?x" << j << " = "; - debugPrintQuantBody( "qcf-qregister", q, d_qinfo[q].d_vars[j], false ); - Trace("qcf-qregister") << std::endl; - } - } - - Trace("qcf-qregister") << "Done registering quantifier." << std::endl; - } -} - -int QuantConflictFind::evaluate( Node n, bool pref, bool hasPref ) { - int ret = 0; - if( n.getKind()==EQUAL ){ - Node n1 = evaluateTerm( n[0] ); - Node n2 = evaluateTerm( n[1] ); - Debug("qcf-eval") << "Evaluate : Normalize " << n << " to " << n1 << " = " << n2 << std::endl; - if( areEqual( n1, n2 ) ){ - ret = 1; - }else if( areDisequal( n1, n2 ) ){ - ret = -1; - } - //else if( d_effort>QuantConflictFind::effort_conflict ){ - // ret = -1; - //} - }else if( MatchGen::isHandledUfTerm( n ) ){ //predicate - Node nn = evaluateTerm( n ); - Debug("qcf-eval") << "Evaluate : Normalize " << nn << " to " << n << std::endl; - if( areEqual( nn, d_true ) ){ - ret = 1; - }else if( areEqual( nn, d_false ) ){ - ret = -1; - } - //else if( d_effort>QuantConflictFind::effort_conflict ){ - // ret = -1; - //} - }else if( n.getKind()==NOT ){ - return -evaluate( n[0] ); - }else if( n.getKind()==ITE ){ - int cev1 = evaluate( n[0] ); - int cevc[2] = { 0, 0 }; - for( unsigned i=0; i<2; i++ ){ - if( ( i==0 && cev1!=-1 ) || ( i==1 && cev1!=1 ) ){ - cevc[i] = evaluate( n[i+1] ); - if( cev1!=0 ){ - ret = cevc[i]; - break; - }else if( cevc[i]==0 ){ - break; - } - } - } - if( ret==0 && cevc[0]!=0 && cevc[0]==cevc[1] ){ - ret = cevc[0]; - } - }else if( n.getKind()==IFF ){ - int cev1 = evaluate( n[0] ); - if( cev1!=0 ){ - int cev2 = evaluate( n[1] ); - if( cev2!=0 ){ - ret = cev1==cev2 ? 1 : -1; - } - } - - }else{ - int ssval = 0; - if( n.getKind()==OR ){ - ssval = 1; - }else if( n.getKind()==AND ){ - ssval = -1; - } - bool isUnk = false; - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - int cev = evaluate( n[i] ); - if( cev==ssval ){ - ret = ssval; - break; - }else if( cev==0 ){ - isUnk = true; - } - } - if( ret==0 && !isUnk ){ - ret = -ssval; - } - } - Debug("qcf-eval") << "Evaluate " << n << " to " << ret << std::endl; - return ret; -} - -short QuantConflictFind::getMaxQcfEffort() { - if( options::qcfMode()==QCF_CONFLICT_ONLY ){ - return effort_conflict; - }else if( options::qcfMode()==QCF_PROP_EQ ){ - return effort_prop_eq; - }else if( options::qcfMode()==QCF_MC ){ - return effort_mc; - }else{ - return 0; - } -} - -bool QuantConflictFind::areMatchEqual( TNode n1, TNode n2 ) { - //if( d_effort==QuantConflictFind::effort_mc ){ - // return n1==n2 || !areDisequal( n1, n2 ); - //}else{ - return n1==n2; - //} -} - -bool QuantConflictFind::areMatchDisequal( TNode n1, TNode n2 ) { - //if( d_effort==QuantConflictFind::effort_conflict ){ - // return areDisequal( n1, n2 ); - //}else{ - return n1!=n2; - //} -} - -//-------------------------------------------------- handling assertions / eqc - -void QuantConflictFind::assertNode( Node q ) { - if( !TermDb::isRewriteRule( q ) ){ - Trace("qcf-proc") << "QCF : assertQuantifier : "; - debugPrintQuant("qcf-proc", q); - Trace("qcf-proc") << std::endl; - d_qassert.push_back( q ); - //set the eqRegistries that this depends on to true - //for( std::map< EqRegistry *, bool >::iterator it = d_qinfo[q].d_rel_eqr.begin(); it != d_qinfo[q].d_rel_eqr.end(); ++it ){ - // it->first->d_active.set( true ); - //} - } -} - -eq::EqualityEngine * QuantConflictFind::getEqualityEngine() { - //return ((uf::TheoryUF*)d_quantEngine->getTheoryEngine()->theoryOf( theory::THEORY_UF ))->getEqualityEngine(); - return d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); -} -bool QuantConflictFind::areEqual( Node n1, Node n2 ) { - return getEqualityEngine()->hasTerm( n1 ) && getEqualityEngine()->hasTerm( n2 ) && getEqualityEngine()->areEqual( n1,n2 ); -} -bool QuantConflictFind::areDisequal( Node n1, Node n2 ) { - return n1!=n2 && getEqualityEngine()->hasTerm( n1 ) && getEqualityEngine()->hasTerm( n2 ) && getEqualityEngine()->areDisequal( n1,n2, false ); -} -Node QuantConflictFind::getRepresentative( Node n ) { - if( getEqualityEngine()->hasTerm( n ) ){ - return getEqualityEngine()->getRepresentative( n ); - }else{ - return n; - } -} -Node QuantConflictFind::evaluateTerm( Node n ) { - if( MatchGen::isHandledUfTerm( n ) ){ - Node f = MatchGen::getOperator( this, n ); - Node nn; - computeUfTerms( f ); - if( getEqualityEngine()->hasTerm( n ) ){ - computeArgReps( n ); - nn = d_uf_terms[f].existsTerm( n, d_arg_reps[n] ); - }else{ - std::vector< TNode > args; - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - Node c = evaluateTerm( n[i] ); - args.push_back( c ); - } - nn = d_uf_terms[f].existsTerm( n, args ); - } - if( !nn.isNull() ){ - Debug("qcf-eval") << "GT: Term " << nn << " for " << n << " hasTerm = " << getEqualityEngine()->hasTerm( n ) << std::endl; - return getRepresentative( nn ); - }else{ - Debug("qcf-eval") << "GT: No term for " << n << " hasTerm = " << getEqualityEngine()->hasTerm( n ) << std::endl; - return n; - } - }else if( n.getKind()==ITE ){ - int v = evaluate( n[0], false, false ); - if( v==1 ){ - return evaluateTerm( n[1] ); - }else if( v==-1 ){ - return evaluateTerm( n[2] ); - } - } - return getRepresentative( n ); -} - -/* -QuantConflictFind::EqcInfo * QuantConflictFind::getEqcInfo( Node n, bool doCreate ) { - std::map< Node, EqcInfo * >::iterator it2 = d_eqc_info.find( n ); - if( it2==d_eqc_info.end() ){ - if( doCreate ){ - EqcInfo * eqci = new EqcInfo( d_c ); - d_eqc_info[n] = eqci; - return eqci; - }else{ - return NULL; - } - } - return it2->second; -} -*/ - -QcfNodeIndex * QuantConflictFind::getQcfNodeIndex( Node eqc, Node f ) { - computeUfTerms( f ); - std::map< TNode, QcfNodeIndex >::iterator itut = d_eqc_uf_terms.find( f ); - if( itut==d_eqc_uf_terms.end() ){ - return NULL; - }else{ - if( eqc.isNull() ){ - return &itut->second; - }else{ - std::map< TNode, QcfNodeIndex >::iterator itute = itut->second.d_children.find( eqc ); - if( itute!=itut->second.d_children.end() ){ - return &itute->second; - }else{ - return NULL; - } - } - } -} - -QcfNodeIndex * QuantConflictFind::getQcfNodeIndex( Node f ) { - computeUfTerms( f ); - std::map< TNode, QcfNodeIndex >::iterator itut = d_uf_terms.find( f ); - if( itut!=d_uf_terms.end() ){ - return &itut->second; - }else{ - return NULL; - } -} - -/** new node */ -void QuantConflictFind::newEqClass( Node n ) { - //Trace("qcf-proc-debug") << "QCF : newEqClass : " << n << std::endl; - //Trace("qcf-proc2-debug") << "QCF : finished newEqClass : " << n << std::endl; -} - -/** merge */ -void QuantConflictFind::merge( Node a, Node b ) { - /* - if( b.getKind()==EQUAL ){ - if( a==d_true ){ - //will merge anyways - //merge( b[0], b[1] ); - }else if( a==d_false ){ - assertDisequal( b[0], b[1] ); - } - }else{ - Trace("qcf-proc") << "QCF : merge : " << a << " " << b << std::endl; - EqcInfo * eqc_b = getEqcInfo( b, false ); - EqcInfo * eqc_a = NULL; - if( eqc_b ){ - eqc_a = getEqcInfo( a ); - //move disequalities of b into a - for( NodeBoolMap::iterator it = eqc_b->d_diseq.begin(); it != eqc_b->d_diseq.end(); ++it ){ - if( (*it).second ){ - Node n = (*it).first; - EqcInfo * eqc_n = getEqcInfo( n, false ); - Assert( eqc_n ); - if( !eqc_n->isDisequal( a ) ){ - Assert( !eqc_a->isDisequal( n ) ); - eqc_n->setDisequal( a ); - eqc_a->setDisequal( n ); - //setEqual( eqc_a, eqc_b, a, n, false ); - } - eqc_n->setDisequal( b, false ); - } - } - ////move all previous EqcRegistry's regarding equalities within b - //for( NodeBoolMap::iterator it = eqc_b->d_rel_eqr_e.begin(); it != eqc_b->d_rel_eqr_e.end(); ++it ){ - // if( (*it).second ){ - // eqc_a->d_rel_eqr_e[(*it).first] = true; - // } - //} - } - //process new equalities - //setEqual( eqc_a, eqc_b, a, b, true ); - Trace("qcf-proc2") << "QCF : finished merge : " << a << " " << b << std::endl; - } - */ -} - -/** assert disequal */ -void QuantConflictFind::assertDisequal( Node a, Node b ) { - /* - a = getRepresentative( a ); - b = getRepresentative( b ); - Trace("qcf-proc") << "QCF : assert disequal : " << a << " " << b << std::endl; - EqcInfo * eqc_a = getEqcInfo( a ); - EqcInfo * eqc_b = getEqcInfo( b ); - if( !eqc_a->isDisequal( b ) ){ - Assert( !eqc_b->isDisequal( a ) ); - eqc_b->setDisequal( a ); - eqc_a->setDisequal( b ); - //setEqual( eqc_a, eqc_b, a, b, false ); - } - Trace("qcf-proc2") << "QCF : finished assert disequal : " << a << " " << b << std::endl; - */ -} - -//-------------------------------------------------- check function - -void QuantConflictFind::reset_round( Theory::Effort level ) { - d_needs_computeRelEqr = true; -} - -/** check */ -void QuantConflictFind::check( Theory::Effort level ) { - Trace("qcf-check") << "QCF : check : " << level << std::endl; - if( d_conflict ){ - Trace("qcf-check2") << "QCF : finished check : already in conflict." << std::endl; - if( level>=Theory::EFFORT_FULL ){ - Trace("qcf-warn") << "ALREADY IN CONFLICT? " << level << std::endl; - //Assert( false ); - } - }else{ - int addedLemmas = 0; - if( d_performCheck ){ - ++(d_statistics.d_inst_rounds); - double clSet = 0; - int prevEt = 0; - if( Trace.isOn("qcf-engine") ){ - prevEt = d_statistics.d_entailment_checks.getData(); - clSet = double(clock())/double(CLOCKS_PER_SEC); - Trace("qcf-engine") << "---Conflict Find Engine Round, effort = " << level << "---" << std::endl; - } - computeRelevantEqr(); - - //determine order for quantified formulas - std::vector< Node > qorder; - std::map< Node, bool > qassert; - //mark which are asserted - for( unsigned i=0; i<d_qassert.size(); i++ ){ - qassert[d_qassert[i]] = true; - } - //add which ones are specified in the order - for( unsigned i=0; i<d_quant_order.size(); i++ ){ - Node n = d_quant_order[i]; - if( std::find( qorder.begin(), qorder.end(), n )==qorder.end() && qassert.find( n )!=qassert.end() ){ - qorder.push_back( n ); - } - } - d_quant_order.clear(); - d_quant_order.insert( d_quant_order.begin(), qorder.begin(), qorder.end() ); - //add remaining - for( unsigned i=0; i<d_qassert.size(); i++ ){ - Node n = d_qassert[i]; - if( std::find( qorder.begin(), qorder.end(), n )==qorder.end() ){ - qorder.push_back( n ); - } - } - - if( Trace.isOn("qcf-debug") ){ - Trace("qcf-debug") << std::endl; - debugPrint("qcf-debug"); - Trace("qcf-debug") << std::endl; - } - short end_e = getMaxQcfEffort(); - for( short e = effort_conflict; e<=end_e; e++ ){ - d_effort = e; - Trace("qcf-check") << "Checking quantified formulas at effort " << e << "..." << std::endl; - for( unsigned j=0; j<qorder.size(); j++ ){ - Node q = qorder[j]; - QuantInfo * qi = &d_qinfo[q]; - - Assert( d_qinfo.find( q )!=d_qinfo.end() ); - if( qi->d_mg->isValid() ){ - Trace("qcf-check") << "Check quantified formula "; - debugPrintQuant("qcf-check", q); - Trace("qcf-check") << " : " << q << "..." << std::endl; - - Trace("qcf-check-debug") << "Reset round..." << std::endl; - qi->reset_round( this ); - //try to make a matches making the body false - Trace("qcf-check-debug") << "Get next match..." << std::endl; - while( qi->d_mg->getNextMatch( this, qi ) ){ - Trace("qcf-check") << "*** Produced match at effort " << e << " : " << std::endl; - qi->debugPrintMatch("qcf-check"); - Trace("qcf-check") << std::endl; - std::vector< int > assigned; - if( !qi->isMatchSpurious( this ) ){ - if( qi->completeMatch( this, assigned ) ){ - /* - if( options::qcfExp() && d_effort==effort_conflict ){ - std::vector< Node > exp; - if( qi->d_mg->getExplanation( this, qi, exp ) ){ - Trace("qcf-check-exp") << "Base explanation is : " << std::endl; - for( unsigned c=0; c<exp.size(); c++ ){ - Trace("qcf-check-exp") << " " << exp[c] << std::endl; - } - std::vector< TNode > c_exp; - eq::EqualityEngine* ee = ((uf::TheoryUF*)d_quantEngine->getTheoryEngine()->theoryOf( THEORY_UF ))->getEqualityEngine() ; - for( unsigned c=0; c<exp.size(); c++ ){ - bool pol = exp[c].getKind()!=NOT; - TNode lit = pol ? exp[c] : exp[c][0]; - Trace("qcf-check-exp") << "Explain " << lit << ", polarity " << pol << std::endl; - if( lit.getKind()==EQUAL ){ - if( !pol && !ee->areDisequal( lit[0], lit[1], true ) ){ - exit( 98 ); - }else if( pol && !ee->areEqual( lit[0], lit[1] ) ){ - exit( 99 ); - } - ee->explainEquality( lit[0], lit[1], pol, c_exp ); - }else{ - if( !ee->areEqual( lit, pol ? d_true : d_false ) ){ - exit( pol ? 96 : 97 ); - } - ee->explainPredicate( lit, pol, c_exp ); - } - } - std::vector< Node > c_lem; - Trace("qcf-check-exp") << "Actual explanation is : " << std::endl; - for( unsigned c=0; c<c_exp.size(); c++ ){ - Trace("qcf-check-exp") << " " << c_exp[c] << std::endl; - Node ccc = c_exp[c].negate(); - if( std::find( c_lem.begin(), c_lem.end(), ccc )==c_lem.end() ){ - c_lem.push_back( ccc ); - } - } - - c_lem.push_back( q.negate() ); - Node conf = NodeManager::currentNM()->mkNode( OR, c_lem ); - Trace("qcf-conflict") << "QCF conflict : " << conf << std::endl; - d_quantEngine->addLemma( conf, false ); - d_conflict.set( true ); - ++(d_statistics.d_conflict_inst); - ++addedLemmas; - break; - } - } - */ - std::vector< Node > terms; - qi->getMatch( terms ); - if( !qi->isTConstraintSpurious( this, terms ) ){ - if( Debug.isOn("qcf-check-inst") ){ - //if( e==effort_conflict ){ - Node inst = d_quantEngine->getInstantiation( q, terms ); - Debug("qcf-check-inst") << "Check instantiation " << inst << "..." << std::endl; - Assert( evaluate( inst )!=1 ); - Assert( evaluate( inst )==-1 || e>effort_conflict ); - //} - } - if( d_quantEngine->addInstantiation( q, terms, false ) ){ - Trace("qcf-check") << " ... Added instantiation" << std::endl; - Trace("qcf-inst") << "*** Was from effort " << e << " : " << std::endl; - qi->debugPrintMatch("qcf-inst"); - Trace("qcf-inst") << std::endl; - ++addedLemmas; - if( e==effort_conflict ){ - d_quant_order.insert( d_quant_order.begin(), q ); - d_conflict.set( true ); - ++(d_statistics.d_conflict_inst); - break; - }else if( e==effort_prop_eq ){ - ++(d_statistics.d_prop_inst); - } - }else{ - Trace("qcf-check") << " ... Failed to add instantiation" << std::endl; - //Assert( false ); - } - } - //clean up assigned - qi->revertMatch( assigned ); - d_tempCache.clear(); - }else{ - Trace("qcf-check") << " ... Spurious instantiation (cannot assign unassigned variables)" << std::endl; - } - }else{ - Trace("qcf-check") << " ... Spurious instantiation (match is inconsistent)" << std::endl; - } - } - if( d_conflict ){ - break; - } - } - } - if( addedLemmas>0 ){ - d_quantEngine->flushLemmas(); - break; - } - } - if( Trace.isOn("qcf-engine") ){ - double clSet2 = double(clock())/double(CLOCKS_PER_SEC); - Trace("qcf-engine") << "Finished conflict find engine, time = " << (clSet2-clSet); - if( addedLemmas>0 ){ - Trace("qcf-engine") << ", effort = " << ( d_effort==effort_conflict ? "conflict" : ( d_effort==effort_prop_eq ? "prop_eq" : "mc" ) ); - Trace("qcf-engine") << ", addedLemmas = " << addedLemmas; - } - Trace("qcf-engine") << std::endl; - int currEt = d_statistics.d_entailment_checks.getData(); - if( currEt!=prevEt ){ - Trace("qcf-engine") << " Entailment checks = " << ( currEt - prevEt ) << std::endl; - } - } - } - Trace("qcf-check2") << "QCF : finished check : " << level << std::endl; - } -} - -bool QuantConflictFind::needsCheck( Theory::Effort level ) { - d_performCheck = false; - if( options::quantConflictFind() && !d_conflict ){ - if( level==Theory::EFFORT_LAST_CALL ){ - d_performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_LAST_CALL; - }else if( level==Theory::EFFORT_FULL ){ - d_performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_DEFAULT; - }else if( level==Theory::EFFORT_STANDARD ){ - d_performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_STD; - } - } - return d_performCheck; -} - -void QuantConflictFind::computeRelevantEqr() { - if( d_needs_computeRelEqr ){ - d_needs_computeRelEqr = false; - Trace("qcf-check") << "Compute relevant equalities..." << std::endl; - d_uf_terms.clear(); - d_eqc_uf_terms.clear(); - d_eqcs.clear(); - d_model_basis.clear(); - d_arg_reps.clear(); - //double clSet = 0; - //if( Trace.isOn("qcf-opt") ){ - // clSet = double(clock())/double(CLOCKS_PER_SEC); - //} - - //long nTermst = 0; - //long nTerms = 0; - //long nEqc = 0; - - //which nodes are irrelevant for disequality matches - std::map< TNode, bool > irrelevant_dnode; - //now, store matches - eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( getEqualityEngine() ); - while( !eqcs_i.isFinished() ){ - //nEqc++; - Node r = (*eqcs_i); - TypeNode rtn = r.getType(); - if( options::qcfMode()==QCF_MC ){ - std::map< TypeNode, std::vector< TNode > >::iterator itt = d_eqcs.find( rtn ); - if( itt==d_eqcs.end() ){ - Node mb = getQuantifiersEngine()->getTermDatabase()->getModelBasisTerm( rtn ); - if( !getEqualityEngine()->hasTerm( mb ) ){ - Trace("qcf-warn") << "WARNING: Model basis term does not exist!" << std::endl; - Assert( false ); - } - Node mbr = getRepresentative( mb ); - if( mbr!=r ){ - d_eqcs[rtn].push_back( mbr ); - } - d_eqcs[rtn].push_back( r ); - d_model_basis[rtn] = mb; - }else{ - itt->second.push_back( r ); - } - }else{ - d_eqcs[rtn].push_back( r ); - } - /* - eq::EqClassIterator eqc_i = eq::EqClassIterator( r, getEqualityEngine() ); - while( !eqc_i.isFinished() ){ - TNode n = (*eqc_i); - if( n.hasBoundVar() ){ - std::cout << "BAD TERM IN DB : " << n << std::endl; - exit( 199 ); - } - ++eqc_i; - } - - */ - - //if( r.getType().isInteger() ){ - // Trace("qcf-mv") << "Model value for eqc(" << r << ") : " << d_quantEngine->getValuation().getModelValue( r ) << std::endl; - //} - //EqcInfo * eqcir = getEqcInfo( r, false ); - //get relevant nodes that we are disequal from - /* - std::vector< Node > deqc; - if( eqcir ){ - for( NodeBoolMap::iterator it = eqcir->d_diseq.begin(); it != eqcir->d_diseq.end(); ++it ){ - if( (*it).second ){ - //Node rd = (*it).first; - //if( rd!=getRepresentative( rd ) ){ - // std::cout << "Bad rep!" << std::endl; - // exit( 0 ); - //} - deqc.push_back( (*it).first ); - } - } - } - */ - //process disequalities - /* - eq::EqClassIterator eqc_i = eq::EqClassIterator( r, getEqualityEngine() ); - while( !eqc_i.isFinished() ){ - TNode n = (*eqc_i); - if( n.getKind()!=EQUAL ){ - nTermst++; - //node_to_rep[n] = r; - //if( n.getNumChildren()>0 ){ - // if( n.getKind()!=APPLY_UF ){ - // std::cout << n.getKind() << " " << n.getOperator() << " " << n << std::endl; - // } - //} - if( !quantifiers::TermDb::hasBoundVarAttr( n ) ){ //temporary - - bool isRedundant; - std::map< TNode, std::vector< TNode > >::iterator it_na; - TNode fn; - if( MatchGen::isHandledUfTerm( n ) ){ - Node f = MatchGen::getOperator( this, n ); - computeArgReps( n ); - it_na = d_arg_reps.find( n ); - Assert( it_na!=d_arg_reps.end() ); - Node nadd = d_eqc_uf_terms[f].d_children[r].addTerm( n, d_arg_reps[n] ); - isRedundant = (nadd!=n); - d_uf_terms[f].addTerm( n, d_arg_reps[n] ); - }else{ - isRedundant = false; - } - nTerms += isRedundant ? 0 : 1; - }else{ - if( Debug.isOn("qcf-nground") ){ - Debug("qcf-nground") << "Non-ground term in eqc : " << n << std::endl; - Assert( false ); - } - } - } - ++eqc_i; - } - */ - ++eqcs_i; - } - /* - if( Trace.isOn("qcf-opt") ){ - double clSet2 = double(clock())/double(CLOCKS_PER_SEC); - Trace("qcf-opt") << "Compute rel eqc : " << std::endl; - Trace("qcf-opt") << " " << nEqc << " equivalence classes. " << std::endl; - Trace("qcf-opt") << " " << nTerms << " / " << nTermst << " terms." << std::endl; - Trace("qcf-opt") << " Time : " << (clSet2-clSet) << std::endl; - } - */ - } -} - -void QuantConflictFind::computeArgReps( TNode n ) { - if( d_arg_reps.find( n )==d_arg_reps.end() ){ - Assert( MatchGen::isHandledUfTerm( n ) ); - for( unsigned j=0; j<n.getNumChildren(); j++ ){ - d_arg_reps[n].push_back( getRepresentative( n[j] ) ); - } - } -} - -void QuantConflictFind::computeUfTerms( TNode f ) { - if( d_uf_terms.find( f )==d_uf_terms.end() ){ - d_uf_terms[f].clear(); - unsigned nt = d_quantEngine->getTermDatabase()->getNumGroundTerms( f ); - for( unsigned i=0; i<nt; i++ ){ - Node n = d_quantEngine->getTermDatabase()->d_op_map[f][i]; - if( getEqualityEngine()->hasTerm( n ) && !n.getAttribute(NoMatchAttribute()) ){ - Node r = getRepresentative( n ); - computeArgReps( n ); - d_eqc_uf_terms[f].d_children[r].addTerm( n, d_arg_reps[n] ); - d_uf_terms[f].addTerm( n, d_arg_reps[n] ); - } - } - } -} - -//-------------------------------------------------- debugging - - -void QuantConflictFind::debugPrint( const char * c ) { - //print the equivalance classes - Trace(c) << "----------EQ classes" << std::endl; - eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( getEqualityEngine() ); - while( !eqcs_i.isFinished() ){ - Node n = (*eqcs_i); - //if( !n.getType().isInteger() ){ - Trace(c) << " - " << n << " : {"; - eq::EqClassIterator eqc_i = eq::EqClassIterator( n, getEqualityEngine() ); - bool pr = false; - while( !eqc_i.isFinished() ){ - Node nn = (*eqc_i); - if( nn.getKind()!=EQUAL && nn!=n ){ - Trace(c) << (pr ? "," : "" ) << " " << nn; - pr = true; - } - ++eqc_i; - } - Trace(c) << (pr ? " " : "" ) << "}" << std::endl; - /* - EqcInfo * eqcn = getEqcInfo( n, false ); - if( eqcn ){ - Trace(c) << " DEQ : {"; - pr = false; - for( NodeBoolMap::iterator it = eqcn->d_diseq.begin(); it != eqcn->d_diseq.end(); ++it ){ - if( (*it).second ){ - Trace(c) << (pr ? "," : "" ) << " " << (*it).first; - pr = true; - } - } - Trace(c) << (pr ? " " : "" ) << "}" << std::endl; - } - //} - */ - ++eqcs_i; - } -} - -void QuantConflictFind::debugPrintQuant( const char * c, Node q ) { - Trace(c) << "Q" << d_quant_id[q]; -} - -void QuantConflictFind::debugPrintQuantBody( const char * c, Node q, Node n, bool doVarNum ) { - if( n.getNumChildren()==0 ){ - Trace(c) << n; - }else if( doVarNum && d_qinfo[q].d_var_num.find( n )!=d_qinfo[q].d_var_num.end() ){ - Trace(c) << "?x" << d_qinfo[q].d_var_num[n]; - }else{ - Trace(c) << "("; - if( n.getKind()==APPLY_UF ){ - Trace(c) << n.getOperator(); - }else{ - Trace(c) << n.getKind(); - } - for( unsigned i=0; i<n.getNumChildren(); i++ ){ - Trace(c) << " "; - debugPrintQuantBody( c, q, n[i] ); - } - Trace(c) << ")"; - } -} - -QuantConflictFind::Statistics::Statistics(): - d_inst_rounds("QuantConflictFind::Inst_Rounds", 0), - d_conflict_inst("QuantConflictFind::Instantiations_Conflict_Find", 0 ), - d_prop_inst("QuantConflictFind::Instantiations_Prop", 0 ), - d_entailment_checks("QuantConflictFind::Entailment_Checks",0) -{ - StatisticsRegistry::registerStat(&d_inst_rounds); - StatisticsRegistry::registerStat(&d_conflict_inst); - StatisticsRegistry::registerStat(&d_prop_inst); - StatisticsRegistry::registerStat(&d_entailment_checks); -} - -QuantConflictFind::Statistics::~Statistics(){ - StatisticsRegistry::unregisterStat(&d_inst_rounds); - StatisticsRegistry::unregisterStat(&d_conflict_inst); - StatisticsRegistry::unregisterStat(&d_prop_inst); - StatisticsRegistry::unregisterStat(&d_entailment_checks); -} - -TNode QuantConflictFind::getZero( Kind k ) { - std::map< Kind, Node >::iterator it = d_zero.find( k ); - if( it==d_zero.end() ){ - Node nn; - if( k==PLUS ){ - nn = NodeManager::currentNM()->mkConst( Rational(0) ); - } - d_zero[k] = nn; - return nn; - }else{ - return it->second; - } -} - - -} +/********************* */
+/*! \file quant_conflict_find.cpp
+ ** \verbatim
+ ** Original author: Andrew Reynolds
+ ** Major contributors: none
+ ** Minor contributors (to current version): none
+ ** This file is part of the CVC4 project.
+ ** Copyright (c) 2009-2014 New York University and The University of Iowa
+ ** See the file COPYING in the top-level source directory for licensing
+ ** information.\endverbatim
+ **
+ ** \brief quant conflict find class
+ **
+ **/
+
+#include <vector>
+
+#include "theory/quantifiers/quant_conflict_find.h"
+#include "theory/quantifiers/quant_util.h"
+#include "theory/theory_engine.h"
+#include "theory/quantifiers/options.h"
+#include "theory/quantifiers/term_database.h"
+#include "theory/quantifiers/trigger.h"
+
+using namespace CVC4;
+using namespace CVC4::kind;
+using namespace CVC4::theory;
+using namespace CVC4::theory::quantifiers;
+using namespace std;
+
+namespace CVC4 {
+
+
+
+void QuantInfo::initialize( Node q, Node qn ) {
+ d_q = q;
+ for( unsigned i=0; i<q[0].getNumChildren(); i++ ){
+ d_match.push_back( TNode::null() );
+ d_match_term.push_back( TNode::null() );
+ }
+
+ //register the variables
+ for( unsigned i=0; i<q[0].getNumChildren(); i++ ){
+ d_var_num[q[0][i]] = i;
+ d_vars.push_back( q[0][i] );
+ }
+
+ registerNode( qn, true, true );
+
+
+ Trace("qcf-qregister") << "- Make match gen structure..." << std::endl;
+ d_mg = new MatchGen( this, qn );
+
+ if( d_mg->isValid() ){
+ /*
+ for( unsigned j=0; j<q[0].getNumChildren(); j++ ){
+ if( d_inMatchConstraint.find( q[0][j] )==d_inMatchConstraint.end() ){
+ Trace("qcf-invalid") << "QCF invalid : variable " << q[0][j] << " does not exist in a matching constraint." << std::endl;
+ d_mg->setInvalid();
+ break;
+ }
+ }
+ */
+ if( d_mg->isValid() ){
+ for( unsigned j=q[0].getNumChildren(); j<d_vars.size(); j++ ){
+ if( d_vars[j].getKind()!=BOUND_VARIABLE ){
+ d_var_mg[j] = NULL;
+ bool is_tsym = false;
+ if( !MatchGen::isHandledUfTerm( d_vars[j] ) && d_vars[j].getKind()!=ITE ){
+ is_tsym = true;
+ d_tsym_vars.push_back( j );
+ }
+ if( !is_tsym || options::qcfTConstraint() ){
+ d_var_mg[j] = new MatchGen( this, d_vars[j], true );
+ }
+ if( !d_var_mg[j] || !d_var_mg[j]->isValid() ){
+ Trace("qcf-invalid") << "QCF invalid : cannot match for " << d_vars[j] << std::endl;
+ d_mg->setInvalid();
+ break;
+ }else{
+ std::vector< int > bvars;
+ d_var_mg[j]->determineVariableOrder( this, bvars );
+ }
+ }
+ }
+ if( d_mg->isValid() ){
+ std::vector< int > bvars;
+ d_mg->determineVariableOrder( this, bvars );
+ }
+ }
+ }else{
+ Trace("qcf-invalid") << "QCF invalid : body of formula cannot be processed." << std::endl;
+ }
+ Trace("qcf-qregister-summary") << "QCF register : " << ( d_mg->isValid() ? "VALID " : "INVALID" ) << " : " << q << std::endl;
+}
+
+void QuantInfo::registerNode( Node n, bool hasPol, bool pol, bool beneathQuant ) {
+ Trace("qcf-qregister-debug2") << "Register : " << n << std::endl;
+ if( n.getKind()==FORALL ){
+ registerNode( n[1], hasPol, pol, true );
+ }else{
+ if( !MatchGen::isHandledBoolConnective( n ) ){
+ if( n.hasBoundVar() ){
+ //literals
+ if( n.getKind()==EQUAL ){
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ flatten( n[i], beneathQuant );
+ }
+ }else if( MatchGen::isHandledUfTerm( n ) ){
+ flatten( n, beneathQuant );
+ }else if( n.getKind()==ITE ){
+ for( unsigned i=1; i<=2; i++ ){
+ flatten( n[i], beneathQuant );
+ }
+ registerNode( n[0], false, pol, beneathQuant );
+ }else if( options::qcfTConstraint() ){
+ //a theory-specific predicate
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ flatten( n[i], beneathQuant );
+ }
+ }
+ }
+ }else{
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ bool newHasPol;
+ bool newPol;
+ QuantPhaseReq::getPolarity( n, i, hasPol, pol, newHasPol, newPol );
+ //QcfNode * qcfc = new QcfNode( d_c );
+ //qcfc->d_parent = qcf;
+ //qcf->d_child[i] = qcfc;
+ registerNode( n[i], newHasPol, newPol, beneathQuant );
+ }
+ }
+ }
+}
+
+void QuantInfo::flatten( Node n, bool beneathQuant ) {
+ Trace("qcf-qregister-debug2") << "Flatten : " << n << std::endl;
+ if( n.hasBoundVar() ){
+ if( n.getKind()==BOUND_VARIABLE ){
+ d_inMatchConstraint[n] = true;
+ }
+ //if( MatchGen::isHandledUfTerm( n ) || n.getKind()==ITE ){
+ if( d_var_num.find( n )==d_var_num.end() ){
+ Trace("qcf-qregister-debug2") << "Add FLATTEN VAR : " << n << std::endl;
+ d_var_num[n] = d_vars.size();
+ d_vars.push_back( n );
+ d_match.push_back( TNode::null() );
+ d_match_term.push_back( TNode::null() );
+ if( n.getKind()==ITE ){
+ registerNode( n, false, false );
+ }else{
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ flatten( n[i], beneathQuant );
+ }
+ }
+ }else{
+ Trace("qcf-qregister-debug2") << "...already processed" << std::endl;
+ }
+ }else{
+ Trace("qcf-qregister-debug2") << "...is ground." << std::endl;
+ }
+}
+
+
+void QuantInfo::reset_round( QuantConflictFind * p ) {
+ for( unsigned i=0; i<d_match.size(); i++ ){
+ d_match[i] = TNode::null();
+ d_match_term[i] = TNode::null();
+ }
+ d_curr_var_deq.clear();
+ d_tconstraints.clear();
+ //add built-in variable constraints
+ for( unsigned r=0; r<2; r++ ){
+ for( std::map< int, std::vector< Node > >::iterator it = d_var_constraint[r].begin();
+ it != d_var_constraint[r].end(); ++it ){
+ for( unsigned j=0; j<it->second.size(); j++ ){
+ Node rr = it->second[j];
+ if( !isVar( rr ) ){
+ rr = p->getRepresentative( rr );
+ }
+ if( addConstraint( p, it->first, rr, r==0 )==-1 ){
+ d_var_constraint[0].clear();
+ d_var_constraint[1].clear();
+ //quantified formula is actually equivalent to true
+ Trace("qcf-qregister") << "Quantifier is equivalent to true!!!" << std::endl;
+ d_mg->d_children.clear();
+ d_mg->d_n = NodeManager::currentNM()->mkConst( true );
+ d_mg->d_type = MatchGen::typ_ground;
+ return;
+ }
+ }
+ }
+ }
+ d_mg->reset_round( p );
+ for( std::map< int, MatchGen * >::iterator it = d_var_mg.begin(); it != d_var_mg.end(); ++it ){
+ it->second->reset_round( p );
+ }
+ //now, reset for matching
+ d_mg->reset( p, false, this );
+}
+
+int QuantInfo::getCurrentRepVar( int v ) {
+ if( v!=-1 && !d_match[v].isNull() ){
+ int vn = getVarNum( d_match[v] );
+ if( vn!=-1 ){
+ //int vr = getCurrentRepVar( vn );
+ //d_match[v] = d_vars[vr];
+ //return vr;
+ return getCurrentRepVar( vn );
+ }
+ }
+ return v;
+}
+
+TNode QuantInfo::getCurrentValue( TNode n ) {
+ int v = getVarNum( n );
+ if( v==-1 ){
+ return n;
+ }else{
+ if( d_match[v].isNull() ){
+ return n;
+ }else{
+ Assert( getVarNum( d_match[v] )!=v );
+ return getCurrentValue( d_match[v] );
+ }
+ }
+}
+
+TNode QuantInfo::getCurrentExpValue( TNode n ) {
+ int v = getVarNum( n );
+ if( v==-1 ){
+ return n;
+ }else{
+ if( d_match[v].isNull() ){
+ return n;
+ }else{
+ Assert( getVarNum( d_match[v] )!=v );
+ if( d_match_term[v].isNull() ){
+ return getCurrentValue( d_match[v] );
+ }else{
+ return d_match_term[v];
+ }
+ }
+ }
+}
+
+bool QuantInfo::getCurrentCanBeEqual( QuantConflictFind * p, int v, TNode n, bool chDiseq ) {
+ //check disequalities
+ std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( v );
+ if( itd!=d_curr_var_deq.end() ){
+ for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){
+ Node cv = getCurrentValue( it->first );
+ Debug("qcf-ccbe") << "compare " << cv << " " << n << std::endl;
+ if( cv==n ){
+ return false;
+ }else if( chDiseq && !isVar( n ) && !isVar( cv ) ){
+ //they must actually be disequal if we are looking for conflicts
+ if( !p->areDisequal( n, cv ) ){
+ //TODO : check for entailed disequal
+
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+}
+
+int QuantInfo::addConstraint( QuantConflictFind * p, int v, TNode n, bool polarity ) {
+ v = getCurrentRepVar( v );
+ int vn = getVarNum( n );
+ vn = vn==-1 ? -1 : getCurrentRepVar( vn );
+ n = getCurrentValue( n );
+ return addConstraint( p, v, n, vn, polarity, false );
+}
+
+int QuantInfo::addConstraint( QuantConflictFind * p, int v, TNode n, int vn, bool polarity, bool doRemove ) {
+ //for handling equalities between variables, and disequalities involving variables
+ Debug("qcf-match-debug") << "- " << (doRemove ? "un" : "" ) << "constrain : " << v << " -> " << n << " (cv=" << getCurrentValue( n ) << ")";
+ Debug("qcf-match-debug") << ", (vn=" << vn << "), polarity = " << polarity << std::endl;
+ Assert( doRemove || n==getCurrentValue( n ) );
+ Assert( doRemove || v==getCurrentRepVar( v ) );
+ Assert( doRemove || vn==getCurrentRepVar( getVarNum( n ) ) );
+ if( polarity ){
+ if( vn!=v ){
+ if( doRemove ){
+ if( vn!=-1 ){
+ //if set to this in the opposite direction, clean up opposite instead
+ // std::map< int, TNode >::iterator itmn = d_match.find( vn );
+ if( d_match[vn]==d_vars[v] ){
+ return addConstraint( p, vn, d_vars[v], v, true, true );
+ }else{
+ //unsetting variables equal
+ std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( vn );
+ if( itd!=d_curr_var_deq.end() ){
+ //remove disequalities owned by this
+ std::vector< TNode > remDeq;
+ for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){
+ if( it->second==v ){
+ remDeq.push_back( it->first );
+ }
+ }
+ for( unsigned i=0; i<remDeq.size(); i++ ){
+ d_curr_var_deq[vn].erase( remDeq[i] );
+ }
+ }
+ }
+ }
+ d_match[v] = TNode::null();
+ return 1;
+ }else{
+ //std::map< int, TNode >::iterator itm = d_match.find( v );
+
+ if( vn!=-1 ){
+ Debug("qcf-match-debug") << " ...Variable bound to variable" << std::endl;
+ //std::map< int, TNode >::iterator itmn = d_match.find( vn );
+ if( d_match[v].isNull() ){
+ //setting variables equal
+ bool alreadySet = false;
+ if( !d_match[vn].isNull() ){
+ alreadySet = true;
+ Assert( !isVar( d_match[vn] ) );
+ }
+
+ //copy or check disequalities
+ std::map< int, std::map< TNode, int > >::iterator itd = d_curr_var_deq.find( v );
+ if( itd!=d_curr_var_deq.end() ){
+ for( std::map< TNode, int >::iterator it = itd->second.begin(); it != itd->second.end(); ++it ){
+ Node dv = getCurrentValue( it->first );
+ if( !alreadySet ){
+ if( d_curr_var_deq[vn].find( dv )==d_curr_var_deq[vn].end() ){
+ d_curr_var_deq[vn][dv] = v;
+ }
+ }else{
+ if( !p->areMatchDisequal( d_match[vn], dv ) ){
+ Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl;
+ return -1;
+ }
+ }
+ }
+ }
+ if( alreadySet ){
+ n = getCurrentValue( n );
+ }
+ }else{
+ if( d_match[vn].isNull() ){
+ Debug("qcf-match-debug") << " ...Reverse direction" << std::endl;
+ //set the opposite direction
+ return addConstraint( p, vn, d_vars[v], v, true, false );
+ }else{
+ Debug("qcf-match-debug") << " -> Both variables bound, compare" << std::endl;
+ //are they currently equal
+ return p->areMatchEqual( d_match[v], d_match[vn] ) ? 0 : -1;
+ }
+ }
+ }else{
+ Debug("qcf-match-debug") << " ...Variable bound to ground" << std::endl;
+ if( d_match[v].isNull() ){
+ }else{
+ //compare ground values
+ Debug("qcf-match-debug") << " -> Ground value, compare " << d_match[v] << " "<< n << std::endl;
+ return p->areMatchEqual( d_match[v], n ) ? 0 : -1;
+ }
+ }
+ if( setMatch( p, v, n ) ){
+ Debug("qcf-match-debug") << " -> success" << std::endl;
+ return 1;
+ }else{
+ Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl;
+ return -1;
+ }
+ }
+ }else{
+ Debug("qcf-match-debug") << " -> redundant, variable identity" << std::endl;
+ return 0;
+ }
+ }else{
+ if( vn==v ){
+ Debug("qcf-match-debug") << " -> fail, variable identity" << std::endl;
+ return -1;
+ }else{
+ if( doRemove ){
+ Assert( d_curr_var_deq[v].find( n )!=d_curr_var_deq[v].end() );
+ d_curr_var_deq[v].erase( n );
+ return 1;
+ }else{
+ if( d_curr_var_deq[v].find( n )==d_curr_var_deq[v].end() ){
+ //check if it respects equality
+ //std::map< int, TNode >::iterator itm = d_match.find( v );
+ if( !d_match[v].isNull() ){
+ TNode nv = getCurrentValue( n );
+ if( !p->areMatchDisequal( nv, d_match[v] ) ){
+ Debug("qcf-match-debug") << " -> fail, conflicting disequality" << std::endl;
+ return -1;
+ }
+ }
+ d_curr_var_deq[v][n] = v;
+ Debug("qcf-match-debug") << " -> success" << std::endl;
+ return 1;
+ }else{
+ Debug("qcf-match-debug") << " -> redundant disequality" << std::endl;
+ return 0;
+ }
+ }
+ }
+ }
+}
+
+bool QuantInfo::isConstrainedVar( int v ) {
+ if( d_curr_var_deq.find( v )!=d_curr_var_deq.end() && !d_curr_var_deq[v].empty() ){
+ return true;
+ }else{
+ Node vv = getVar( v );
+ //for( std::map< int, TNode >::iterator it = d_match.begin(); it != d_match.end(); ++it ){
+ for( unsigned i=0; i<d_match.size(); i++ ){
+ if( d_match[i]==vv ){
+ return true;
+ }
+ }
+ for( std::map< int, std::map< TNode, int > >::iterator it = d_curr_var_deq.begin(); it != d_curr_var_deq.end(); ++it ){
+ for( std::map< TNode, int >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ){
+ if( it2->first==vv ){
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
+
+bool QuantInfo::setMatch( QuantConflictFind * p, int v, TNode n ) {
+ if( getCurrentCanBeEqual( p, v, n ) ){
+ Debug("qcf-match-debug") << "-- bind : " << v << " -> " << n << ", checked " << d_curr_var_deq[v].size() << " disequalities" << std::endl;
+ d_match[v] = n;
+ return true;
+ }else{
+ return false;
+ }
+}
+
+bool QuantInfo::isMatchSpurious( QuantConflictFind * p ) {
+ for( int i=0; i<getNumVars(); i++ ){
+ //std::map< int, TNode >::iterator it = d_match.find( i );
+ if( !d_match[i].isNull() ){
+ if( !getCurrentCanBeEqual( p, i, d_match[i], p->d_effort==QuantConflictFind::effort_conflict ) ){
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool QuantInfo::isTConstraintSpurious( QuantConflictFind * p, std::vector< Node >& terms ) {
+ if( !d_tconstraints.empty() ){
+ //check constraints
+ for( std::map< Node, bool >::iterator it = d_tconstraints.begin(); it != d_tconstraints.end(); ++it ){
+ //apply substitution to the tconstraint
+ Node cons = it->first.substitute( p->getQuantifiersEngine()->getTermDatabase()->d_vars[d_q].begin(),
+ p->getQuantifiersEngine()->getTermDatabase()->d_vars[d_q].end(),
+ terms.begin(), terms.end() );
+ cons = it->second ? cons : cons.negate();
+ if( !entailmentTest( p, cons, p->d_effort==QuantConflictFind::effort_conflict ) ){
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool QuantInfo::entailmentTest( QuantConflictFind * p, Node lit, bool chEnt ) {
+ Trace("qcf-tconstraint-debug") << "Check : " << lit << std::endl;
+ Node rew = Rewriter::rewrite( lit );
+ if( rew==p->d_false ){
+ Trace("qcf-tconstraint-debug") << "...constraint " << lit << " is disentailed (rewrites to false)." << std::endl;
+ return false;
+ }else if( rew!=p->d_true ){
+ //if checking for conflicts, we must be sure that the constraint is entailed
+ if( chEnt ){
+ //check if it is entailed
+ Trace("qcf-tconstraint-debug") << "Check entailment of " << rew << "..." << std::endl;
+ std::pair<bool, Node> et = p->getQuantifiersEngine()->getTheoryEngine()->entailmentCheck(THEORY_OF_TYPE_BASED, rew );
+ ++(p->d_statistics.d_entailment_checks);
+ Trace("qcf-tconstraint-debug") << "ET result : " << et.first << " " << et.second << std::endl;
+ if( !et.first ){
+ Trace("qcf-tconstraint-debug") << "...cannot show entailment of " << rew << "." << std::endl;
+ return false;
+ }else{
+ return true;
+ }
+ }else{
+ Trace("qcf-tconstraint-debug") << "...does not need to be entailed." << std::endl;
+ return true;
+ }
+ }else{
+ Trace("qcf-tconstraint-debug") << "...rewrites to true." << std::endl;
+ return true;
+ }
+}
+
+bool QuantInfo::completeMatch( QuantConflictFind * p, std::vector< int >& assigned, bool doContinue ) {
+ //assign values for variables that were unassigned (usually not necessary, but handles corner cases)
+ bool doFail = false;
+ bool success = true;
+ if( doContinue ){
+ doFail = true;
+ success = false;
+ }else{
+ //solve for interpreted symbol matches
+ // this breaks the invariant that all introduced constraints are over existing terms
+ for( int i=(int)(d_tsym_vars.size()-1); i>=0; i-- ){
+ int index = d_tsym_vars[i];
+ TNode v = getCurrentValue( d_vars[index] );
+ int slv_v = -1;
+ if( v==d_vars[index] ){
+ slv_v = index;
+ }
+ Trace("qcf-tconstraint-debug") << "Solve " << d_vars[index] << " = " << v << " " << d_vars[index].getKind() << std::endl;
+ if( d_vars[index].getKind()==PLUS || d_vars[index].getKind()==MULT ){
+ Kind k = d_vars[index].getKind();
+ std::vector< TNode > children;
+ for( unsigned j=0; j<d_vars[index].getNumChildren(); j++ ){
+ int vn = getVarNum( d_vars[index][j] );
+ if( vn!=-1 ){
+ TNode vv = getCurrentValue( d_vars[index][j] );
+ if( vv==d_vars[index][j] ){
+ //we will assign this
+ if( slv_v==-1 ){
+ Trace("qcf-tconstraint-debug") << "...will solve for var #" << vn << std::endl;
+ slv_v = vn;
+ if( p->d_effort!=QuantConflictFind::effort_conflict ){
+ break;
+ }
+ }else{
+ Node z = p->getZero( k );
+ if( !z.isNull() ){
+ Trace("qcf-tconstraint-debug") << "...set " << d_vars[vn] << " = " << z << std::endl;
+ assigned.push_back( vn );
+ if( !setMatch( p, vn, z ) ){
+ success = false;
+ break;
+ }
+ }
+ }
+ }else{
+ Trace("qcf-tconstraint-debug") << "...sum value " << vv << std::endl;
+ children.push_back( vv );
+ }
+ }else{
+ Trace("qcf-tconstraint-debug") << "...sum " << d_vars[index][j] << std::endl;
+ children.push_back( d_vars[index][j] );
+ }
+ }
+ if( success ){
+ if( slv_v!=-1 ){
+ Node lhs;
+ if( children.empty() ){
+ lhs = p->getZero( k );
+ }else if( children.size()==1 ){
+ lhs = children[0];
+ }else{
+ lhs = NodeManager::currentNM()->mkNode( k, children );
+ }
+ Node sum;
+ if( v==d_vars[index] ){
+ sum = lhs;
+ }else{
+ if( p->d_effort==QuantConflictFind::effort_conflict ){
+ Kind kn = k;
+ if( d_vars[index].getKind()==PLUS ){
+ kn = MINUS;
+ }
+ if( kn!=k ){
+ sum = NodeManager::currentNM()->mkNode( kn, v, lhs );
+ }
+ }
+ }
+ if( !sum.isNull() ){
+ assigned.push_back( slv_v );
+ Trace("qcf-tconstraint-debug") << "...set " << d_vars[slv_v] << " = " << sum << std::endl;
+ if( !setMatch( p, slv_v, sum ) ){
+ success = false;
+ }
+ p->d_tempCache.push_back( sum );
+ }
+ }else{
+ //must show that constraint is met
+ Node sum = NodeManager::currentNM()->mkNode( k, children );
+ Node eq = sum.eqNode( v );
+ if( !entailmentTest( p, eq ) ){
+ success = false;
+ }
+ p->d_tempCache.push_back( sum );
+ }
+ }
+ }
+
+ if( !success ){
+ break;
+ }
+ }
+ if( success ){
+ //check what is left to assign
+ d_unassigned.clear();
+ d_unassigned_tn.clear();
+ std::vector< int > unassigned[2];
+ std::vector< TypeNode > unassigned_tn[2];
+ for( int i=0; i<getNumVars(); i++ ){
+ if( d_match[i].isNull() ){
+ int rindex = d_var_mg.find( i )==d_var_mg.end() ? 1 : 0;
+ unassigned[rindex].push_back( i );
+ unassigned_tn[rindex].push_back( getVar( i ).getType() );
+ assigned.push_back( i );
+ }
+ }
+ d_unassigned_nvar = unassigned[0].size();
+ for( unsigned i=0; i<2; i++ ){
+ d_unassigned.insert( d_unassigned.end(), unassigned[i].begin(), unassigned[i].end() );
+ d_unassigned_tn.insert( d_unassigned_tn.end(), unassigned_tn[i].begin(), unassigned_tn[i].end() );
+ }
+ d_una_eqc_count.clear();
+ d_una_index = 0;
+ }
+ }
+
+ if( !d_unassigned.empty() && ( success || doContinue ) ){
+ Trace("qcf-check") << "Assign to unassigned..." << std::endl;
+ do {
+ if( doFail ){
+ Trace("qcf-check-unassign") << "Failure, try again..." << std::endl;
+ }
+ bool invalidMatch = false;
+ while( ( d_una_index>=0 && (int)d_una_index<(int)d_unassigned.size() ) || invalidMatch || doFail ){
+ invalidMatch = false;
+ if( !doFail && d_una_index==(int)d_una_eqc_count.size() ){
+ //check if it has now been assigned
+ if( d_una_index<d_unassigned_nvar ){
+ if( !isConstrainedVar( d_unassigned[d_una_index] ) ){
+ d_una_eqc_count.push_back( -1 );
+ }else{
+ d_var_mg[ d_unassigned[d_una_index] ]->reset( p, true, this );
+ d_una_eqc_count.push_back( 0 );
+ }
+ }else{
+ d_una_eqc_count.push_back( 0 );
+ }
+ }else{
+ bool failed = false;
+ if( !doFail ){
+ if( d_una_index<d_unassigned_nvar ){
+ if( !isConstrainedVar( d_unassigned[d_una_index] ) ){
+ Trace("qcf-check-unassign") << "Succeeded, variable unconstrained at " << d_una_index << std::endl;
+ d_una_index++;
+ }else if( d_var_mg[d_unassigned[d_una_index]]->getNextMatch( p, this ) ){
+ Trace("qcf-check-unassign") << "Succeeded match with mg at " << d_una_index << std::endl;
+ d_una_index++;
+ }else{
+ failed = true;
+ Trace("qcf-check-unassign") << "Failed match with mg at " << d_una_index << std::endl;
+ }
+ }else{
+ Assert( doFail || d_una_index==(int)d_una_eqc_count.size()-1 );
+ if( d_una_eqc_count[d_una_index]<(int)p->d_eqcs[d_unassigned_tn[d_una_index]].size() ){
+ int currIndex = d_una_eqc_count[d_una_index];
+ d_una_eqc_count[d_una_index]++;
+ Trace("qcf-check-unassign") << d_unassigned[d_una_index] << "->" << p->d_eqcs[d_unassigned_tn[d_una_index]][currIndex] << std::endl;
+ if( setMatch( p, d_unassigned[d_una_index], p->d_eqcs[d_unassigned_tn[d_una_index]][currIndex] ) ){
+ d_match_term[d_unassigned[d_una_index]] = TNode::null();
+ Trace("qcf-check-unassign") << "Succeeded match " << d_una_index << std::endl;
+ d_una_index++;
+ }else{
+ Trace("qcf-check-unassign") << "Failed match " << d_una_index << std::endl;
+ invalidMatch = true;
+ }
+ }else{
+ failed = true;
+ Trace("qcf-check-unassign") << "No more matches " << d_una_index << std::endl;
+ }
+ }
+ }
+ if( doFail || failed ){
+ do{
+ if( !doFail ){
+ d_una_eqc_count.pop_back();
+ }else{
+ doFail = false;
+ }
+ d_una_index--;
+ }while( d_una_index>=0 && d_una_eqc_count[d_una_index]==-1 );
+ }
+ }
+ }
+ success = d_una_index>=0;
+ if( success ){
+ doFail = true;
+ Trace("qcf-check-unassign") << " Try: " << std::endl;
+ for( unsigned i=0; i<d_unassigned.size(); i++ ){
+ int ui = d_unassigned[i];
+ if( !d_match[ui].isNull() ){
+ Trace("qcf-check-unassign") << " Assigned #" << ui << " : " << d_vars[ui] << " -> " << d_match[ui] << std::endl;
+ }
+ }
+ }
+ }while( success && isMatchSpurious( p ) );
+ }
+ if( success ){
+ for( unsigned i=0; i<d_unassigned.size(); i++ ){
+ int ui = d_unassigned[i];
+ if( !d_match[ui].isNull() ){
+ Trace("qcf-check") << " Assigned #" << ui << " : " << d_vars[ui] << " -> " << d_match[ui] << std::endl;
+ }
+ }
+ return true;
+ }else{
+ for( unsigned i=0; i<assigned.size(); i++ ){
+ d_match[ assigned[i] ] = TNode::null();
+ }
+ assigned.clear();
+ return false;
+ }
+}
+
+void QuantInfo::getMatch( std::vector< Node >& terms ){
+ for( unsigned i=0; i<d_q[0].getNumChildren(); i++ ){
+ //Node cv = qi->getCurrentValue( qi->d_match[i] );
+ int repVar = getCurrentRepVar( i );
+ Node cv;
+ //std::map< int, TNode >::iterator itmt = qi->d_match_term.find( repVar );
+ if( !d_match_term[repVar].isNull() ){
+ cv = d_match_term[repVar];
+ }else{
+ cv = d_match[repVar];
+ }
+ Debug("qcf-check-inst") << "INST : " << i << " -> " << cv << ", from " << d_match[i] << std::endl;
+ terms.push_back( cv );
+ }
+}
+
+void QuantInfo::revertMatch( std::vector< int >& assigned ) {
+ for( unsigned i=0; i<assigned.size(); i++ ){
+ d_match[ assigned[i] ] = TNode::null();
+ }
+}
+
+void QuantInfo::debugPrintMatch( const char * c ) {
+ for( int i=0; i<getNumVars(); i++ ){
+ Trace(c) << " " << d_vars[i] << " -> ";
+ if( !d_match[i].isNull() ){
+ Trace(c) << d_match[i];
+ }else{
+ Trace(c) << "(unassigned) ";
+ }
+ if( !d_curr_var_deq[i].empty() ){
+ Trace(c) << ", DEQ{ ";
+ for( std::map< TNode, int >::iterator it = d_curr_var_deq[i].begin(); it != d_curr_var_deq[i].end(); ++it ){
+ Trace(c) << it->first << " ";
+ }
+ Trace(c) << "}";
+ }
+ if( !d_match_term[i].isNull() && d_match_term[i]!=d_match[i] ){
+ Trace(c) << ", EXP : " << d_match_term[i];
+ }
+ Trace(c) << std::endl;
+ }
+ if( !d_tconstraints.empty() ){
+ Trace(c) << "ADDITIONAL CONSTRAINTS : " << std::endl;
+ for( std::map< Node, bool >::iterator it = d_tconstraints.begin(); it != d_tconstraints.end(); ++it ){
+ Trace(c) << " " << it->first << " -> " << it->second << std::endl;
+ }
+ }
+}
+
+MatchGen::MatchGen( QuantInfo * qi, Node n, bool isVar ){
+ Trace("qcf-qregister-debug") << "Make match gen for " << n << ", isVar = " << isVar << std::endl;
+ std::vector< Node > qni_apps;
+ d_qni_size = 0;
+ if( isVar ){
+ Assert( qi->d_var_num.find( n )!=qi->d_var_num.end() );
+ if( n.getKind()==ITE ){
+ d_type = typ_ite_var;
+ d_type_not = false;
+ d_n = n;
+ d_children.push_back( MatchGen( qi, d_n[0] ) );
+ if( d_children[0].isValid() ){
+ d_type = typ_ite_var;
+ for( unsigned i=1; i<=2; i++ ){
+ Node nn = n.eqNode( n[i] );
+ d_children.push_back( MatchGen( qi, nn ) );
+ d_children[d_children.size()-1].d_qni_bound_except.push_back( 0 );
+ if( !d_children[d_children.size()-1].isValid() ){
+ setInvalid();
+ break;
+ }
+ }
+ }else{
+ d_type = typ_invalid;
+ }
+ }else{
+ d_type = isHandledUfTerm( n ) ? typ_var : typ_tsym;
+ d_qni_var_num[0] = qi->getVarNum( n );
+ d_qni_size++;
+ d_type_not = false;
+ d_n = n;
+ //Node f = getOperator( n );
+ for( unsigned j=0; j<d_n.getNumChildren(); j++ ){
+ Node nn = d_n[j];
+ Trace("qcf-qregister-debug") << " " << d_qni_size;
+ if( qi->isVar( nn ) ){
+ int v = qi->d_var_num[nn];
+ Trace("qcf-qregister-debug") << " is var #" << v << std::endl;
+ d_qni_var_num[d_qni_size] = v;
+ //qi->addFuncParent( v, f, j );
+ }else{
+ Trace("qcf-qregister-debug") << " is gterm " << nn << std::endl;
+ d_qni_gterm[d_qni_size] = nn;
+ }
+ d_qni_size++;
+ }
+ }
+ }else{
+ if( n.hasBoundVar() ){
+ d_type_not = false;
+ d_n = n;
+ if( d_n.getKind()==NOT ){
+ d_n = d_n[0];
+ d_type_not = !d_type_not;
+ }
+
+ if( isHandledBoolConnective( d_n ) ){
+ //non-literals
+ d_type = typ_formula;
+ for( unsigned i=0; i<d_n.getNumChildren(); i++ ){
+ if( d_n.getKind()!=FORALL || i==1 ){
+ d_children.push_back( MatchGen( qi, d_n[i], false ) );
+ if( !d_children[d_children.size()-1].isValid() ){
+ setInvalid();
+ break;
+ }
+ }
+ /*
+ else if( isTop && n.getKind()==OR && d_children[d_children.size()-1].d_type==typ_var_eq ){
+ Trace("qcf-qregister-debug") << "Remove child, make built-in constraint" << std::endl;
+ //if variable equality/disequality at top level, remove immediately
+ bool cIsNot = d_children[d_children.size()-1].d_type_not;
+ Node cn = d_children[d_children.size()-1].d_n;
+ Assert( cn.getKind()==EQUAL );
+ Assert( p->d_qinfo[q].isVar( cn[0] ) || p->d_qinfo[q].isVar( cn[1] ) );
+ //make it a built-in constraint instead
+ for( unsigned i=0; i<2; i++ ){
+ if( p->d_qinfo[q].isVar( cn[i] ) ){
+ int v = p->d_qinfo[q].getVarNum( cn[i] );
+ Node cno = cn[i==0 ? 1 : 0];
+ p->d_qinfo[q].d_var_constraint[ cIsNot ? 0 : 1 ][v].push_back( cno );
+ break;
+ }
+ }
+ d_children.pop_back();
+ }
+ */
+ }
+ }else{
+ d_type = typ_invalid;
+ //literals
+ if( isHandledUfTerm( d_n ) ){
+ Assert( qi->isVar( d_n ) );
+ d_type = typ_pred;
+ }else if( d_n.getKind()==BOUND_VARIABLE ){
+ Assert( d_n.getType().isBoolean() );
+ d_type = typ_bool_var;
+ }else if( d_n.getKind()==EQUAL || options::qcfTConstraint() ){
+ for( unsigned i=0; i<d_n.getNumChildren(); i++ ){
+ if( d_n[i].hasBoundVar() ){
+ if( !qi->isVar( d_n[i] ) ){
+ Trace("qcf-qregister-debug") << "ERROR : not var " << d_n[i] << std::endl;
+ }
+ Assert( qi->isVar( d_n[i] ) );
+ if( d_n.getKind()!=EQUAL && qi->isVar( d_n[i] ) ){
+ d_qni_var_num[i+1] = qi->d_var_num[d_n[i]];
+ }
+ }else{
+ d_qni_gterm[i] = d_n[i];
+ }
+ }
+ d_type = d_n.getKind()==EQUAL ? typ_eq : typ_tconstraint;
+ Trace("qcf-tconstraint") << "T-Constraint : " << d_n << std::endl;
+ }
+ }
+ }else{
+ //we will just evaluate
+ d_n = n;
+ d_type = typ_ground;
+ }
+ //if( d_type!=typ_invalid ){
+ //determine an efficient children ordering
+ //if( !d_children.empty() ){
+ //for( unsigned i=0; i<d_children.size(); i++ ){
+ // d_children_order.push_back( i );
+ //}
+ //if( !d_n.isNull() && ( d_n.getKind()==OR || d_n.getKind()==AND || d_n.getKind()==IFF ) ){
+ //sort based on the type of the constraint : ground comes first, then literals, then others
+ //MatchGenSort mgs;
+ //mgs.d_mg = this;
+ //std::sort( d_children_order.begin(), d_children_order.end(), mgs );
+ //}
+ //}
+ //}
+ }
+ Trace("qcf-qregister-debug") << "Done make match gen " << n << ", type = ";
+ debugPrintType( "qcf-qregister-debug", d_type, true );
+ Trace("qcf-qregister-debug") << std::endl;
+ //Assert( d_children.size()==d_children_order.size() );
+
+}
+
+void MatchGen::collectBoundVar( QuantInfo * qi, Node n, std::vector< int >& cbvars ) {
+ int v = qi->getVarNum( n );
+ if( v!=-1 && std::find( cbvars.begin(), cbvars.end(), v )==cbvars.end() ){
+ cbvars.push_back( v );
+ }
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ collectBoundVar( qi, n[i], cbvars );
+ }
+}
+
+void MatchGen::determineVariableOrder( QuantInfo * qi, std::vector< int >& bvars ) {
+ Trace("qcf-qregister-debug") << "Determine variable order " << d_n << std::endl;
+ bool isCom = d_type==typ_formula && ( d_n.getKind()==OR || d_n.getKind()==AND || d_n.getKind()==IFF );
+ std::map< int, std::vector< int > > c_to_vars;
+ std::map< int, std::vector< int > > vars_to_c;
+ std::map< int, int > vb_count;
+ std::map< int, int > vu_count;
+ std::vector< bool > assigned;
+ Trace("qcf-qregister-debug") << "Calculate bound variables..." << std::endl;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ collectBoundVar( qi, d_children[i].d_n, c_to_vars[i] );
+ assigned.push_back( false );
+ vb_count[i] = 0;
+ vu_count[i] = 0;
+ for( unsigned j=0; j<c_to_vars[i].size(); j++ ){
+ int v = c_to_vars[i][j];
+ vars_to_c[v].push_back( i );
+ if( std::find( bvars.begin(), bvars.end(), v )==bvars.end() ){
+ vu_count[i]++;
+ if( !isCom ){
+ bvars.push_back( v );
+ }
+ }else{
+ vb_count[i]++;
+ }
+ }
+ }
+ if( isCom ){
+ //children that bind the least number of unbound variables go first
+ do {
+ int min_score = -1;
+ int min_score_index = -1;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ if( !assigned[i] ){
+ int score = vu_count[i];
+ if( min_score==-1 || score<min_score ){
+ min_score = score;
+ min_score_index = i;
+ }
+ }
+ }
+ Trace("qcf-qregister-debug") << "...assign child " << min_score_index << "/" << d_children.size() << std::endl;
+ Assert( min_score_index!=-1 );
+ //add to children order
+ d_children_order.push_back( min_score_index );
+ assigned[min_score_index] = true;
+ //if( vb_count[min_score_index]==0 ){
+ // d_independent.push_back( min_score_index );
+ //}
+ //determine order internal to children
+ d_children[min_score_index].determineVariableOrder( qi, bvars );
+ Trace("qcf-qregister-debug") << "...bind variables" << std::endl;
+ //now, make it a bound variable
+ for( unsigned i=0; i<c_to_vars[min_score_index].size(); i++ ){
+ int v = c_to_vars[min_score_index][i];
+ if( std::find( bvars.begin(), bvars.end(), v )==bvars.end() ){
+ for( unsigned j=0; j<vars_to_c[v].size(); j++ ){
+ int vc = vars_to_c[v][j];
+ vu_count[vc]--;
+ vb_count[vc]++;
+ }
+ bvars.push_back( v );
+ }
+ }
+ Trace("qcf-qregister-debug") << "...done assign child " << min_score_index << std::endl;
+ }while( d_children_order.size()!=d_children.size() );
+ Trace("qcf-qregister-debug") << "Done assign variable ordering for " << d_n << std::endl;
+ }else{
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ d_children_order.push_back( i );
+ d_children[i].determineVariableOrder( qi, bvars );
+ }
+ }
+}
+
+
+void MatchGen::reset_round( QuantConflictFind * p ) {
+ d_wasSet = false;
+ for( unsigned i=0; i<d_children.size(); i++ ){
+ d_children[i].reset_round( p );
+ }
+ for( std::map< int, TNode >::iterator it = d_qni_gterm.begin(); it != d_qni_gterm.end(); ++it ){
+ d_qni_gterm_rep[it->first] = p->getRepresentative( it->second );
+ }
+ if( d_type==typ_ground ){
+ int e = p->evaluate( d_n );
+ if( e==1 ){
+ d_ground_eval[0] = p->d_true;
+ }else if( e==-1 ){
+ d_ground_eval[0] = p->d_false;
+ }
+ }else if( d_type==typ_eq ){
+ for( unsigned i=0; i<d_n.getNumChildren(); i++ ){
+ if( !d_n[i].hasBoundVar() ){
+ d_ground_eval[i] = p->evaluateTerm( d_n[i] );
+ }
+ }
+ }
+ d_qni_bound_cons.clear();
+ d_qni_bound_cons_var.clear();
+ d_qni_bound.clear();
+}
+
+void MatchGen::reset( QuantConflictFind * p, bool tgt, QuantInfo * qi ) {
+ d_tgt = d_type_not ? !tgt : tgt;
+ Debug("qcf-match") << " Reset for : " << d_n << ", type : ";
+ debugPrintType( "qcf-match", d_type );
+ Debug("qcf-match") << ", tgt = " << d_tgt << ", children = " << d_children.size() << " " << d_children_order.size() << std::endl;
+ d_qn.clear();
+ d_qni.clear();
+ d_qni_bound.clear();
+ d_child_counter = -1;
+ d_tgt_orig = d_tgt;
+
+ //set up processing matches
+ if( d_type==typ_invalid ){
+ //do nothing
+ }else if( d_type==typ_ground ){
+ if( d_ground_eval[0]==( d_tgt ? p->d_true : p->d_false ) ){
+ d_child_counter = 0;
+ }
+ }else if( d_type==typ_bool_var ){
+ //get current value of the variable
+ TNode n = qi->getCurrentValue( d_n );
+ int vn = qi->getCurrentRepVar( qi->getVarNum( n ) );
+ if( vn==-1 ){
+ //evaluate the value, see if it is compatible
+ int e = p->evaluate( n );
+ if( ( e==1 && d_tgt ) || ( e==0 && !d_tgt ) ){
+ d_child_counter = 0;
+ }
+ }else{
+ //unassigned, set match to true/false
+ d_qni_bound[0] = vn;
+ qi->setMatch( p, vn, d_tgt ? p->d_true : p->d_false );
+ d_child_counter = 0;
+ }
+ if( d_child_counter==0 ){
+ d_qn.push_back( NULL );
+ }
+ }else if( d_type==typ_var ){
+ Assert( isHandledUfTerm( d_n ) );
+ Node f = getOperator( p, d_n );
+ Debug("qcf-match-debug") << " reset: Var will match operators of " << f << std::endl;
+ TermArgTrie * qni = p->getTermDatabase()->getTermArgTrie( Node::null(), f );
+ if( qni!=NULL ){
+ d_qn.push_back( qni );
+ }
+ d_matched_basis = false;
+ }else if( d_type==typ_tsym || d_type==typ_tconstraint ){
+ for( std::map< int, int >::iterator it = d_qni_var_num.begin(); it != d_qni_var_num.end(); ++it ){
+ int repVar = qi->getCurrentRepVar( it->second );
+ if( qi->d_match[repVar].isNull() ){
+ Debug("qcf-match-debug") << "Force matching on child #" << it->first << ", which is var #" << repVar << std::endl;
+ d_qni_bound[it->first] = repVar;
+ }
+ }
+ d_qn.push_back( NULL );
+ }else if( d_type==typ_pred || d_type==typ_eq ){
+ //add initial constraint
+ Node nn[2];
+ int vn[2];
+ if( d_type==typ_pred ){
+ nn[0] = qi->getCurrentValue( d_n );
+ vn[0] = qi->getCurrentRepVar( qi->getVarNum( nn[0] ) );
+ nn[1] = p->getRepresentative( d_tgt ? p->d_true : p->d_false );
+ vn[1] = -1;
+ d_tgt = true;
+ }else{
+ for( unsigned i=0; i<2; i++ ){
+ TNode nc;
+ std::map< int, TNode >::iterator it = d_qni_gterm_rep.find( i );
+ if( it!=d_qni_gterm_rep.end() ){
+ nc = it->second;
+ }else{
+ nc = d_n[i];
+ }
+ nn[i] = qi->getCurrentValue( nc );
+ vn[i] = qi->getCurrentRepVar( qi->getVarNum( nn[i] ) );
+ }
+ }
+ bool success;
+ if( vn[0]==-1 && vn[1]==-1 ){
+ //Trace("qcf-explain") << " reset : " << d_n << " check ground values " << nn[0] << " " << nn[1] << " (tgt=" << d_tgt << ")" << std::endl;
+ Debug("qcf-match-debug") << " reset: check ground values " << nn[0] << " " << nn[1] << " (" << d_tgt << ")" << std::endl;
+ //just compare values
+ if( d_tgt ){
+ success = p->areMatchEqual( nn[0], nn[1] );
+ }else{
+ if( p->d_effort==QuantConflictFind::effort_conflict ){
+ success = p->areDisequal( nn[0], nn[1] );
+ }else{
+ success = p->areMatchDisequal( nn[0], nn[1] );
+ }
+ }
+ }else{
+ //otherwise, add a constraint to a variable
+ if( vn[1]!=-1 && vn[0]==-1 ){
+ //swap
+ Node t = nn[1];
+ nn[1] = nn[0];
+ nn[0] = t;
+ vn[0] = vn[1];
+ vn[1] = -1;
+ }
+ Debug("qcf-match-debug") << " reset: add constraint " << vn[0] << " -> " << nn[1] << " (vn=" << vn[1] << ")" << std::endl;
+ //add some constraint
+ int addc = qi->addConstraint( p, vn[0], nn[1], vn[1], d_tgt, false );
+ success = addc!=-1;
+ //if successful and non-redundant, store that we need to cleanup this
+ if( addc==1 ){
+ //Trace("qcf-explain") << " reset: " << d_n << " add constraint " << vn[0] << " -> " << nn[1] << " (vn=" << vn[1] << ")" << ", d_tgt = " << d_tgt << std::endl;
+ for( unsigned i=0; i<2; i++ ){
+ if( vn[i]!=-1 && std::find( d_qni_bound_except.begin(), d_qni_bound_except.end(), i )==d_qni_bound_except.end() ){
+ d_qni_bound[vn[i]] = vn[i];
+ }
+ }
+ d_qni_bound_cons[vn[0]] = nn[1];
+ d_qni_bound_cons_var[vn[0]] = vn[1];
+ }
+ }
+ //if successful, we will bind values to variables
+ if( success ){
+ d_qn.push_back( NULL );
+ }
+ }else{
+ if( d_children.empty() ){
+ //add dummy
+ d_qn.push_back( NULL );
+ }else{
+ if( d_tgt && d_n.getKind()==FORALL ){
+ //do nothing
+ }else{
+ //reset the first child to d_tgt
+ d_child_counter = 0;
+ getChild( d_child_counter )->reset( p, d_tgt, qi );
+ }
+ }
+ }
+ d_binding = false;
+ d_wasSet = true;
+ Debug("qcf-match") << " reset: Finished reset for " << d_n << ", success = " << ( !d_qn.empty() || d_child_counter!=-1 ) << std::endl;
+}
+
+bool MatchGen::getNextMatch( QuantConflictFind * p, QuantInfo * qi ) {
+ Debug("qcf-match") << " Get next match for : " << d_n << ", type = ";
+ debugPrintType( "qcf-match", d_type );
+ Debug("qcf-match") << ", children = " << d_children.size() << ", binding = " << d_binding << std::endl;
+ if( d_type==typ_invalid || d_type==typ_ground ){
+ if( d_child_counter==0 ){
+ d_child_counter = -1;
+ return true;
+ }else{
+ d_wasSet = false;
+ return false;
+ }
+ }else if( d_type==typ_var || d_type==typ_eq || d_type==typ_pred || d_type==typ_bool_var || d_type==typ_tconstraint || d_type==typ_tsym ){
+ bool success = false;
+ bool terminate = false;
+ do {
+ bool doReset = false;
+ bool doFail = false;
+ if( !d_binding ){
+ if( doMatching( p, qi ) ){
+ Debug("qcf-match-debug") << " - Matching succeeded" << std::endl;
+ d_binding = true;
+ d_binding_it = d_qni_bound.begin();
+ doReset = true;
+ //for tconstraint, add constraint
+ if( d_type==typ_tconstraint ){
+ std::map< Node, bool >::iterator it = qi->d_tconstraints.find( d_n );
+ if( it==qi->d_tconstraints.end() ){
+ qi->d_tconstraints[d_n] = d_tgt;
+ //store that we added this constraint
+ d_qni_bound_cons[0] = d_n;
+ }else if( d_tgt!=it->second ){
+ success = false;
+ terminate = true;
+ }
+ }
+ }else{
+ Debug("qcf-match-debug") << " - Matching failed" << std::endl;
+ success = false;
+ terminate = true;
+ }
+ }else{
+ doFail = true;
+ }
+ if( d_binding ){
+ //also need to create match for each variable we bound
+ success = true;
+ Debug("qcf-match-debug") << " Produce matches for bound variables by " << d_n << ", type = ";
+ debugPrintType( "qcf-match-debug", d_type );
+ Debug("qcf-match-debug") << "..." << std::endl;
+
+ while( ( success && d_binding_it!=d_qni_bound.end() ) || doFail ){
+ std::map< int, MatchGen * >::iterator itm;
+ if( !doFail ){
+ Debug("qcf-match-debug") << " check variable " << d_binding_it->second << std::endl;
+ itm = qi->d_var_mg.find( d_binding_it->second );
+ }
+ if( doFail || ( d_binding_it->first!=0 && itm!=qi->d_var_mg.end() ) ){
+ Debug("qcf-match-debug") << " we had bound variable " << d_binding_it->second << ", reset = " << doReset << std::endl;
+ if( doReset ){
+ itm->second->reset( p, true, qi );
+ }
+ if( doFail || !itm->second->getNextMatch( p, qi ) ){
+ do {
+ if( d_binding_it==d_qni_bound.begin() ){
+ Debug("qcf-match-debug") << " failed." << std::endl;
+ success = false;
+ }else{
+ --d_binding_it;
+ Debug("qcf-match-debug") << " decrement..." << std::endl;
+ }
+ }while( success && ( d_binding_it->first==0 || qi->d_var_mg.find( d_binding_it->second )==qi->d_var_mg.end() ) );
+ doReset = false;
+ doFail = false;
+ }else{
+ Debug("qcf-match-debug") << " increment..." << std::endl;
+ ++d_binding_it;
+ doReset = true;
+ }
+ }else{
+ Debug("qcf-match-debug") << " skip..." << d_binding_it->second << std::endl;
+ ++d_binding_it;
+ doReset = true;
+ }
+ }
+ if( !success ){
+ d_binding = false;
+ }else{
+ terminate = true;
+ if( d_binding_it==d_qni_bound.begin() ){
+ d_binding = false;
+ }
+ }
+ }
+ }while( !terminate );
+ //if not successful, clean up the variables you bound
+ if( !success ){
+ if( d_type==typ_eq || d_type==typ_pred ){
+ //clean up the constraints you added
+ for( std::map< int, TNode >::iterator it = d_qni_bound_cons.begin(); it != d_qni_bound_cons.end(); ++it ){
+ if( !it->second.isNull() ){
+ Debug("qcf-match") << " Clean up bound var " << it->first << (d_tgt ? "!" : "") << " = " << it->second << std::endl;
+ std::map< int, int >::iterator itb = d_qni_bound_cons_var.find( it->first );
+ int vn = itb!=d_qni_bound_cons_var.end() ? itb->second : -1;
+ //Trace("qcf-explain") << " cleanup: " << d_n << " remove constraint " << it->first << " -> " << it->second << " (vn=" << vn << ")" << ", d_tgt = " << d_tgt << std::endl;
+ qi->addConstraint( p, it->first, it->second, vn, d_tgt, true );
+ }
+ }
+ d_qni_bound_cons.clear();
+ d_qni_bound_cons_var.clear();
+ d_qni_bound.clear();
+ }else{
+ //clean up the matches you set
+ for( std::map< int, int >::iterator it = d_qni_bound.begin(); it != d_qni_bound.end(); ++it ){
+ Debug("qcf-match") << " Clean up bound var " << it->second << std::endl;
+ Assert( it->second<qi->getNumVars() );
+ qi->d_match[ it->second ] = TNode::null();
+ qi->d_match_term[ it->second ] = TNode::null();
+ }
+ d_qni_bound.clear();
+ }
+ if( d_type==typ_tconstraint ){
+ //remove constraint if applicable
+ if( d_qni_bound_cons.find( 0 )!=d_qni_bound_cons.end() ){
+ qi->d_tconstraints.erase( d_n );
+ d_qni_bound_cons.clear();
+ }
+ }
+ /*
+ if( d_type==typ_var && p->d_effort==QuantConflictFind::effort_mc && !d_matched_basis ){
+ d_matched_basis = true;
+ Node f = getOperator( d_n );
+ TNode mbo = p->getQuantifiersEngine()->getTermDatabase()->getModelBasisOpTerm( f );
+ if( qi->setMatch( p, d_qni_var_num[0], mbo ) ){
+ success = true;
+ d_qni_bound[0] = d_qni_var_num[0];
+ }
+ }
+ */
+ }
+ Debug("qcf-match") << " ...finished matching for " << d_n << ", success = " << success << std::endl;
+ d_wasSet = success;
+ return success;
+ }else if( d_type==typ_formula || d_type==typ_ite_var ){
+ bool success = false;
+ if( d_child_counter<0 ){
+ if( d_child_counter<-1 ){
+ success = true;
+ d_child_counter = -1;
+ }
+ }else{
+ while( !success && d_child_counter>=0 ){
+ //transition system based on d_child_counter
+ if( d_n.getKind()==OR || d_n.getKind()==AND ){
+ if( (d_n.getKind()==AND)==d_tgt ){
+ //all children must match simultaneously
+ if( getChild( d_child_counter )->getNextMatch( p, qi ) ){
+ if( d_child_counter<(int)(getNumChildren()-1) ){
+ d_child_counter++;
+ Debug("qcf-match-debug") << " Reset child " << d_child_counter << " of " << d_n << std::endl;
+ getChild( d_child_counter )->reset( p, d_tgt, qi );
+ }else{
+ success = true;
+ }
+ }else{
+ //if( std::find( d_independent.begin(), d_independent.end(), d_child_counter )!=d_independent.end() ){
+ // d_child_counter--;
+ //}else{
+ d_child_counter--;
+ //}
+ }
+ }else{
+ //one child must match
+ if( !getChild( d_child_counter )->getNextMatch( p, qi ) ){
+ if( d_child_counter<(int)(getNumChildren()-1) ){
+ d_child_counter++;
+ Debug("qcf-match-debug") << " Reset child " << d_child_counter << " of " << d_n << ", one match" << std::endl;
+ getChild( d_child_counter )->reset( p, d_tgt, qi );
+ }else{
+ d_child_counter = -1;
+ }
+ }else{
+ success = true;
+ }
+ }
+ }else if( d_n.getKind()==IFF ){
+ //construct match based on both children
+ if( d_child_counter%2==0 ){
+ if( getChild( 0 )->getNextMatch( p, qi ) ){
+ d_child_counter++;
+ getChild( 1 )->reset( p, d_child_counter==1, qi );
+ }else{
+ if( d_child_counter==0 ){
+ d_child_counter = 2;
+ getChild( 0 )->reset( p, !d_tgt, qi );
+ }else{
+ d_child_counter = -1;
+ }
+ }
+ }
+ if( d_child_counter>=0 && d_child_counter%2==1 ){
+ if( getChild( 1 )->getNextMatch( p, qi ) ){
+ success = true;
+ }else{
+ d_child_counter--;
+ }
+ }
+ }else if( d_n.getKind()==ITE ){
+ if( d_child_counter%2==0 ){
+ int index1 = d_child_counter==4 ? 1 : 0;
+ if( getChild( index1 )->getNextMatch( p, qi ) ){
+ d_child_counter++;
+ getChild( d_child_counter==5 ? 2 : (d_tgt==(d_child_counter==1) ? 1 : 2) )->reset( p, d_tgt, qi );
+ }else{
+ if( d_child_counter==4 || ( d_type==typ_ite_var && d_child_counter==2 ) ){
+ d_child_counter = -1;
+ }else{
+ d_child_counter +=2;
+ getChild( d_child_counter==2 ? 0 : 1 )->reset( p, d_child_counter==2 ? !d_tgt : d_tgt, qi );
+ }
+ }
+ }
+ if( d_child_counter>=0 && d_child_counter%2==1 ){
+ int index2 = d_child_counter==5 ? 2 : (d_tgt==(d_child_counter==1) ? 1 : 2);
+ if( getChild( index2 )->getNextMatch( p, qi ) ){
+ success = true;
+ }else{
+ d_child_counter--;
+ }
+ }
+ }else if( d_n.getKind()==FORALL ){
+ if( getChild( d_child_counter )->getNextMatch( p, qi ) ){
+ success = true;
+ }else{
+ d_child_counter = -1;
+ }
+ }
+ }
+ d_wasSet = success;
+ Debug("qcf-match") << " ...finished construct match for " << d_n << ", success = " << success << std::endl;
+ return success;
+ }
+ }
+ Debug("qcf-match") << " ...already finished for " << d_n << std::endl;
+ return false;
+}
+
+bool MatchGen::getExplanation( QuantConflictFind * p, QuantInfo * qi, std::vector< Node >& exp ) {
+ if( d_type==typ_eq ){
+ Node n[2];
+ for( unsigned i=0; i<2; i++ ){
+ Trace("qcf-explain") << "Explain term " << d_n[i] << "..." << std::endl;
+ n[i] = getExplanationTerm( p, qi, d_n[i], exp );
+ }
+ Node eq = n[0].eqNode( n[1] );
+ if( !d_tgt_orig ){
+ eq = eq.negate();
+ }
+ exp.push_back( eq );
+ Trace("qcf-explain") << "Explanation for " << d_n << " (tgt=" << d_tgt_orig << ") is " << eq << ", set = " << d_wasSet << std::endl;
+ return true;
+ }else if( d_type==typ_pred ){
+ Trace("qcf-explain") << "Explain term " << d_n << "..." << std::endl;
+ Node n = getExplanationTerm( p, qi, d_n, exp );
+ if( !d_tgt_orig ){
+ n = n.negate();
+ }
+ exp.push_back( n );
+ Trace("qcf-explain") << "Explanation for " << d_n << " (tgt=" << d_tgt_orig << ") is " << n << ", set = " << d_wasSet << std::endl;
+ return true;
+ }else if( d_type==typ_formula ){
+ Trace("qcf-explain") << "Explanation get for " << d_n << ", counter = " << d_child_counter << ", tgt = " << d_tgt_orig << ", set = " << d_wasSet << std::endl;
+ if( d_n.getKind()==OR || d_n.getKind()==AND ){
+ if( (d_n.getKind()==AND)==d_tgt ){
+ for( unsigned i=0; i<getNumChildren(); i++ ){
+ if( !getChild( i )->getExplanation( p, qi, exp ) ){
+ return false;
+ }
+ }
+ }else{
+ return getChild( d_child_counter )->getExplanation( p, qi, exp );
+ }
+ }else if( d_n.getKind()==IFF ){
+ for( unsigned i=0; i<2; i++ ){
+ if( !getChild( i )->getExplanation( p, qi, exp ) ){
+ return false;
+ }
+ }
+ }else if( d_n.getKind()==ITE ){
+ for( unsigned i=0; i<3; i++ ){
+ bool isActive = ( ( i==0 && d_child_counter!=5 ) ||
+ ( i==1 && d_child_counter!=( d_tgt ? 3 : 1 ) ) ||
+ ( i==2 && d_child_counter!=( d_tgt ? 1 : 3 ) ) );
+ if( isActive ){
+ if( !getChild( i )->getExplanation( p, qi, exp ) ){
+ return false;
+ }
+ }
+ }
+ }else{
+ return false;
+ }
+ return true;
+ }else{
+ return false;
+ }
+}
+
+Node MatchGen::getExplanationTerm( QuantConflictFind * p, QuantInfo * qi, Node t, std::vector< Node >& exp ) {
+ Node v = qi->getCurrentExpValue( t );
+ if( isHandledUfTerm( t ) ){
+ for( unsigned i=0; i<t.getNumChildren(); i++ ){
+ Node vi = getExplanationTerm( p, qi, t[i], exp );
+ if( vi!=v[i] ){
+ Node eq = vi.eqNode( v[i] );
+ if( std::find( exp.begin(), exp.end(), eq )==exp.end() ){
+ Trace("qcf-explain") << " add : " << eq << "." << std::endl;
+ exp.push_back( eq );
+ }
+ }
+ }
+ }
+ return v;
+}
+
+bool MatchGen::doMatching( QuantConflictFind * p, QuantInfo * qi ) {
+ if( !d_qn.empty() ){
+ if( d_qn[0]==NULL ){
+ d_qn.clear();
+ return true;
+ }else{
+ Assert( d_type==typ_var );
+ Assert( d_qni_size>0 );
+ bool invalidMatch;
+ do {
+ invalidMatch = false;
+ Debug("qcf-match-debug") << " Do matching " << d_n << " " << d_qn.size() << " " << d_qni.size() << std::endl;
+ if( d_qn.size()==d_qni.size()+1 ) {
+ int index = (int)d_qni.size();
+ //initialize
+ TNode val;
+ std::map< int, int >::iterator itv = d_qni_var_num.find( index );
+ if( itv!=d_qni_var_num.end() ){
+ //get the representative variable this variable is equal to
+ int repVar = qi->getCurrentRepVar( itv->second );
+ Debug("qcf-match-debug") << " Match " << index << " is a variable " << itv->second << ", which is repVar " << repVar << std::endl;
+ //get the value the rep variable
+ //std::map< int, TNode >::iterator itm = qi->d_match.find( repVar );
+ if( !qi->d_match[repVar].isNull() ){
+ val = qi->d_match[repVar];
+ Debug("qcf-match-debug") << " Variable is already bound to " << val << std::endl;
+ }else{
+ //binding a variable
+ d_qni_bound[index] = repVar;
+ std::map< TNode, TermArgTrie >::iterator it = d_qn[index]->d_data.begin();
+ if( it != d_qn[index]->d_data.end() ) {
+ d_qni.push_back( it );
+ //set the match
+ if( qi->setMatch( p, d_qni_bound[index], it->first ) ){
+ Debug("qcf-match-debug") << " Binding variable" << std::endl;
+ if( d_qn.size()<d_qni_size ){
+ d_qn.push_back( &it->second );
+ }
+ }else{
+ Debug("qcf-match") << " Binding variable, currently fail." << std::endl;
+ invalidMatch = true;
+ }
+ }else{
+ Debug("qcf-match-debug") << " Binding variable, fail, no more variables to bind" << std::endl;
+ d_qn.pop_back();
+ }
+ }
+ }else{
+ Debug("qcf-match-debug") << " Match " << index << " is ground term" << std::endl;
+ Assert( d_qni_gterm.find( index )!=d_qni_gterm.end() );
+ Assert( d_qni_gterm_rep.find( index )!=d_qni_gterm_rep.end() );
+ val = d_qni_gterm_rep[index];
+ Assert( !val.isNull() );
+ }
+ if( !val.isNull() ){
+ //constrained by val
+ std::map< TNode, TermArgTrie >::iterator it = d_qn[index]->d_data.find( val );
+ if( it!=d_qn[index]->d_data.end() ){
+ Debug("qcf-match-debug") << " Match" << std::endl;
+ d_qni.push_back( it );
+ if( d_qn.size()<d_qni_size ){
+ d_qn.push_back( &it->second );
+ }
+ }else{
+ Debug("qcf-match-debug") << " Failed to match" << std::endl;
+ d_qn.pop_back();
+ }
+ }
+ }else{
+ Assert( d_qn.size()==d_qni.size() );
+ int index = d_qni.size()-1;
+ //increment if binding this variable
+ bool success = false;
+ std::map< int, int >::iterator itb = d_qni_bound.find( index );
+ if( itb!=d_qni_bound.end() ){
+ d_qni[index]++;
+ if( d_qni[index]!=d_qn[index]->d_data.end() ){
+ success = true;
+ if( qi->setMatch( p, itb->second, d_qni[index]->first ) ){
+ Debug("qcf-match-debug") << " Bind next variable" << std::endl;
+ if( d_qn.size()<d_qni_size ){
+ d_qn.push_back( &d_qni[index]->second );
+ }
+ }else{
+ Debug("qcf-match-debug") << " Bind next variable, currently fail" << std::endl;
+ invalidMatch = true;
+ }
+ }else{
+ qi->d_match[ itb->second ] = TNode::null();
+ qi->d_match_term[ itb->second ] = TNode::null();
+ Debug("qcf-match-debug") << " Bind next variable, no more variables to bind" << std::endl;
+ }
+ }else{
+ //TODO : if it equal to something else, also try that
+ }
+ //if not incrementing, move to next
+ if( !success ){
+ d_qn.pop_back();
+ d_qni.pop_back();
+ }
+ }
+ }while( ( !d_qn.empty() && d_qni.size()!=d_qni_size ) || invalidMatch );
+ if( d_qni.size()==d_qni_size ){
+ //Assert( !d_qni[d_qni.size()-1]->second.d_data.empty() );
+ //Debug("qcf-match-debug") << " We matched " << d_qni[d_qni.size()-1]->second.d_children.begin()->first << std::endl;
+ Assert( !d_qni[d_qni.size()-1]->second.d_data.empty() );
+ TNode t = d_qni[d_qni.size()-1]->second.d_data.begin()->first;
+ Debug("qcf-match-debug") << " " << d_n << " matched " << t << std::endl;
+ qi->d_match_term[d_qni_var_num[0]] = t;
+ //set the match terms
+ for( std::map< int, int >::iterator it = d_qni_bound.begin(); it != d_qni_bound.end(); ++it ){
+ Debug("qcf-match-debug") << " position " << it->first << " bounded " << it->second << " / " << qi->d_q[0].getNumChildren() << std::endl;
+ //if( it->second<(int)qi->d_q[0].getNumChildren() ){ //if it is an actual variable, we are interested in knowing the actual term
+ if( it->first>0 ){
+ Assert( !qi->d_match[ it->second ].isNull() );
+ Assert( p->areEqual( t[it->first-1], qi->d_match[ it->second ] ) );
+ qi->d_match_term[it->second] = t[it->first-1];
+ }
+ //}
+ }
+ }
+ }
+ }
+ return !d_qn.empty();
+}
+
+void MatchGen::debugPrintType( const char * c, short typ, bool isTrace ) {
+ if( isTrace ){
+ switch( typ ){
+ case typ_invalid: Trace(c) << "invalid";break;
+ case typ_ground: Trace(c) << "ground";break;
+ case typ_eq: Trace(c) << "eq";break;
+ case typ_pred: Trace(c) << "pred";break;
+ case typ_formula: Trace(c) << "formula";break;
+ case typ_var: Trace(c) << "var";break;
+ case typ_ite_var: Trace(c) << "ite_var";break;
+ case typ_bool_var: Trace(c) << "bool_var";break;
+ }
+ }else{
+ switch( typ ){
+ case typ_invalid: Debug(c) << "invalid";break;
+ case typ_ground: Debug(c) << "ground";break;
+ case typ_eq: Debug(c) << "eq";break;
+ case typ_pred: Debug(c) << "pred";break;
+ case typ_formula: Debug(c) << "formula";break;
+ case typ_var: Debug(c) << "var";break;
+ case typ_ite_var: Debug(c) << "ite_var";break;
+ case typ_bool_var: Debug(c) << "bool_var";break;
+ }
+ }
+}
+
+void MatchGen::setInvalid() {
+ d_type = typ_invalid;
+ d_children.clear();
+}
+
+bool MatchGen::isHandledBoolConnective( TNode n ) {
+ return n.getType().isBoolean() && ( n.getKind()==OR || n.getKind()==AND || n.getKind()==IFF || n.getKind()==ITE || n.getKind()==FORALL || n.getKind()==NOT );
+}
+
+bool MatchGen::isHandledUfTerm( TNode n ) {
+ //return n.getKind()==APPLY_UF || n.getKind()==STORE || n.getKind()==SELECT ||
+ // n.getKind()==APPLY_CONSTRUCTOR || n.getKind()==APPLY_SELECTOR_TOTAL || n.getKind()==APPLY_TESTER;
+ return inst::Trigger::isAtomicTriggerKind( n.getKind() );
+}
+
+Node MatchGen::getOperator( QuantConflictFind * p, Node n ) {
+ if( isHandledUfTerm( n ) ){
+ return p->getQuantifiersEngine()->getTermDatabase()->getOperator( n );
+ }else{
+ return Node::null();
+ }
+}
+
+bool MatchGen::isHandled( TNode n ) {
+ if( n.getKind()!=BOUND_VARIABLE && n.hasBoundVar() ){
+ if( !isHandledBoolConnective( n ) && !isHandledUfTerm( n ) && n.getKind()!=EQUAL && n.getKind()!=ITE ){
+ return false;
+ }
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ if( !isHandled( n[i] ) ){
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+
+QuantConflictFind::QuantConflictFind( QuantifiersEngine * qe, context::Context* c ) :
+QuantifiersModule( qe ),
+d_c( c ),
+d_conflict( c, false ),
+d_qassert( c ) {
+ d_fid_count = 0;
+ d_true = NodeManager::currentNM()->mkConst<bool>(true);
+ d_false = NodeManager::currentNM()->mkConst<bool>(false);
+}
+
+Node QuantConflictFind::mkEqNode( Node a, Node b ) {
+ if( a.getType().isBoolean() ){
+ return a.iffNode( b );
+ }else{
+ return a.eqNode( b );
+ }
+}
+
+//-------------------------------------------------- registration
+
+void QuantConflictFind::registerQuantifier( Node q ) {
+ if( !TermDb::isRewriteRule( q ) ){
+ d_quants.push_back( q );
+ d_quant_id[q] = d_quants.size();
+ Trace("qcf-qregister") << "Register ";
+ debugPrintQuant( "qcf-qregister", q );
+ Trace("qcf-qregister") << " : " << q << std::endl;
+ //make QcfNode structure
+ Trace("qcf-qregister") << "- Get relevant equality/disequality pairs, calculate flattening..." << std::endl;
+ d_qinfo[q].initialize( q, q[1] );
+
+ //debug print
+ Trace("qcf-qregister") << "- Flattened structure is :" << std::endl;
+ Trace("qcf-qregister") << " ";
+ debugPrintQuantBody( "qcf-qregister", q, q[1] );
+ Trace("qcf-qregister") << std::endl;
+ if( d_qinfo[q].d_vars.size()>q[0].getNumChildren() ){
+ Trace("qcf-qregister") << " with additional constraints : " << std::endl;
+ for( unsigned j=q[0].getNumChildren(); j<d_qinfo[q].d_vars.size(); j++ ){
+ Trace("qcf-qregister") << " ?x" << j << " = ";
+ debugPrintQuantBody( "qcf-qregister", q, d_qinfo[q].d_vars[j], false );
+ Trace("qcf-qregister") << std::endl;
+ }
+ }
+
+ Trace("qcf-qregister") << "Done registering quantifier." << std::endl;
+ }
+}
+
+int QuantConflictFind::evaluate( Node n, bool pref, bool hasPref ) {
+ int ret = 0;
+ if( n.getKind()==EQUAL ){
+ Node n1 = evaluateTerm( n[0] );
+ Node n2 = evaluateTerm( n[1] );
+ Debug("qcf-eval") << "Evaluate : Normalize " << n << " to " << n1 << " = " << n2 << std::endl;
+ if( areEqual( n1, n2 ) ){
+ ret = 1;
+ }else if( areDisequal( n1, n2 ) ){
+ ret = -1;
+ }
+ //else if( d_effort>QuantConflictFind::effort_conflict ){
+ // ret = -1;
+ //}
+ }else if( MatchGen::isHandledUfTerm( n ) ){ //predicate
+ Node nn = evaluateTerm( n );
+ Debug("qcf-eval") << "Evaluate : Normalize " << nn << " to " << n << std::endl;
+ if( areEqual( nn, d_true ) ){
+ ret = 1;
+ }else if( areEqual( nn, d_false ) ){
+ ret = -1;
+ }
+ //else if( d_effort>QuantConflictFind::effort_conflict ){
+ // ret = -1;
+ //}
+ }else if( n.getKind()==NOT ){
+ return -evaluate( n[0] );
+ }else if( n.getKind()==ITE ){
+ int cev1 = evaluate( n[0] );
+ int cevc[2] = { 0, 0 };
+ for( unsigned i=0; i<2; i++ ){
+ if( ( i==0 && cev1!=-1 ) || ( i==1 && cev1!=1 ) ){
+ cevc[i] = evaluate( n[i+1] );
+ if( cev1!=0 ){
+ ret = cevc[i];
+ break;
+ }else if( cevc[i]==0 ){
+ break;
+ }
+ }
+ }
+ if( ret==0 && cevc[0]!=0 && cevc[0]==cevc[1] ){
+ ret = cevc[0];
+ }
+ }else if( n.getKind()==IFF ){
+ int cev1 = evaluate( n[0] );
+ if( cev1!=0 ){
+ int cev2 = evaluate( n[1] );
+ if( cev2!=0 ){
+ ret = cev1==cev2 ? 1 : -1;
+ }
+ }
+
+ }else{
+ int ssval = 0;
+ if( n.getKind()==OR ){
+ ssval = 1;
+ }else if( n.getKind()==AND ){
+ ssval = -1;
+ }
+ bool isUnk = false;
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ int cev = evaluate( n[i] );
+ if( cev==ssval ){
+ ret = ssval;
+ break;
+ }else if( cev==0 ){
+ isUnk = true;
+ }
+ }
+ if( ret==0 && !isUnk ){
+ ret = -ssval;
+ }
+ }
+ Debug("qcf-eval") << "Evaluate " << n << " to " << ret << std::endl;
+ return ret;
+}
+
+short QuantConflictFind::getMaxQcfEffort() {
+ if( options::qcfMode()==QCF_CONFLICT_ONLY ){
+ return effort_conflict;
+ }else if( options::qcfMode()==QCF_PROP_EQ ){
+ return effort_prop_eq;
+ }else if( options::qcfMode()==QCF_MC ){
+ return effort_mc;
+ }else{
+ return 0;
+ }
+}
+
+bool QuantConflictFind::areMatchEqual( TNode n1, TNode n2 ) {
+ //if( d_effort==QuantConflictFind::effort_mc ){
+ // return n1==n2 || !areDisequal( n1, n2 );
+ //}else{
+ return n1==n2;
+ //}
+}
+
+bool QuantConflictFind::areMatchDisequal( TNode n1, TNode n2 ) {
+ //if( d_effort==QuantConflictFind::effort_conflict ){
+ // return areDisequal( n1, n2 );
+ //}else{
+ return n1!=n2;
+ //}
+}
+
+//-------------------------------------------------- handling assertions / eqc
+
+void QuantConflictFind::assertNode( Node q ) {
+ if( !TermDb::isRewriteRule( q ) ){
+ Trace("qcf-proc") << "QCF : assertQuantifier : ";
+ debugPrintQuant("qcf-proc", q);
+ Trace("qcf-proc") << std::endl;
+ d_qassert.push_back( q );
+ //set the eqRegistries that this depends on to true
+ //for( std::map< EqRegistry *, bool >::iterator it = d_qinfo[q].d_rel_eqr.begin(); it != d_qinfo[q].d_rel_eqr.end(); ++it ){
+ // it->first->d_active.set( true );
+ //}
+ }
+}
+
+eq::EqualityEngine * QuantConflictFind::getEqualityEngine() {
+ //return ((uf::TheoryUF*)d_quantEngine->getTheoryEngine()->theoryOf( theory::THEORY_UF ))->getEqualityEngine();
+ return d_quantEngine->getTheoryEngine()->getMasterEqualityEngine();
+}
+bool QuantConflictFind::areEqual( Node n1, Node n2 ) {
+ return getEqualityEngine()->hasTerm( n1 ) && getEqualityEngine()->hasTerm( n2 ) && getEqualityEngine()->areEqual( n1,n2 );
+}
+bool QuantConflictFind::areDisequal( Node n1, Node n2 ) {
+ return n1!=n2 && getEqualityEngine()->hasTerm( n1 ) && getEqualityEngine()->hasTerm( n2 ) && getEqualityEngine()->areDisequal( n1,n2, false );
+}
+Node QuantConflictFind::getRepresentative( Node n ) {
+ if( getEqualityEngine()->hasTerm( n ) ){
+ return getEqualityEngine()->getRepresentative( n );
+ }else{
+ return n;
+ }
+}
+TermDb* QuantConflictFind::getTermDatabase() {
+ return d_quantEngine->getTermDatabase();
+}
+
+Node QuantConflictFind::evaluateTerm( Node n ) {
+ if( MatchGen::isHandledUfTerm( n ) ){
+ Node f = MatchGen::getOperator( this, n );
+ Node nn;
+ if( getEqualityEngine()->hasTerm( n ) ){
+ nn = getTermDatabase()->existsTerm( f, n );
+ }else{
+ std::vector< TNode > args;
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ Node c = evaluateTerm( n[i] );
+ args.push_back( c );
+ }
+ nn = getTermDatabase()->d_func_map_trie[f].existsTerm( args );
+ }
+ if( !nn.isNull() ){
+ Debug("qcf-eval") << "GT: Term " << nn << " for " << n << " hasTerm = " << getEqualityEngine()->hasTerm( n ) << std::endl;
+ return getRepresentative( nn );
+ }else{
+ Debug("qcf-eval") << "GT: No term for " << n << " hasTerm = " << getEqualityEngine()->hasTerm( n ) << std::endl;
+ return n;
+ }
+ }else if( n.getKind()==ITE ){
+ int v = evaluate( n[0], false, false );
+ if( v==1 ){
+ return evaluateTerm( n[1] );
+ }else if( v==-1 ){
+ return evaluateTerm( n[2] );
+ }
+ }
+ return getRepresentative( n );
+}
+
+/** new node */
+void QuantConflictFind::newEqClass( Node n ) {
+ //Trace("qcf-proc-debug") << "QCF : newEqClass : " << n << std::endl;
+ //Trace("qcf-proc2-debug") << "QCF : finished newEqClass : " << n << std::endl;
+}
+
+/** merge */
+void QuantConflictFind::merge( Node a, Node b ) {
+
+}
+
+/** assert disequal */
+void QuantConflictFind::assertDisequal( Node a, Node b ) {
+
+}
+
+//-------------------------------------------------- check function
+
+bool QuantConflictFind::needsCheck( Theory::Effort level ) {
+ bool performCheck = false;
+ if( options::quantConflictFind() && !d_conflict ){
+ if( level==Theory::EFFORT_LAST_CALL ){
+ performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_LAST_CALL;
+ }else if( level==Theory::EFFORT_FULL ){
+ performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_DEFAULT;
+ }else if( level==Theory::EFFORT_STANDARD ){
+ performCheck = options::qcfWhenMode()==QCF_WHEN_MODE_STD;
+ }
+ }
+ return performCheck;
+}
+
+void QuantConflictFind::reset_round( Theory::Effort level ) {
+ d_needs_computeRelEqr = true;
+}
+
+/** check */
+void QuantConflictFind::check( Theory::Effort level, unsigned quant_e ) {
+ if( quant_e==QuantifiersEngine::QEFFORT_CONFLICT ){
+ Trace("qcf-check") << "QCF : check : " << level << std::endl;
+ if( d_conflict ){
+ Trace("qcf-check2") << "QCF : finished check : already in conflict." << std::endl;
+ if( level>=Theory::EFFORT_FULL ){
+ Trace("qcf-warn") << "ALREADY IN CONFLICT? " << level << std::endl;
+ //Assert( false );
+ }
+ }else{
+ int addedLemmas = 0;
+ ++(d_statistics.d_inst_rounds);
+ double clSet = 0;
+ int prevEt = 0;
+ if( Trace.isOn("qcf-engine") ){
+ prevEt = d_statistics.d_entailment_checks.getData();
+ clSet = double(clock())/double(CLOCKS_PER_SEC);
+ Trace("qcf-engine") << "---Conflict Find Engine Round, effort = " << level << "---" << std::endl;
+ }
+ computeRelevantEqr();
+
+ //determine order for quantified formulas
+ std::vector< Node > qorder;
+ std::map< Node, bool > qassert;
+ //mark which are asserted
+ for( unsigned i=0; i<d_qassert.size(); i++ ){
+ qassert[d_qassert[i]] = true;
+ }
+ //add which ones are specified in the order
+ for( unsigned i=0; i<d_quant_order.size(); i++ ){
+ Node n = d_quant_order[i];
+ if( std::find( qorder.begin(), qorder.end(), n )==qorder.end() && qassert.find( n )!=qassert.end() ){
+ qorder.push_back( n );
+ }
+ }
+ d_quant_order.clear();
+ d_quant_order.insert( d_quant_order.begin(), qorder.begin(), qorder.end() );
+ //add remaining
+ for( unsigned i=0; i<d_qassert.size(); i++ ){
+ Node n = d_qassert[i];
+ if( std::find( qorder.begin(), qorder.end(), n )==qorder.end() ){
+ qorder.push_back( n );
+ }
+ }
+
+ if( Trace.isOn("qcf-debug") ){
+ Trace("qcf-debug") << std::endl;
+ debugPrint("qcf-debug");
+ Trace("qcf-debug") << std::endl;
+ }
+ short end_e = getMaxQcfEffort();
+ for( short e = effort_conflict; e<=end_e; e++ ){
+ d_effort = e;
+ Trace("qcf-check") << "Checking quantified formulas at effort " << e << "..." << std::endl;
+ for( unsigned j=0; j<qorder.size(); j++ ){
+ Node q = qorder[j];
+ QuantInfo * qi = &d_qinfo[q];
+
+ Assert( d_qinfo.find( q )!=d_qinfo.end() );
+ if( qi->d_mg->isValid() ){
+ Trace("qcf-check") << "Check quantified formula ";
+ debugPrintQuant("qcf-check", q);
+ Trace("qcf-check") << " : " << q << "..." << std::endl;
+
+ Trace("qcf-check-debug") << "Reset round..." << std::endl;
+ qi->reset_round( this );
+ //try to make a matches making the body false
+ Trace("qcf-check-debug") << "Get next match..." << std::endl;
+ while( qi->d_mg->getNextMatch( this, qi ) ){
+ Trace("qcf-check") << "*** Produced match at effort " << e << " : " << std::endl;
+ qi->debugPrintMatch("qcf-check");
+ Trace("qcf-check") << std::endl;
+ std::vector< int > assigned;
+ if( !qi->isMatchSpurious( this ) ){
+ if( qi->completeMatch( this, assigned ) ){
+ std::vector< Node > terms;
+ qi->getMatch( terms );
+ if( !qi->isTConstraintSpurious( this, terms ) ){
+ if( Debug.isOn("qcf-check-inst") ){
+ //if( e==effort_conflict ){
+ Node inst = d_quantEngine->getInstantiation( q, terms );
+ Debug("qcf-check-inst") << "Check instantiation " << inst << "..." << std::endl;
+ Assert( evaluate( inst )!=1 );
+ Assert( evaluate( inst )==-1 || e>effort_conflict );
+ //}
+ }
+ if( d_quantEngine->addInstantiation( q, terms, false ) ){
+ Trace("qcf-check") << " ... Added instantiation" << std::endl;
+ Trace("qcf-inst") << "*** Was from effort " << e << " : " << std::endl;
+ qi->debugPrintMatch("qcf-inst");
+ Trace("qcf-inst") << std::endl;
+ ++addedLemmas;
+ if( e==effort_conflict ){
+ d_quant_order.insert( d_quant_order.begin(), q );
+ d_conflict.set( true );
+ ++(d_statistics.d_conflict_inst);
+ break;
+ }else if( e==effort_prop_eq ){
+ ++(d_statistics.d_prop_inst);
+ }
+ }else{
+ Trace("qcf-check") << " ... Failed to add instantiation" << std::endl;
+ //Assert( false );
+ }
+ }
+ //clean up assigned
+ qi->revertMatch( assigned );
+ d_tempCache.clear();
+ }else{
+ Trace("qcf-check") << " ... Spurious instantiation (cannot assign unassigned variables)" << std::endl;
+ }
+ }else{
+ Trace("qcf-check") << " ... Spurious instantiation (match is inconsistent)" << std::endl;
+ }
+ }
+ if( d_conflict ){
+ break;
+ }
+ }
+ }
+ if( addedLemmas>0 ){
+ break;
+ }
+ }
+ if( Trace.isOn("qcf-engine") ){
+ double clSet2 = double(clock())/double(CLOCKS_PER_SEC);
+ Trace("qcf-engine") << "Finished conflict find engine, time = " << (clSet2-clSet);
+ if( addedLemmas>0 ){
+ Trace("qcf-engine") << ", effort = " << ( d_effort==effort_conflict ? "conflict" : ( d_effort==effort_prop_eq ? "prop_eq" : "mc" ) );
+ Trace("qcf-engine") << ", addedLemmas = " << addedLemmas;
+ }
+ Trace("qcf-engine") << std::endl;
+ int currEt = d_statistics.d_entailment_checks.getData();
+ if( currEt!=prevEt ){
+ Trace("qcf-engine") << " Entailment checks = " << ( currEt - prevEt ) << std::endl;
+ }
+ }
+ Trace("qcf-check2") << "QCF : finished check : " << level << std::endl;
+ }
+ }
+}
+
+void QuantConflictFind::computeRelevantEqr() {
+ if( d_needs_computeRelEqr ){
+ d_needs_computeRelEqr = false;
+ Trace("qcf-check") << "Compute relevant equalities..." << std::endl;
+ //d_uf_terms.clear();
+ //d_eqc_uf_terms.clear();
+ d_eqcs.clear();
+ d_model_basis.clear();
+ //d_arg_reps.clear();
+ //double clSet = 0;
+ //if( Trace.isOn("qcf-opt") ){
+ // clSet = double(clock())/double(CLOCKS_PER_SEC);
+ //}
+
+ //long nTermst = 0;
+ //long nTerms = 0;
+ //long nEqc = 0;
+
+ //which nodes are irrelevant for disequality matches
+ std::map< TNode, bool > irrelevant_dnode;
+ //now, store matches
+ eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( getEqualityEngine() );
+ while( !eqcs_i.isFinished() ){
+ //nEqc++;
+ Node r = (*eqcs_i);
+ TypeNode rtn = r.getType();
+ if( options::qcfMode()==QCF_MC ){
+ std::map< TypeNode, std::vector< TNode > >::iterator itt = d_eqcs.find( rtn );
+ if( itt==d_eqcs.end() ){
+ Node mb = getQuantifiersEngine()->getTermDatabase()->getModelBasisTerm( rtn );
+ if( !getEqualityEngine()->hasTerm( mb ) ){
+ Trace("qcf-warn") << "WARNING: Model basis term does not exist!" << std::endl;
+ Assert( false );
+ }
+ Node mbr = getRepresentative( mb );
+ if( mbr!=r ){
+ d_eqcs[rtn].push_back( mbr );
+ }
+ d_eqcs[rtn].push_back( r );
+ d_model_basis[rtn] = mb;
+ }else{
+ itt->second.push_back( r );
+ }
+ }else{
+ d_eqcs[rtn].push_back( r );
+ }
+ ++eqcs_i;
+ }
+ /*
+ if( Trace.isOn("qcf-opt") ){
+ double clSet2 = double(clock())/double(CLOCKS_PER_SEC);
+ Trace("qcf-opt") << "Compute rel eqc : " << std::endl;
+ Trace("qcf-opt") << " " << nEqc << " equivalence classes. " << std::endl;
+ Trace("qcf-opt") << " " << nTerms << " / " << nTermst << " terms." << std::endl;
+ Trace("qcf-opt") << " Time : " << (clSet2-clSet) << std::endl;
+ }
+ */
+ }
+}
+
+
+//-------------------------------------------------- debugging
+
+
+void QuantConflictFind::debugPrint( const char * c ) {
+ //print the equivalance classes
+ Trace(c) << "----------EQ classes" << std::endl;
+ eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( getEqualityEngine() );
+ while( !eqcs_i.isFinished() ){
+ Node n = (*eqcs_i);
+ //if( !n.getType().isInteger() ){
+ Trace(c) << " - " << n << " : {";
+ eq::EqClassIterator eqc_i = eq::EqClassIterator( n, getEqualityEngine() );
+ bool pr = false;
+ while( !eqc_i.isFinished() ){
+ Node nn = (*eqc_i);
+ if( nn.getKind()!=EQUAL && nn!=n ){
+ Trace(c) << (pr ? "," : "" ) << " " << nn;
+ pr = true;
+ }
+ ++eqc_i;
+ }
+ Trace(c) << (pr ? " " : "" ) << "}" << std::endl;
+ /*
+ EqcInfo * eqcn = getEqcInfo( n, false );
+ if( eqcn ){
+ Trace(c) << " DEQ : {";
+ pr = false;
+ for( NodeBoolMap::iterator it = eqcn->d_diseq.begin(); it != eqcn->d_diseq.end(); ++it ){
+ if( (*it).second ){
+ Trace(c) << (pr ? "," : "" ) << " " << (*it).first;
+ pr = true;
+ }
+ }
+ Trace(c) << (pr ? " " : "" ) << "}" << std::endl;
+ }
+ //}
+ */
+ ++eqcs_i;
+ }
+}
+
+void QuantConflictFind::debugPrintQuant( const char * c, Node q ) {
+ Trace(c) << "Q" << d_quant_id[q];
+}
+
+void QuantConflictFind::debugPrintQuantBody( const char * c, Node q, Node n, bool doVarNum ) {
+ if( n.getNumChildren()==0 ){
+ Trace(c) << n;
+ }else if( doVarNum && d_qinfo[q].d_var_num.find( n )!=d_qinfo[q].d_var_num.end() ){
+ Trace(c) << "?x" << d_qinfo[q].d_var_num[n];
+ }else{
+ Trace(c) << "(";
+ if( n.getKind()==APPLY_UF ){
+ Trace(c) << n.getOperator();
+ }else{
+ Trace(c) << n.getKind();
+ }
+ for( unsigned i=0; i<n.getNumChildren(); i++ ){
+ Trace(c) << " ";
+ debugPrintQuantBody( c, q, n[i] );
+ }
+ Trace(c) << ")";
+ }
+}
+
+QuantConflictFind::Statistics::Statistics():
+ d_inst_rounds("QuantConflictFind::Inst_Rounds", 0),
+ d_conflict_inst("QuantConflictFind::Instantiations_Conflict_Find", 0 ),
+ d_prop_inst("QuantConflictFind::Instantiations_Prop", 0 ),
+ d_entailment_checks("QuantConflictFind::Entailment_Checks",0)
+{
+ StatisticsRegistry::registerStat(&d_inst_rounds);
+ StatisticsRegistry::registerStat(&d_conflict_inst);
+ StatisticsRegistry::registerStat(&d_prop_inst);
+ StatisticsRegistry::registerStat(&d_entailment_checks);
+}
+
+QuantConflictFind::Statistics::~Statistics(){
+ StatisticsRegistry::unregisterStat(&d_inst_rounds);
+ StatisticsRegistry::unregisterStat(&d_conflict_inst);
+ StatisticsRegistry::unregisterStat(&d_prop_inst);
+ StatisticsRegistry::unregisterStat(&d_entailment_checks);
+}
+
+TNode QuantConflictFind::getZero( Kind k ) {
+ std::map< Kind, Node >::iterator it = d_zero.find( k );
+ if( it==d_zero.end() ){
+ Node nn;
+ if( k==PLUS ){
+ nn = NodeManager::currentNM()->mkConst( Rational(0) );
+ }
+ d_zero[k] = nn;
+ return nn;
+ }else{
+ return it->second;
+ }
+}
+
+
+}
diff --git a/src/theory/quantifiers/quant_conflict_find.h b/src/theory/quantifiers/quant_conflict_find.h index 0464c04e5..d8f1c8e6f 100644..100755 --- a/src/theory/quantifiers/quant_conflict_find.h +++ b/src/theory/quantifiers/quant_conflict_find.h @@ -1,297 +1,259 @@ -/********************* */ -/*! \file quant_conflict_find.h - ** \verbatim - ** Original author: Andrew Reynolds - ** Major contributors: Morgan Deters - ** Minor contributors (to current version): none - ** This file is part of the CVC4 project. - ** Copyright (c) 2009-2014 New York University and The University of Iowa - ** See the file COPYING in the top-level source directory for licensing - ** information.\endverbatim - ** - ** \brief quantifiers conflict find class - **/ - -#include "cvc4_private.h" - -#ifndef QUANT_CONFLICT_FIND -#define QUANT_CONFLICT_FIND - -#include "context/cdhashmap.h" -#include "context/cdchunk_list.h" -#include "theory/quantifiers_engine.h" - -namespace CVC4 { -namespace theory { -namespace quantifiers { - -class QcfNode; - -class QuantConflictFind; - -class QcfNodeIndex { -public: - std::map< TNode, QcfNodeIndex > d_children; - void clear() { d_children.clear(); } - void debugPrint( const char * c, int t ); - Node existsTerm( TNode n, std::vector< TNode >& reps, int index = 0 ); - Node addTerm( TNode n, std::vector< TNode >& reps, int index = 0 ); -}; - -class QuantInfo; - -//match generator -class MatchGen { - friend class QuantInfo; -private: - //current children information - int d_child_counter; - //children of this object - std::vector< int > d_children_order; - unsigned getNumChildren() { return d_children.size(); } - MatchGen * getChild( int i ) { return &d_children[d_children_order[i]]; } - //MatchGen * getChild( int i ) { return &d_children[i]; } - //current matching information - std::vector< QcfNodeIndex * > d_qn; - std::vector< std::map< TNode, QcfNodeIndex >::iterator > d_qni; - bool doMatching( QuantConflictFind * p, QuantInfo * qi ); - //for matching : each index is either a variable or a ground term - unsigned d_qni_size; - std::map< int, int > d_qni_var_num; - std::map< int, TNode > d_qni_gterm; - std::map< int, TNode > d_qni_gterm_rep; - std::map< int, int > d_qni_bound; - std::vector< int > d_qni_bound_except; - std::map< int, TNode > d_qni_bound_cons; - std::map< int, int > d_qni_bound_cons_var; - std::map< int, int >::iterator d_binding_it; - //std::vector< int > d_independent; - bool d_matched_basis; - bool d_binding; - //int getVarBindingVar(); - std::map< int, Node > d_ground_eval; - //determine variable order - void determineVariableOrder( QuantInfo * qi, std::vector< int >& bvars ); - void collectBoundVar( QuantInfo * qi, Node n, std::vector< int >& cbvars ); -public: - //type of the match generator - enum { - typ_invalid, - typ_ground, - typ_pred, - typ_eq, - typ_formula, - typ_var, - typ_ite_var, - typ_bool_var, - typ_tconstraint, - typ_tsym, - }; - void debugPrintType( const char * c, short typ, bool isTrace = false ); -public: - MatchGen() : d_type( typ_invalid ){} - MatchGen( QuantInfo * qi, Node n, bool isVar = false ); - bool d_tgt; - bool d_tgt_orig; - bool d_wasSet; - Node d_n; - std::vector< MatchGen > d_children; - short d_type; - bool d_type_not; - void reset_round( QuantConflictFind * p ); - void reset( QuantConflictFind * p, bool tgt, QuantInfo * qi ); - bool getNextMatch( QuantConflictFind * p, QuantInfo * qi ); - bool getExplanation( QuantConflictFind * p, QuantInfo * qi, std::vector< Node >& exp ); - Node getExplanationTerm( QuantConflictFind * p, QuantInfo * qi, Node t, std::vector< Node >& exp ); - bool isValid() { return d_type!=typ_invalid; } - void setInvalid(); - - // is this term treated as UF application? - static bool isHandledBoolConnective( TNode n ); - static bool isHandledUfTerm( TNode n ); - static Node getOperator( QuantConflictFind * p, Node n ); - //can this node be handled by the algorithm - static bool isHandled( TNode n ); -}; - -//info for quantifiers -class QuantInfo { -private: - void registerNode( Node n, bool hasPol, bool pol, bool beneathQuant = false ); - void flatten( Node n, bool beneathQuant ); -private: //for completing match - std::vector< int > d_unassigned; - std::vector< TypeNode > d_unassigned_tn; - int d_unassigned_nvar; - int d_una_index; - std::vector< int > d_una_eqc_count; -public: - QuantInfo() : d_mg( NULL ) {} - ~QuantInfo() { delete d_mg; } - std::vector< TNode > d_vars; - std::map< TNode, int > d_var_num; - std::vector< int > d_tsym_vars; - std::map< TNode, bool > d_inMatchConstraint; - std::map< int, std::vector< Node > > d_var_constraint[2]; - int getVarNum( TNode v ) { return d_var_num.find( v )!=d_var_num.end() ? d_var_num[v] : -1; } - bool isVar( TNode v ) { return d_var_num.find( v )!=d_var_num.end(); } - int getNumVars() { return (int)d_vars.size(); } - TNode getVar( int i ) { return d_vars[i]; } - - MatchGen * d_mg; - Node d_q; - std::map< int, MatchGen * > d_var_mg; - void reset_round( QuantConflictFind * p ); -public: - //initialize - void initialize( Node q, Node qn ); - //current constraints - std::vector< TNode > d_match; - std::vector< TNode > d_match_term; - std::map< int, std::map< TNode, int > > d_curr_var_deq; - std::map< Node, bool > d_tconstraints; - int getCurrentRepVar( int v ); - TNode getCurrentValue( TNode n ); - TNode getCurrentExpValue( TNode n ); - bool getCurrentCanBeEqual( QuantConflictFind * p, int v, TNode n, bool chDiseq = false ); - int addConstraint( QuantConflictFind * p, int v, TNode n, bool polarity ); - int addConstraint( QuantConflictFind * p, int v, TNode n, int vn, bool polarity, bool doRemove ); - bool setMatch( QuantConflictFind * p, int v, TNode n ); - bool isMatchSpurious( QuantConflictFind * p ); - bool isTConstraintSpurious( QuantConflictFind * p, std::vector< Node >& terms ); - bool entailmentTest( QuantConflictFind * p, Node lit, bool chEnt = true ); - bool completeMatch( QuantConflictFind * p, std::vector< int >& assigned, bool doContinue = false ); - void revertMatch( std::vector< int >& assigned ); - void debugPrintMatch( const char * c ); - bool isConstrainedVar( int v ); -public: - void getMatch( std::vector< Node >& terms ); -}; - -class QuantConflictFind : public QuantifiersModule -{ - friend class QcfNodeIndex; - friend class MatchGen; - friend class QuantInfo; - typedef context::CDChunkList<Node> NodeList; - typedef context::CDHashMap<Node, bool, NodeHashFunction> NodeBoolMap; -private: - context::Context* d_c; - context::CDO< bool > d_conflict; - bool d_performCheck; - std::vector< Node > d_quant_order; - std::map< Kind, Node > d_zero; - //for storing nodes created during t-constraint solving (prevents memory leaks) - std::vector< Node > d_tempCache; -private: - std::map< Node, Node > d_op_node; - int d_fid_count; - std::map< Node, int > d_fid; - Node mkEqNode( Node a, Node b ); -public: //for ground terms - Node d_true; - Node d_false; - TNode getZero( Kind k ); -private: - Node evaluateTerm( Node n ); - int evaluate( Node n, bool pref = false, bool hasPref = false ); -private: - //currently asserted quantifiers - NodeList d_qassert; - std::map< Node, QuantInfo > d_qinfo; -private: //for equivalence classes - eq::EqualityEngine * getEqualityEngine(); - bool areDisequal( Node n1, Node n2 ); - bool areEqual( Node n1, Node n2 ); - Node getRepresentative( Node n ); - -/* - class EqcInfo { - public: - EqcInfo( context::Context* c ) : d_diseq( c ) {} - NodeBoolMap d_diseq; - bool isDisequal( Node n ) { return d_diseq.find( n )!=d_diseq.end() && d_diseq[n]; } - void setDisequal( Node n, bool val = true ) { d_diseq[n] = val; } - //NodeBoolMap& getRelEqr( int index ) { return index==0 ? d_rel_eqr_e : d_rel_eqr_d; } - }; - std::map< Node, EqcInfo * > d_eqc_info; - EqcInfo * getEqcInfo( Node n, bool doCreate = true ); -*/ - // operator -> index(terms) - std::map< TNode, QcfNodeIndex > d_uf_terms; - // operator -> index(eqc -> terms) - std::map< TNode, QcfNodeIndex > d_eqc_uf_terms; - //get qcf node index - QcfNodeIndex * getQcfNodeIndex( Node eqc, Node f ); - QcfNodeIndex * getQcfNodeIndex( Node f ); - // type -> list(eqc) - std::map< TypeNode, std::vector< TNode > > d_eqcs; - std::map< TypeNode, Node > d_model_basis; - //mapping from UF terms to representatives of their arguments - std::map< TNode, std::vector< TNode > > d_arg_reps; - //compute arg reps - void computeArgReps( TNode n ); - //compute - void computeUfTerms( TNode f ); -public: - enum { - effort_conflict, - effort_prop_eq, - effort_mc, - }; - short d_effort; - void setEffort( int e ) { d_effort = e; } - static short getMaxQcfEffort(); - bool areMatchEqual( TNode n1, TNode n2 ); - bool areMatchDisequal( TNode n1, TNode n2 ); -public: - QuantConflictFind( QuantifiersEngine * qe, context::Context* c ); - /** register quantifier */ - void registerQuantifier( Node q ); -public: - /** assert quantifier */ - void assertNode( Node q ); - /** new node */ - void newEqClass( Node n ); - /** merge */ - void merge( Node a, Node b ); - /** assert disequal */ - void assertDisequal( Node a, Node b ); - /** reset round */ - void reset_round( Theory::Effort level ); - /** check */ - void check( Theory::Effort level ); - /** needs check */ - bool needsCheck( Theory::Effort level ); -private: - bool d_needs_computeRelEqr; -public: - void computeRelevantEqr(); -private: - void debugPrint( const char * c ); - //for debugging - std::vector< Node > d_quants; - std::map< Node, int > d_quant_id; - void debugPrintQuant( const char * c, Node q ); - void debugPrintQuantBody( const char * c, Node q, Node n, bool doVarNum = true ); -public: - /** statistics class */ - class Statistics { - public: - IntStat d_inst_rounds; - IntStat d_conflict_inst; - IntStat d_prop_inst; - IntStat d_entailment_checks; - Statistics(); - ~Statistics(); - }; - Statistics d_statistics; - /** Identify this module */ - std::string identify() const { return "QcfEngine"; } -}; - -} -} -} - -#endif +/********************* */
+/*! \file quant_conflict_find.h
+ ** \verbatim
+ ** Original author: Andrew Reynolds
+ ** Major contributors: none
+ ** Minor contributors (to current version): none
+ ** This file is part of the CVC4 project.
+ ** Copyright (c) 2009-2014 New York University and The University of Iowa
+ ** See the file COPYING in the top-level source directory for licensing
+ ** information.\endverbatim
+ **
+ ** \brief quantifiers conflict find class
+ **/
+
+#include "cvc4_private.h"
+
+#ifndef QUANT_CONFLICT_FIND
+#define QUANT_CONFLICT_FIND
+
+#include "context/cdhashmap.h"
+#include "context/cdchunk_list.h"
+#include "theory/quantifiers_engine.h"
+#include "theory/quantifiers/term_database.h"
+
+namespace CVC4 {
+namespace theory {
+namespace quantifiers {
+
+class QuantConflictFind;
+class QuantInfo;
+
+//match generator
+class MatchGen {
+ friend class QuantInfo;
+private:
+ //current children information
+ int d_child_counter;
+ //children of this object
+ std::vector< int > d_children_order;
+ unsigned getNumChildren() { return d_children.size(); }
+ MatchGen * getChild( int i ) { return &d_children[d_children_order[i]]; }
+ //MatchGen * getChild( int i ) { return &d_children[i]; }
+ //current matching information
+ std::vector< TermArgTrie * > d_qn;
+ std::vector< std::map< TNode, TermArgTrie >::iterator > d_qni;
+ bool doMatching( QuantConflictFind * p, QuantInfo * qi );
+ //for matching : each index is either a variable or a ground term
+ unsigned d_qni_size;
+ std::map< int, int > d_qni_var_num;
+ std::map< int, TNode > d_qni_gterm;
+ std::map< int, TNode > d_qni_gterm_rep;
+ std::map< int, int > d_qni_bound;
+ std::vector< int > d_qni_bound_except;
+ std::map< int, TNode > d_qni_bound_cons;
+ std::map< int, int > d_qni_bound_cons_var;
+ std::map< int, int >::iterator d_binding_it;
+ //std::vector< int > d_independent;
+ bool d_matched_basis;
+ bool d_binding;
+ //int getVarBindingVar();
+ std::map< int, Node > d_ground_eval;
+ //determine variable order
+ void determineVariableOrder( QuantInfo * qi, std::vector< int >& bvars );
+ void collectBoundVar( QuantInfo * qi, Node n, std::vector< int >& cbvars );
+public:
+ //type of the match generator
+ enum {
+ typ_invalid,
+ typ_ground,
+ typ_pred,
+ typ_eq,
+ typ_formula,
+ typ_var,
+ typ_ite_var,
+ typ_bool_var,
+ typ_tconstraint,
+ typ_tsym,
+ };
+ void debugPrintType( const char * c, short typ, bool isTrace = false );
+public:
+ MatchGen() : d_type( typ_invalid ){}
+ MatchGen( QuantInfo * qi, Node n, bool isVar = false );
+ bool d_tgt;
+ bool d_tgt_orig;
+ bool d_wasSet;
+ Node d_n;
+ std::vector< MatchGen > d_children;
+ short d_type;
+ bool d_type_not;
+ void reset_round( QuantConflictFind * p );
+ void reset( QuantConflictFind * p, bool tgt, QuantInfo * qi );
+ bool getNextMatch( QuantConflictFind * p, QuantInfo * qi );
+ bool getExplanation( QuantConflictFind * p, QuantInfo * qi, std::vector< Node >& exp );
+ Node getExplanationTerm( QuantConflictFind * p, QuantInfo * qi, Node t, std::vector< Node >& exp );
+ bool isValid() { return d_type!=typ_invalid; }
+ void setInvalid();
+
+ // is this term treated as UF application?
+ static bool isHandledBoolConnective( TNode n );
+ static bool isHandledUfTerm( TNode n );
+ static Node getOperator( QuantConflictFind * p, Node n );
+ //can this node be handled by the algorithm
+ static bool isHandled( TNode n );
+};
+
+//info for quantifiers
+class QuantInfo {
+private:
+ void registerNode( Node n, bool hasPol, bool pol, bool beneathQuant = false );
+ void flatten( Node n, bool beneathQuant );
+private: //for completing match
+ std::vector< int > d_unassigned;
+ std::vector< TypeNode > d_unassigned_tn;
+ int d_unassigned_nvar;
+ int d_una_index;
+ std::vector< int > d_una_eqc_count;
+public:
+ QuantInfo() : d_mg( NULL ) {}
+ ~QuantInfo() { delete d_mg; }
+ std::vector< TNode > d_vars;
+ std::map< TNode, int > d_var_num;
+ std::vector< int > d_tsym_vars;
+ std::map< TNode, bool > d_inMatchConstraint;
+ std::map< int, std::vector< Node > > d_var_constraint[2];
+ int getVarNum( TNode v ) { return d_var_num.find( v )!=d_var_num.end() ? d_var_num[v] : -1; }
+ bool isVar( TNode v ) { return d_var_num.find( v )!=d_var_num.end(); }
+ int getNumVars() { return (int)d_vars.size(); }
+ TNode getVar( int i ) { return d_vars[i]; }
+
+ MatchGen * d_mg;
+ Node d_q;
+ std::map< int, MatchGen * > d_var_mg;
+ void reset_round( QuantConflictFind * p );
+public:
+ //initialize
+ void initialize( Node q, Node qn );
+ //current constraints
+ std::vector< TNode > d_match;
+ std::vector< TNode > d_match_term;
+ std::map< int, std::map< TNode, int > > d_curr_var_deq;
+ std::map< Node, bool > d_tconstraints;
+ int getCurrentRepVar( int v );
+ TNode getCurrentValue( TNode n );
+ TNode getCurrentExpValue( TNode n );
+ bool getCurrentCanBeEqual( QuantConflictFind * p, int v, TNode n, bool chDiseq = false );
+ int addConstraint( QuantConflictFind * p, int v, TNode n, bool polarity );
+ int addConstraint( QuantConflictFind * p, int v, TNode n, int vn, bool polarity, bool doRemove );
+ bool setMatch( QuantConflictFind * p, int v, TNode n );
+ bool isMatchSpurious( QuantConflictFind * p );
+ bool isTConstraintSpurious( QuantConflictFind * p, std::vector< Node >& terms );
+ bool entailmentTest( QuantConflictFind * p, Node lit, bool chEnt = true );
+ bool completeMatch( QuantConflictFind * p, std::vector< int >& assigned, bool doContinue = false );
+ void revertMatch( std::vector< int >& assigned );
+ void debugPrintMatch( const char * c );
+ bool isConstrainedVar( int v );
+public:
+ void getMatch( std::vector< Node >& terms );
+};
+
+class QuantConflictFind : public QuantifiersModule
+{
+ friend class MatchGen;
+ friend class QuantInfo;
+ typedef context::CDChunkList<Node> NodeList;
+ typedef context::CDHashMap<Node, bool, NodeHashFunction> NodeBoolMap;
+private:
+ context::Context* d_c;
+ context::CDO< bool > d_conflict;
+ std::vector< Node > d_quant_order;
+ std::map< Kind, Node > d_zero;
+ //for storing nodes created during t-constraint solving (prevents memory leaks)
+ std::vector< Node > d_tempCache;
+private:
+ std::map< Node, Node > d_op_node;
+ int d_fid_count;
+ std::map< Node, int > d_fid;
+ Node mkEqNode( Node a, Node b );
+public: //for ground terms
+ Node d_true;
+ Node d_false;
+ TNode getZero( Kind k );
+private:
+ Node evaluateTerm( Node n );
+ int evaluate( Node n, bool pref = false, bool hasPref = false );
+private:
+ //currently asserted quantifiers
+ NodeList d_qassert;
+ std::map< Node, QuantInfo > d_qinfo;
+private: //for equivalence classes
+ eq::EqualityEngine * getEqualityEngine();
+ bool areDisequal( Node n1, Node n2 );
+ bool areEqual( Node n1, Node n2 );
+ Node getRepresentative( Node n );
+ TermDb* getTermDatabase();
+ // type -> list(eqc)
+ std::map< TypeNode, std::vector< TNode > > d_eqcs;
+ std::map< TypeNode, Node > d_model_basis;
+public:
+ enum {
+ effort_conflict,
+ effort_prop_eq,
+ effort_mc,
+ };
+ short d_effort;
+ void setEffort( int e ) { d_effort = e; }
+ static short getMaxQcfEffort();
+ bool areMatchEqual( TNode n1, TNode n2 );
+ bool areMatchDisequal( TNode n1, TNode n2 );
+public:
+ QuantConflictFind( QuantifiersEngine * qe, context::Context* c );
+ /** register quantifier */
+ void registerQuantifier( Node q );
+public:
+ /** assert quantifier */
+ void assertNode( Node q );
+ /** new node */
+ void newEqClass( Node n );
+ /** merge */
+ void merge( Node a, Node b );
+ /** assert disequal */
+ void assertDisequal( Node a, Node b );
+ /** needs check */
+ bool needsCheck( Theory::Effort level );
+ /** reset round */
+ void reset_round( Theory::Effort level );
+ /** check */
+ void check( Theory::Effort level, unsigned quant_e );
+private:
+ bool d_needs_computeRelEqr;
+public:
+ void computeRelevantEqr();
+private:
+ void debugPrint( const char * c );
+ //for debugging
+ std::vector< Node > d_quants;
+ std::map< Node, int > d_quant_id;
+ void debugPrintQuant( const char * c, Node q );
+ void debugPrintQuantBody( const char * c, Node q, Node n, bool doVarNum = true );
+public:
+ /** statistics class */
+ class Statistics {
+ public:
+ IntStat d_inst_rounds;
+ IntStat d_conflict_inst;
+ IntStat d_prop_inst;
+ IntStat d_entailment_checks;
+ Statistics();
+ ~Statistics();
+ };
+ Statistics d_statistics;
+ /** Identify this module */
+ std::string identify() const { return "QcfEngine"; }
+};
+
+}
+}
+}
+
+#endif
diff --git a/src/theory/quantifiers/quantifiers_attributes.cpp b/src/theory/quantifiers/quantifiers_attributes.cpp index a5de6ffa9..b41987923 100644 --- a/src/theory/quantifiers/quantifiers_attributes.cpp +++ b/src/theory/quantifiers/quantifiers_attributes.cpp @@ -14,6 +14,7 @@ #include "theory/quantifiers/quantifiers_attributes.h" #include "theory/quantifiers/options.h" +#include "theory/quantifiers/term_database.h" using namespace std; using namespace CVC4; @@ -22,7 +23,8 @@ using namespace CVC4::context; using namespace CVC4::theory; using namespace CVC4::theory::quantifiers; -void QuantifiersAttributes::setUserAttribute( const std::string& attr, Node n ){ +void QuantifiersAttributes::setUserAttribute( const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value ){ + Trace("quant-attr-debug") << "Set " << attr << " " << n << std::endl; if( n.getKind()==FORALL ){ if( attr=="axiom" ){ Trace("quant-attr") << "Set axiom " << n << std::endl; @@ -32,14 +34,22 @@ void QuantifiersAttributes::setUserAttribute( const std::string& attr, Node n ){ Trace("quant-attr") << "Set conjecture " << n << std::endl; ConjectureAttribute ca; n.setAttribute( ca, true ); - }else if( attr=="rr_priority" ){ - //Trace("quant-attr") << "Set rr priority " << n << std::endl; - //RrPriorityAttribute rra; - + }else if( attr=="inst-level" ){ + Assert( node_values.size()==1 ); + uint64_t lvl = node_values[0].getConst<Rational>().getNumerator().getLong(); + Trace("quant-attr") << "Set instantiation level " << n << " to " << lvl << std::endl; + QuantInstLevelAttribute qila; + n.setAttribute( qila, lvl ); + }else if( attr=="rr-priority" ){ + Assert( node_values.size()==1 ); + uint64_t lvl = node_values[0].getConst<Rational>().getNumerator().getLong(); + Trace("quant-attr") << "Set rewrite rule priority " << n << " to " << lvl << std::endl; + RrPriorityAttribute rrpa; + n.setAttribute( rrpa, lvl ); } }else{ for( size_t i=0; i<n.getNumChildren(); i++ ){ - setUserAttribute( attr, n[i] ); + setUserAttribute( attr, n[i], node_values, str_value ); } } } diff --git a/src/theory/quantifiers/quantifiers_attributes.h b/src/theory/quantifiers/quantifiers_attributes.h index cf9620a07..34649ae05 100644 --- a/src/theory/quantifiers/quantifiers_attributes.h +++ b/src/theory/quantifiers/quantifiers_attributes.h @@ -44,7 +44,7 @@ struct QuantifiersAttributes * This function will apply a custom set of attributes to all top-level universal * quantifiers contained in n */ - static void setUserAttribute( const std::string& attr, Node n ); + static void setUserAttribute( const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value ); }; diff --git a/src/theory/quantifiers/quantifiers_rewriter.cpp b/src/theory/quantifiers/quantifiers_rewriter.cpp index eb14b0abe..1a20693f9 100644 --- a/src/theory/quantifiers/quantifiers_rewriter.cpp +++ b/src/theory/quantifiers/quantifiers_rewriter.cpp @@ -159,7 +159,13 @@ RewriteResponse QuantifiersRewriter::preRewrite(TNode in) { } Node body = in[1]; bool doRewrite = false; + std::vector< Node > ipl; while( body.getNumChildren()>=2 && body.getKind()==in.getKind() ){ + if( body.getNumChildren()==3 ){ + for( unsigned i=0; i<body[2].getNumChildren(); i++ ){ + ipl.push_back( body[2][i] ); + } + } for( int i=0; i<(int)body[0].getNumChildren(); i++ ){ args.push_back( body[0][i] ); } @@ -171,7 +177,12 @@ RewriteResponse QuantifiersRewriter::preRewrite(TNode in) { children.push_back( NodeManager::currentNM()->mkNode(kind::BOUND_VAR_LIST,args) ); children.push_back( body ); if( in.getNumChildren()==3 ){ - children.push_back( in[2] ); + for( unsigned i=0; i<in[2].getNumChildren(); i++ ){ + ipl.push_back( in[2][i] ); + } + } + if( !ipl.empty() ){ + children.push_back( NodeManager::currentNM()->mkNode( INST_PATTERN_LIST, ipl ) ); } Node n = NodeManager::currentNM()->mkNode( in.getKind(), children ); if( in!=n ){ @@ -1142,8 +1153,10 @@ Node QuantifiersRewriter::preSkolemizeQuantifiers( Node n, bool polarity, std::v //process body Node nn = preSkolemizeQuantifiers( n[1], polarity, fvTypes, fvs ); std::vector< Node > sk; + Node sub; + std::vector< unsigned > sub_vars; //return skolemized body - return TermDb::mkSkolemizedBody( n, nn, fvTypes, fvs, sk ); + return TermDb::mkSkolemizedBody( n, nn, fvTypes, fvs, sk, sub, sub_vars ); } }else{ //check if it contains a quantifier as a subterm diff --git a/src/theory/quantifiers/rewrite_engine.cpp b/src/theory/quantifiers/rewrite_engine.cpp index 1b13d772e..7d9fa3344 100644 --- a/src/theory/quantifiers/rewrite_engine.cpp +++ b/src/theory/quantifiers/rewrite_engine.cpp @@ -61,8 +61,14 @@ double RewriteEngine::getPriority( Node f ) { //return deterministic ? 0.0 : 1.0; } -void RewriteEngine::check( Theory::Effort e ) { - if( e==Theory::EFFORT_FULL ){ +bool RewriteEngine::needsCheck( Theory::Effort e ){ + return e==Theory::EFFORT_FULL; + //return e>=Theory::EFFORT_LAST_CALL; +} + +void RewriteEngine::check( Theory::Effort e, unsigned quant_e ) { + if( quant_e==QuantifiersEngine::QEFFORT_STANDARD ){ + //if( e==Theory::EFFORT_FULL ){ Trace("rewrite-engine") << "---Rewrite Engine Round, effort = " << e << "---" << std::endl; //if( e==Theory::EFFORT_LAST_CALL ){ // if( !d_quantEngine->getModel()->isModelSet() ){ @@ -102,7 +108,6 @@ void RewriteEngine::check( Theory::Effort e ) { }else{ //otherwise, the search will continue - d_quantEngine->flushLemmas( &d_quantEngine->getOutputChannel() ); } } } diff --git a/src/theory/quantifiers/rewrite_engine.h b/src/theory/quantifiers/rewrite_engine.h index d2108bf3e..1703a9bfc 100644 --- a/src/theory/quantifiers/rewrite_engine.h +++ b/src/theory/quantifiers/rewrite_engine.h @@ -54,7 +54,8 @@ private: public: RewriteEngine( context::Context* c, QuantifiersEngine* qe ); - void check( Theory::Effort e ); + bool needsCheck( Theory::Effort e ); + void check( Theory::Effort e, unsigned quant_e ); void registerQuantifier( Node f ); void assertNode( Node n ); /** Identify this module */ diff --git a/src/theory/quantifiers/term_database.cpp b/src/theory/quantifiers/term_database.cpp index 9ea9ee962..5cc79b9b6 100644 --- a/src/theory/quantifiers/term_database.cpp +++ b/src/theory/quantifiers/term_database.cpp @@ -31,25 +31,39 @@ using namespace CVC4::theory::quantifiers; using namespace CVC4::theory::inst; -bool TermArgTrie::addTerm2( QuantifiersEngine* qe, Node n, int argIndex ){ - if( argIndex<(int)n.getNumChildren() ){ - Node r = qe->getEqualityQuery()->getRepresentative( n[ argIndex ] ); - std::map< Node, TermArgTrie >::iterator it = d_data.find( r ); +TNode TermArgTrie::existsTerm( std::vector< TNode >& reps, int argIndex ) { + if( argIndex==(int)reps.size() ){ + if( d_data.empty() ){ + return Node::null(); + }else{ + return d_data.begin()->first; + } + }else{ + std::map< TNode, TermArgTrie >::iterator it = d_data.find( reps[argIndex] ); if( it==d_data.end() ){ - d_data[r].addTerm2( qe, n, argIndex+1 ); + return Node::null(); + }else{ + return it->second.existsTerm( reps, argIndex+1 ); + } + } +} + +bool TermArgTrie::addTerm( TNode n, std::vector< TNode >& reps, int argIndex ){ + if( argIndex==(int)reps.size() ){ + if( d_data.empty() ){ + //store n in d_data (this should be interpretted as the "data" and not as a reference to a child) + d_data[n].clear(); return true; }else{ - return it->second.addTerm2( qe, n, argIndex+1 ); + return false; } }else{ - //store n in d_data (this should be interpretted as the "data" and not as a reference to a child) - d_data[n].d_data.clear(); - return false; + return d_data[reps[argIndex]].addTerm( n, reps, argIndex+1 ); } } void TermArgTrie::debugPrint( const char * c, Node n, unsigned depth ) { - for( std::map< Node, TermArgTrie >::iterator it = d_data.begin(); it != d_data.end(); ++it ){ + for( std::map< TNode, TermArgTrie >::iterator it = d_data.begin(); it != d_data.end(); ++it ){ for( unsigned i=0; i<depth; i++ ){ Debug(c) << " "; } Debug(c) << it->first << std::endl; it->second.debugPrint( c, n, depth+1 ); @@ -57,7 +71,8 @@ void TermArgTrie::debugPrint( const char * c, Node n, unsigned depth ) { } TermDb::TermDb( context::Context* c, context::UserContext* u, QuantifiersEngine* qe ) : d_quantEngine( qe ), d_op_ccount( u ) { - + d_true = NodeManager::currentNM()->mkConst( true ); + d_false = NodeManager::currentNM()->mkConst( false ); } /** ground terms */ @@ -129,8 +144,6 @@ void TermDb::addTerm( Node n, std::set< Node >& added, bool withinQuant ){ for( size_t i=0; i<d_op_triggers[op].size(); i++ ){ addedLemmas += d_op_triggers[op][i]->addTerm( n ); } - //Message() << "Terms, added lemmas: " << addedLemmas << std::endl; - d_quantEngine->flushLemmas( &d_quantEngine->getOutputChannel() ); } } } @@ -143,65 +156,163 @@ void TermDb::addTerm( Node n, std::set< Node >& added, bool withinQuant ){ } } - void TermDb::reset( Theory::Effort effort ){ +void TermDb::computeArgReps( TNode n ) { + if( d_arg_reps.find( n )==d_arg_reps.end() ){ + eq::EqualityEngine * ee = d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); + for( unsigned j=0; j<n.getNumChildren(); j++ ){ + TNode r = ee->hasTerm( n[j] ) ? ee->getRepresentative( n[j] ) : n[j]; + d_arg_reps[n].push_back( r ); + } + } +} + +void TermDb::computeUfEqcTerms( TNode f ) { + if( d_func_map_eqc_trie.find( f )==d_func_map_eqc_trie.end() ){ + d_func_map_eqc_trie[f].clear(); + eq::EqualityEngine * ee = d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); + for( unsigned i=0; i<d_op_map[f].size(); i++ ){ + TNode n = d_op_map[f][i]; + if( !n.getAttribute(NoMatchAttribute()) ){ + computeArgReps( n ); + TNode r = ee->hasTerm( n ) ? ee->getRepresentative( n ) : n; + d_func_map_eqc_trie[f].d_data[r].addTerm( n, d_arg_reps[n] ); + } + } + } +} + +TNode TermDb::evaluateTerm( TNode n, std::map< TNode, TNode >& subs, bool subsRep ) { + Trace("term-db-eval") << "evaluate term : " << n << std::endl; + eq::EqualityEngine * ee = d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); + if( ee->hasTerm( n ) ){ + Trace("term-db-eval") << "...exists in ee, return rep " << std::endl; + return ee->getRepresentative( n ); + }else if( n.getKind()==BOUND_VARIABLE ){ + Assert( subs.find( n )!=subs.end() ); + Trace("term-db-eval") << "...substitution is : " << subs[n] << std::endl; + if( subsRep ){ + Assert( ee->hasTerm( subs[n] ) ); + Assert( ee->getRepresentative( subs[n] )==subs[n] ); + return subs[n]; + }else{ + return evaluateTerm( subs[n], subs, subsRep ); + } + }else{ + if( n.hasOperator() ){ + TNode f = getOperator( n ); + if( !f.isNull() ){ + std::vector< TNode > args; + for( unsigned i=0; i<n.getNumChildren(); i++ ){ + TNode c = evaluateTerm( n[i], subs, subsRep ); + if( c.isNull() ){ + return TNode::null(); + } + Trace("term-db-eval") << "Got child : " << c << std::endl; + args.push_back( c ); + } + Trace("term-db-eval") << "Get term from DB" << std::endl; + TNode nn = d_func_map_trie[f].existsTerm( args ); + Trace("term-db-eval") << "Got term " << nn << std::endl; + if( !nn.isNull() ){ + if( ee->hasTerm( nn ) ){ + Trace("term-db-eval") << "return rep " << std::endl; + return ee->getRepresentative( nn ); + }else{ + //Assert( false ); + } + } + } + } + return TNode::null(); + } +} + +bool TermDb::isEntailed( TNode n, std::map< TNode, TNode >& subs, bool subsRep, bool pol ) { + Trace("term-db-eval") << "Check entailed : " << n << ", pol = " << pol << std::endl; + Assert( n.getType().isBoolean() ); + if( n.getKind()==EQUAL ){ + TNode n1 = evaluateTerm( n[0], subs, subsRep ); + if( !n1.isNull() ){ + TNode n2 = evaluateTerm( n[1], subs, subsRep ); + if( !n2.isNull() ){ + eq::EqualityEngine * ee = d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); + Assert( ee->hasTerm( n1 ) ); + Assert( ee->hasTerm( n2 ) ); + if( pol ){ + return n1==n2 || ee->areEqual( n1, n2 ); + }else{ + return n1!=n2 && ee->areDisequal( n1, n2, false ); + } + } + } + }else if( n.getKind()==APPLY_UF ){ + TNode n1 = evaluateTerm( n, subs, subsRep ); + if( !n1.isNull() ){ + eq::EqualityEngine * ee = d_quantEngine->getTheoryEngine()->getMasterEqualityEngine(); + Assert( ee->hasTerm( n1 ) ); + TNode n2 = pol ? d_true : d_false; + if( ee->hasTerm( n2 ) ){ + return ee->areEqual( n1, n2 ); + } + } + }else if( n.getKind()==NOT ){ + return isEntailed( n[0], subs, subsRep, !pol ); + }else if( n.getKind()==OR || n.getKind()==AND ){ + bool simPol = ( pol && n.getKind()==OR ) || ( !pol && n.getKind()==AND ); + for( unsigned i=0; i<n.getNumChildren(); i++ ){ + if( isEntailed( n[i], subs, subsRep, pol ) ){ + if( simPol ){ + return true; + } + }else{ + if( !simPol ){ + return false; + } + } + } + return !simPol; + }else if( n.getKind()==IFF || n.getKind()==ITE ){ + for( unsigned i=0; i<2; i++ ){ + if( isEntailed( n[0], subs, subsRep, i==0 ) ){ + unsigned ch = ( n.getKind()==IFF || i==0 ) ? 1 : 2; + bool reqPol = ( n.getKind()==ITE || i==0 ) ? pol : !pol; + return isEntailed( n[ch], subs, subsRep, reqPol ); + } + } + } + return false; +} + +void TermDb::reset( Theory::Effort effort ){ int nonCongruentCount = 0; int congruentCount = 0; int alreadyCongruentCount = 0; + d_op_nonred_count.clear(); + d_arg_reps.clear(); + d_func_map_trie.clear(); + d_func_map_eqc_trie.clear(); //rebuild d_func/pred_map_trie for each operation, this will calculate all congruent terms for( std::map< Node, std::vector< Node > >::iterator it = d_op_map.begin(); it != d_op_map.end(); ++it ){ d_op_nonred_count[ it->first ] = 0; if( !it->second.empty() ){ - if( it->second[0].getType().isBoolean() ){ - d_pred_map_trie[ 0 ][ it->first ].d_data.clear(); - d_pred_map_trie[ 1 ][ it->first ].d_data.clear(); - }else{ - d_func_map_trie[ it->first ].d_data.clear(); - for( int i=0; i<(int)it->second.size(); i++ ){ - Node n = it->second[i]; - computeModelBasisArgAttribute( n ); - if( !n.getAttribute(NoMatchAttribute()) ){ - if( !d_func_map_trie[ it->first ].addTerm( d_quantEngine, n ) ){ - NoMatchAttribute nma; - n.setAttribute(nma,true); - Debug("term-db-cong") << n << " is redundant." << std::endl; - congruentCount++; - }else{ - nonCongruentCount++; - d_op_nonred_count[ it->first ]++; - } - }else{ + for( unsigned i=0; i<it->second.size(); i++ ){ + Node n = it->second[i]; + computeModelBasisArgAttribute( n ); + if( !n.getAttribute(NoMatchAttribute()) ){ + computeArgReps( n ); + if( !d_func_map_trie[ it->first ].addTerm( n, d_arg_reps[n] ) ){ + NoMatchAttribute nma; + n.setAttribute(nma,true); + Debug("term-db-cong") << n << " is redundant." << std::endl; congruentCount++; - alreadyCongruentCount++; - } - } - } - } - } - for( int i=0; i<2; i++ ){ - Node n = NodeManager::currentNM()->mkConst( i==1 ); - if( d_quantEngine->getEqualityQuery()->getEngine()->hasTerm( n ) ){ - eq::EqClassIterator eqc( d_quantEngine->getEqualityQuery()->getEngine()->getRepresentative( n ), - d_quantEngine->getEqualityQuery()->getEngine() ); - while( !eqc.isFinished() ){ - Node en = (*eqc); - computeModelBasisArgAttribute( en ); - if( en.getKind()==APPLY_UF && !TermDb::hasInstConstAttr(en) ){ - if( !en.getAttribute(NoMatchAttribute()) ){ - Node op = getOperator( en ); - if( !d_pred_map_trie[i][op].addTerm( d_quantEngine, en ) ){ - NoMatchAttribute nma; - en.setAttribute(nma,true); - Debug("term-db-cong") << en << " is redundant." << std::endl; - congruentCount++; - }else{ - nonCongruentCount++; - d_op_nonred_count[ op ]++; - } }else{ - alreadyCongruentCount++; + nonCongruentCount++; + d_op_nonred_count[ it->first ]++; } + }else{ + congruentCount++; + alreadyCongruentCount++; } - ++eqc; } } } @@ -219,6 +330,39 @@ void TermDb::addTerm( Node n, std::set< Node >& added, bool withinQuant ){ } } +TermArgTrie * TermDb::getTermArgTrie( Node f ) { + std::map< Node, TermArgTrie >::iterator itut = d_func_map_trie.find( f ); + if( itut!=d_func_map_trie.end() ){ + return &itut->second; + }else{ + return NULL; + } +} + +TermArgTrie * TermDb::getTermArgTrie( Node eqc, Node f ) { + computeUfEqcTerms( f ); + std::map< Node, TermArgTrie >::iterator itut = d_func_map_eqc_trie.find( f ); + if( itut==d_func_map_eqc_trie.end() ){ + return NULL; + }else{ + if( eqc.isNull() ){ + return &itut->second; + }else{ + std::map< TNode, TermArgTrie >::iterator itute = itut->second.d_data.find( eqc ); + if( itute!=itut->second.d_data.end() ){ + return &itute->second; + }else{ + return NULL; + } + } + } +} + +TNode TermDb::existsTerm( Node f, Node n ) { + computeArgReps( n ); + return d_func_map_trie[f].existsTerm( d_arg_reps[n] ); +} + Node TermDb::getModelBasisTerm( TypeNode tn, int i ){ if( d_model_basis_term.find( tn )==d_model_basis_term.end() ){ Node mbt; @@ -448,14 +592,15 @@ void getSelfSel( const DatatypeConstructor& dc, Node n, TypeNode ntn, std::vecto Node TermDb::mkSkolemizedBody( Node f, Node n, std::vector< TypeNode >& argTypes, std::vector< TNode >& fvs, - std::vector< Node >& sk ) { + std::vector< Node >& sk, Node& sub, std::vector< unsigned >& sub_vars ) { + Assert( sk.empty() || sk.size()==f[0].getNumChildren() ); //calculate the variables and substitution std::vector< TNode > ind_vars; std::vector< unsigned > ind_var_indicies; std::vector< TNode > vars; std::vector< unsigned > var_indicies; for( unsigned i=0; i<f[0].getNumChildren(); i++ ){ - if( options::dtStcInduction() && datatypes::DatatypesRewriter::isTermDatatype( f[0][i] ) ){ + if( isInductionTerm( f[0][i] ) ){ ind_vars.push_back( f[0][i] ); ind_var_indicies.push_back( i ); }else{ @@ -463,19 +608,23 @@ Node TermDb::mkSkolemizedBody( Node f, Node n, std::vector< TypeNode >& argTypes var_indicies.push_back( i ); } Node s; - //make the new function symbol - if( argTypes.empty() ){ - s = NodeManager::currentNM()->mkSkolem( "skv", f[0][i].getType(), "created during skolemization" ); + //make the new function symbol or use existing + if( i>=sk.size() ){ + if( argTypes.empty() ){ + s = NodeManager::currentNM()->mkSkolem( "skv", f[0][i].getType(), "created during skolemization" ); + }else{ + TypeNode typ = NodeManager::currentNM()->mkFunctionType( argTypes, f[0][i].getType() ); + Node op = NodeManager::currentNM()->mkSkolem( "skop", typ, "op created during pre-skolemization" ); + //DOTHIS: set attribute on op, marking that it should not be selected as trigger + std::vector< Node > funcArgs; + funcArgs.push_back( op ); + funcArgs.insert( funcArgs.end(), fvs.begin(), fvs.end() ); + s = NodeManager::currentNM()->mkNode( kind::APPLY_UF, funcArgs ); + } + sk.push_back( s ); }else{ - TypeNode typ = NodeManager::currentNM()->mkFunctionType( argTypes, f[0][i].getType() ); - Node op = NodeManager::currentNM()->mkSkolem( "skop", typ, "op created during pre-skolemization" ); - //DOTHIS: set attribute on op, marking that it should not be selected as trigger - std::vector< Node > funcArgs; - funcArgs.push_back( op ); - funcArgs.insert( funcArgs.end(), fvs.begin(), fvs.end() ); - s = NodeManager::currentNM()->mkNode( kind::APPLY_UF, funcArgs ); + Assert( sk[i].getType()==f[0][i].getType() ); } - sk.push_back( s ); } Node ret; if( vars.empty() ){ @@ -489,39 +638,48 @@ Node TermDb::mkSkolemizedBody( Node f, Node n, std::vector< TypeNode >& argTypes ret = n.substitute( vars.begin(), vars.end(), var_sk.begin(), var_sk.end() ); } if( !ind_vars.empty() ){ - Trace("stc-ind") << "Ind strengthen : (not " << f << ")" << std::endl; - Trace("stc-ind") << "Skolemized is : " << ret << std::endl; - Node nret; + Trace("sk-ind") << "Ind strengthen : (not " << f << ")" << std::endl; + Trace("sk-ind") << "Skolemized is : " << ret << std::endl; Node n_str_ind; TypeNode tn = ind_vars[0].getType(); - if( datatypes::DatatypesRewriter::isTypeDatatype(tn) ){ - Node k = sk[ind_var_indicies[0]]; + Node k = sk[ind_var_indicies[0]]; + Node nret = ret.substitute( ind_vars[0], k ); + //note : everything is under a negation + //the following constructs ~( R( x, k ) => ~P( x ) ) + if( options::dtStcInduction() && datatypes::DatatypesRewriter::isTypeDatatype(tn) ){ const Datatype& dt = ((DatatypeType)(tn).toType()).getDatatype(); std::vector< Node > disj; for( unsigned i=0; i<dt.getNumConstructors(); i++ ){ - std::vector< Node > selfSel; - getSelfSel( dt[i], k, tn, selfSel ); - std::vector< Node > conj; - conj.push_back( NodeManager::currentNM()->mkNode( APPLY_TESTER, Node::fromExpr( dt[i].getTester() ), k ).negate() ); - for( unsigned j=0; j<selfSel.size(); j++ ){ - conj.push_back( ret.substitute( ind_vars[0], selfSel[j] ).negate() ); - } - disj.push_back( conj.size()==1 ? conj[0] : NodeManager::currentNM()->mkNode( OR, conj ) ); + std::vector< Node > selfSel; + getSelfSel( dt[i], k, tn, selfSel ); + std::vector< Node > conj; + conj.push_back( NodeManager::currentNM()->mkNode( APPLY_TESTER, Node::fromExpr( dt[i].getTester() ), k ).negate() ); + for( unsigned j=0; j<selfSel.size(); j++ ){ + conj.push_back( ret.substitute( ind_vars[0], selfSel[j] ).negate() ); + } + disj.push_back( conj.size()==1 ? conj[0] : NodeManager::currentNM()->mkNode( OR, conj ) ); } Assert( !disj.empty() ); n_str_ind = disj.size()==1 ? disj[0] : NodeManager::currentNM()->mkNode( AND, disj ); - Trace("stc-ind") << "Strengthening is : " << n_str_ind << std::endl; - nret = ret.substitute( ind_vars[0], k ); + }else if( options::intWfInduction() && tn.isInteger() ){ + Node icond = NodeManager::currentNM()->mkNode( GEQ, k, NodeManager::currentNM()->mkConst( Rational(0) ) ); + Node iret = ret.substitute( ind_vars[0], NodeManager::currentNM()->mkNode( MINUS, k, NodeManager::currentNM()->mkConst( Rational(1) ) ) ).negate(); + n_str_ind = NodeManager::currentNM()->mkNode( OR, icond.negate(), iret ); + n_str_ind = NodeManager::currentNM()->mkNode( AND, icond, n_str_ind ); }else{ - Trace("stc-ind") << "Unknown induction for term : " << ind_vars[0] << ", type = " << tn << std::endl; + Trace("sk-ind") << "Unknown induction for term : " << ind_vars[0] << ", type = " << tn << std::endl; Assert( false ); } - + Trace("sk-ind") << "Strengthening is : " << n_str_ind << std::endl; + std::vector< Node > rem_ind_vars; rem_ind_vars.insert( rem_ind_vars.end(), ind_vars.begin()+1, ind_vars.end() ); if( !rem_ind_vars.empty() ){ Node bvl = NodeManager::currentNM()->mkNode( BOUND_VAR_LIST, rem_ind_vars ); nret = NodeManager::currentNM()->mkNode( FORALL, bvl, nret ); + nret = Rewriter::rewrite( nret ); + sub = nret; + sub_vars.insert( sub_vars.end(), ind_var_indicies.begin()+1, ind_var_indicies.end() ); n_str_ind = NodeManager::currentNM()->mkNode( FORALL, bvl, n_str_ind.negate() ).negate(); } ret = NodeManager::currentNM()->mkNode( OR, nret, n_str_ind ); @@ -535,7 +693,17 @@ Node TermDb::getSkolemizedBody( Node f ){ if( d_skolem_body.find( f )==d_skolem_body.end() ){ std::vector< TypeNode > fvTypes; std::vector< TNode > fvs; - d_skolem_body[ f ] = mkSkolemizedBody( f, f[1], fvTypes, fvs, d_skolem_constants[f] ); + Node sub; + std::vector< unsigned > sub_vars; + d_skolem_body[ f ] = mkSkolemizedBody( f, f[1], fvTypes, fvs, d_skolem_constants[f], sub, sub_vars ); + //store sub quantifier information + if( !sub.isNull() ){ + //if we are skolemizing one at a time, we already know the skolem constants of the sub-quantified formula, store them + Assert( d_skolem_constants[sub].empty() ); + for( unsigned i=0; i<sub_vars.size(); i++ ){ + d_skolem_constants[sub].push_back( d_skolem_constants[f][sub_vars[i]] ); + } + } Assert( d_skolem_constants[f].size()==f[0].getNumChildren() ); if( options::sortInference() ){ for( unsigned i=0; i<d_skolem_constants[f].size(); i++ ){ @@ -752,6 +920,17 @@ void TermDb::registerTrigger( theory::inst::Trigger* tr, Node op ){ } } +bool TermDb::isInductionTerm( Node n ) { + if( options::dtStcInduction() && datatypes::DatatypesRewriter::isTermDatatype( n ) ){ + return true; + } + if( options::intWfInduction() && n.getType().isInteger() ){ + return true; + } + return false; +} + + bool TermDb::isRewriteRule( Node q ) { return !getRewriteRule( q ).isNull(); } diff --git a/src/theory/quantifiers/term_database.h b/src/theory/quantifiers/term_database.h index c839d08d7..504ecd667 100644 --- a/src/theory/quantifiers/term_database.h +++ b/src/theory/quantifiers/term_database.h @@ -55,6 +55,13 @@ typedef expr::Attribute<ModelBasisArgAttributeId, uint64_t> ModelBasisArgAttribu struct BoundIntLitAttributeId {}; typedef expr::Attribute<BoundIntLitAttributeId, uint64_t> BoundIntLitAttribute; +//for quantifier instantiation level +struct QuantInstLevelAttributeId {}; +typedef expr::Attribute<QuantInstLevelAttributeId, uint64_t> QuantInstLevelAttribute; + +//rewrite-rule priority +struct RrPriorityAttributeId {}; +typedef expr::Attribute<RrPriorityAttributeId, uint64_t> RrPriorityAttribute; class QuantifiersEngine; @@ -69,14 +76,14 @@ namespace rrinst{ namespace quantifiers { class TermArgTrie { -private: - bool addTerm2( QuantifiersEngine* qe, Node n, int argIndex ); public: /** the data */ - std::map< Node, TermArgTrie > d_data; + std::map< TNode, TermArgTrie > d_data; public: - bool addTerm( QuantifiersEngine* qe, Node n ) { return addTerm2( qe, n, 0 ); } + TNode existsTerm( std::vector< TNode >& reps, int argIndex = 0 ); + bool addTerm( TNode n, std::vector< TNode >& reps, int argIndex = 0 ); void debugPrint( const char * c, Node n, unsigned depth = 0 ); + void clear() { d_data.clear(); } };/* class TermArgTrie */ @@ -103,6 +110,9 @@ private: public: TermDb( context::Context* c, context::UserContext* u, QuantifiersEngine* qe ); ~TermDb(){} + /** boolean terms */ + Node d_true; + Node d_false; /** ground terms */ unsigned getNumGroundTerms( Node f ); /** count number of non-redundant ground terms per operator */ @@ -111,16 +121,32 @@ public: std::map< Node, std::vector< Node > > d_op_map; /** map from APPLY_UF functions to trie */ std::map< Node, TermArgTrie > d_func_map_trie; - /** map from APPLY_UF predicates to trie */ - std::map< Node, TermArgTrie > d_pred_map_trie[2]; + std::map< Node, TermArgTrie > d_func_map_eqc_trie; + /**mapping from UF terms to representatives of their arguments */ + std::map< TNode, std::vector< TNode > > d_arg_reps; /** map from type nodes to terms of that type */ std::map< TypeNode, std::vector< Node > > d_type_map; /** add a term to the database */ void addTerm( Node n, std::set< Node >& added, bool withinQuant = false ); /** reset (calculate which terms are active) */ void reset( Theory::Effort effort ); - /** get operation */ + /** get operator*/ Node getOperator( Node n ); + /** get term arg index */ + TermArgTrie * getTermArgTrie( Node f ); + TermArgTrie * getTermArgTrie( Node eqc, Node f ); + /** exists term */ + TNode existsTerm( Node f, Node n ); + /** compute arg reps */ + void computeArgReps( TNode n ); + /** compute uf eqc terms */ + void computeUfEqcTerms( TNode f ); + /** evaluate a term under a substitution. Return representative in EE if possible. + * subsRep is whether subs contains only representatives + */ + TNode evaluateTerm( TNode n, std::map< TNode, TNode >& subs, bool subsRep ); + /** is entailed (incomplete check) */ + bool isEntailed( TNode n, std::map< TNode, TNode >& subs, bool subsRep, bool pol ); public: /** parent structure (for efficient E-matching): n -> op -> index -> L @@ -206,7 +232,7 @@ public: std::map< Node, std::vector< Node > > d_skolem_constants; /** make the skolemized body f[e/x] */ static Node mkSkolemizedBody( Node f, Node n, std::vector< TypeNode >& fvTypes, std::vector< TNode >& fvs, - std::vector< Node >& sk ); + std::vector< Node >& sk, Node& sub, std::vector< unsigned >& sub_vars ); /** get the skolemized body */ Node getSkolemizedBody( Node f); @@ -245,11 +271,18 @@ public: int isInstanceOf( Node n1, Node n2 ); /** filter all nodes that have instances */ void filterInstances( std::vector< Node >& nodes ); -public: + +public: //for induction + /** is induction variable */ + static bool isInductionTerm( Node n ); + + +public: //general queries concerning quantified formulas wrt modules /** is quantifier treated as a rewrite rule? */ static bool isRewriteRule( Node q ); /** get the rewrite rule associated with the quanfied formula */ static Node getRewriteRule( Node q ); + };/* class TermDb */ }/* CVC4::theory::quantifiers namespace */ diff --git a/src/theory/quantifiers/theory_quantifiers.cpp b/src/theory/quantifiers/theory_quantifiers.cpp index 4ba3c499d..4e8a0a411 100644 --- a/src/theory/quantifiers/theory_quantifiers.cpp +++ b/src/theory/quantifiers/theory_quantifiers.cpp @@ -42,6 +42,8 @@ TheoryQuantifiers::TheoryQuantifiers(Context* c, context::UserContext* u, Output d_baseDecLevel = -1; out.handleUserAttribute( "axiom", this ); out.handleUserAttribute( "conjecture", this ); + out.handleUserAttribute( "inst-level", this ); + out.handleUserAttribute( "rr-priority", this ); } TheoryQuantifiers::~TheoryQuantifiers() { @@ -193,6 +195,6 @@ bool TheoryQuantifiers::restart(){ } } -void TheoryQuantifiers::setUserAttribute( const std::string& attr, Node n ){ - QuantifiersAttributes::setUserAttribute( attr, n ); +void TheoryQuantifiers::setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value){ + QuantifiersAttributes::setUserAttribute( attr, n, node_values, str_value ); } diff --git a/src/theory/quantifiers/theory_quantifiers.h b/src/theory/quantifiers/theory_quantifiers.h index ffd3c4c59..6febc8417 100644 --- a/src/theory/quantifiers/theory_quantifiers.h +++ b/src/theory/quantifiers/theory_quantifiers.h @@ -69,7 +69,7 @@ public: void shutdown() { } std::string identify() const { return std::string("TheoryQuantifiers"); } bool flipDecision(); - void setUserAttribute( const std::string& attr, Node n ); + void setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value); eq::EqualityEngine* getMasterEqualityEngine() { return d_masterEqualityEngine; } bool ppDontRewriteSubterm(TNode atom) { return atom.getKind() == kind::FORALL || atom.getKind() == kind::EXISTS; } private: diff --git a/src/theory/quantifiers_engine.cpp b/src/theory/quantifiers_engine.cpp index c55ffa2a6..e54dfe42f 100644 --- a/src/theory/quantifiers_engine.cpp +++ b/src/theory/quantifiers_engine.cpp @@ -30,6 +30,7 @@ #include "theory/quantifiers/bounded_integers.h" #include "theory/quantifiers/rewrite_engine.h" #include "theory/quantifiers/quant_conflict_find.h" +#include "theory/quantifiers/conjecture_generator.h" #include "theory/quantifiers/relevant_domain.h" #include "theory/uf/options.h" #include "theory/uf/theory_uf.h" @@ -83,6 +84,12 @@ d_lemmas_produced_c(u){ }else{ d_qcf = NULL; } + if( options::conjectureGen() ){ + d_sg_gen = new quantifiers::ConjectureGenerator( this, c ); + d_modules.push_back( d_sg_gen ); + }else{ + d_sg_gen = NULL; + } if( !options::finiteModelFind() || options::fmfInstEngine() ){ //the instantiation must set incomplete flag unless finite model finding is turned on d_inst_engine = new quantifiers::InstantiationEngine( this, !options::finiteModelFind() ); @@ -159,35 +166,50 @@ void QuantifiersEngine::finishInit(){ void QuantifiersEngine::check( Theory::Effort e ){ CodeTimer codeTimer(d_time); - bool needsCheck = e>=Theory::EFFORT_LAST_CALL; //always need to check at or above last call - for( int i=0; i<(int)d_modules.size(); i++ ){ - if( d_modules[i]->needsCheck( e ) ){ - needsCheck = true; + bool needsCheck = false; + bool needsBuildModel = false; + std::vector< QuantifiersModule* > qm; + if( d_model->getNumAssertedQuantifiers()>0 ){ + needsCheck = e>=Theory::EFFORT_LAST_CALL; //always need to check at or above last call + for( int i=0; i<(int)d_modules.size(); i++ ){ + if( d_modules[i]->needsCheck( e ) ){ + qm.push_back( d_modules[i] ); + needsCheck = true; + } } } if( needsCheck ){ Trace("quant-engine") << "Quantifiers Engine check, level = " << e << std::endl; + Trace("quant-engine-debug") << " modules to check : "; + for( unsigned i=0; i<qm.size(); i++ ){ + Trace("quant-engine-debug") << qm[i]->identify() << " "; + } + Trace("quant-engine-debug") << std::endl; + Trace("quant-engine-debug") << " # quantified formulas = " << d_model->getNumAssertedQuantifiers() << std::endl; + if( !getMasterEqualityEngine()->consistent() ){ Trace("quant-engine") << "Master equality engine not consistent, return." << std::endl; return; } - Trace("quant-engine-debug") << "Resetting modules..." << std::endl; + Trace("quant-engine-debug") << "Resetting all modules..." << std::endl; //reset relevant information + d_conflict = false; d_hasAddedLemma = false; d_term_db->reset( e ); d_eq_query->reset(); if( d_rel_dom ){ d_rel_dom->reset(); } + d_model->reset_round(); for( int i=0; i<(int)d_modules.size(); i++ ){ d_modules[i]->reset_round( e ); } - Trace("quant-engine-debug") << "Done resetting modules." << std::endl; + Trace("quant-engine-debug") << "Done resetting all modules." << std::endl; if( e==Theory::EFFORT_LAST_CALL ){ //if effort is last call, try to minimize model first if( options::finiteModelFind() ){ - //first, check if we can minimize the model further + //first, check if we can minimize the model further FIXME: remove? if( !((uf::TheoryUF*)getTheoryEngine()->theoryOf( THEORY_UF ))->getStrongSolver()->minimize() ){ return; } @@ -196,19 +218,27 @@ void QuantifiersEngine::check( Theory::Effort e ){ }else if( e==Theory::EFFORT_FULL ){ ++(d_statistics.d_instantiation_rounds); } - Trace("quant-engine-debug") << "Check with modules..." << std::endl; - for( int i=0; i<(int)d_modules.size(); i++ ){ - Trace("quant-engine-debug") << "Check " << d_modules[i]->identify().c_str() << "..." << std::endl; - d_modules[i]->check( e ); + + Trace("quant-engine-debug") << "Check modules that needed check..." << std::endl; + for( unsigned quant_e = QEFFORT_CONFLICT; quant_e<=QEFFORT_MODEL; quant_e++ ){ + for( int i=0; i<(int)qm.size(); i++ ){ + Trace("quant-engine-debug") << "Check " << d_modules[i]->identify().c_str() << "..." << std::endl; + qm[i]->check( e, quant_e ); + } + //flush all current lemmas + flushLemmas(); + //if we have added one, stop + if( d_hasAddedLemma ){ + break; + } } - Trace("quant-engine-debug") << "Done check with modules." << std::endl; + Trace("quant-engine-debug") << "Done check modules that needed check." << std::endl; + //build the model if not done so already // this happens if no quantifiers are currently asserted and no model-building module is enabled if( e==Theory::EFFORT_LAST_CALL && !d_hasAddedLemma ){ if( options::produceModels() && !d_model->isModelSet() ){ - Trace("quant-engine-debug") << "Build the model..." << std::endl; - d_te->getModelBuilder()->buildModel( d_model, true ); - Trace("quant-engine-debug") << "Done building the model." << std::endl; + needsBuildModel = true; } if( Trace.isOn("inst-per-quant") ){ for( std::map< Node, int >::iterator it = d_total_inst_debug.begin(); it != d_total_inst_debug.end(); ++it ){ @@ -224,6 +254,16 @@ void QuantifiersEngine::check( Theory::Effort e ){ } } Trace("quant-engine") << "Finished quantifiers engine check." << std::endl; + }else{ + if( e==Theory::EFFORT_LAST_CALL && options::produceModels() ){ + needsBuildModel = true; + } + } + + if( needsBuildModel ){ + Trace("quant-engine-debug") << "Build the model..." << std::endl; + d_te->getModelBuilder()->buildModel( d_model, true ); + Trace("quant-engine-debug") << "Done building the model." << std::endl; } } @@ -261,7 +301,7 @@ void QuantifiersEngine::registerQuantifier( Node f ){ void QuantifiersEngine::registerPattern( std::vector<Node> & pattern) { for(std::vector<Node>::iterator p = pattern.begin(); p != pattern.end(); ++p){ std::set< Node > added; - getTermDatabase()->addTerm(*p,added); + getTermDatabase()->addTerm( *p, added ); } } @@ -314,6 +354,10 @@ Node QuantifiersEngine::getNextDecisionRequest(){ void QuantifiersEngine::addTermToDatabase( Node n, bool withinQuant ){ std::set< Node > added; getTermDatabase()->addTerm( n, added, withinQuant ); + //maybe have triggered instantiations if we are doing eager instantiation + if( options::eagerInstQuant() ){ + flushLemmas(); + } //added contains also the Node that just have been asserted in this branch if( d_quant_rel ){ for( std::set< Node >::iterator i=added.begin(), end=added.end(); i!=end; i++ ){ @@ -372,7 +416,7 @@ bool QuantifiersEngine::addInstantiation( Node f, std::vector< Node >& vars, std } } } - setInstantiationLevelAttr( body, f[1], maxInstLevel+1, terms ); + setInstantiationLevelAttr( body, f[1], maxInstLevel+1 ); } Trace("inst-debug") << "*** Lemma is " << lem << std::endl; ++(d_statistics.d_instantiations); @@ -383,22 +427,52 @@ bool QuantifiersEngine::addInstantiation( Node f, std::vector< Node >& vars, std } } -void QuantifiersEngine::setInstantiationLevelAttr( Node n, Node qn, uint64_t level, std::vector< Node >& inst_terms ){ +void QuantifiersEngine::setInstantiationLevelAttr( Node n, Node qn, uint64_t level ){ + Trace("inst-level-debug") << "IL : " << n << " " << qn << " " << level << std::endl; //if not from the vector of terms we instantiatied - if( std::find( inst_terms.begin(), inst_terms.end(), n )==inst_terms.end() ){ + if( qn.getKind()!=BOUND_VARIABLE && n!=qn ){ //if this is a new term, without an instantiation level - if( n!=qn && !n.hasAttribute(InstLevelAttribute()) ){ + if( !n.hasAttribute(InstLevelAttribute()) ){ InstLevelAttribute ila; n.setAttribute(ila,level); + Trace("inst-level-debug") << "Set instantiation level " << n << " to " << level << std::endl; } - Assert( qn.getKind()!=BOUND_VARIABLE ); Assert( n.getNumChildren()==qn.getNumChildren() ); for( int i=0; i<(int)n.getNumChildren(); i++ ){ - setInstantiationLevelAttr( n[i], qn[i], level, inst_terms ); + setInstantiationLevelAttr( n[i], qn[i], level ); + } + } +} + +void QuantifiersEngine::setInstantiationLevelAttr( Node n, uint64_t level ){ + InstLevelAttribute ila; + n.setAttribute(ila,level); + for( int i=0; i<(int)n.getNumChildren(); i++ ){ + setInstantiationLevelAttr( n[i], level ); + } +} + +bool QuantifiersEngine::isTermEligibleForInstantiation( Node n, Node f, bool print ) { + if( n.hasAttribute(InstLevelAttribute()) ){ + unsigned ml = options::instMaxLevel(); + if( f.hasAttribute(QuantInstLevelAttribute()) ){ + ml = f.getAttribute(QuantInstLevelAttribute()); + } + if( n.getAttribute(InstLevelAttribute())>ml ){ + Trace("inst-add-debug") << "Term " << n << " has instantiation level " << n.getAttribute(InstLevelAttribute()); + Trace("inst-add-debug") << ", which is more than maximum allowed level " << ml << " for this quantified formula." << std::endl; + return false; + } + }else{ + if( options::instLevelInputOnly() ){ + Trace("inst-add-debug") << "Term " << n << " does not have an instantiation level." << std::endl; + return false; } } + return true; } + Node QuantifiersEngine::getSubstitute( Node n, std::vector< Node >& terms ){ if( n.getKind()==INST_CONSTANT ){ Debug("check-inst") << "Substitute inst constant : " << n << std::endl; @@ -511,6 +585,10 @@ bool QuantifiersEngine::addLemma( Node lem, bool doCache ){ } } +void QuantifiersEngine::addRequirePhase( Node lit, bool req ){ + d_phase_req_waiting[lit] = req; +} + bool QuantifiersEngine::addInstantiation( Node f, InstMatch& m, bool mkRep, bool modEq, bool modInst ){ std::vector< Node > terms; //make sure there are values for each variable we are instantiating @@ -536,24 +614,32 @@ bool QuantifiersEngine::addInstantiation( Node f, std::vector< Node >& terms, bo if( mkRep ){ //pick the best possible representative for instantiation, based on past use and simplicity of term terms[i] = d_eq_query->getInternalRepresentative( terms[i], f, i ); - //Trace("inst-add-debug") << " (" << terms[i] << ")"; + Trace("inst-add-debug2") << " (" << terms[i] << ")"; } } Trace("inst-add-debug") << std::endl; + //check based on instantiation level if( options::instMaxLevel()!=-1 ){ for( unsigned i=0; i<terms.size(); i++ ){ - if( terms[i].hasAttribute(InstLevelAttribute()) && - (int)terms[i].getAttribute(InstLevelAttribute())>options::instMaxLevel() ){ - Trace("inst-add-debug") << "Term " << terms[i] << " has instantiation level " << terms[i].getAttribute(InstLevelAttribute()); - Trace("inst-add-debug") << ", which is more than maximum allowed level " << options::instMaxLevel() << std::endl; + if( !isTermEligibleForInstantiation( terms[i], f, true ) ){ return false; } } } + //check for entailment + if( options::instNoEntail() ){ + std::map< TNode, TNode > subs; + for( unsigned i=0; i<terms.size(); i++ ){ + subs[f[0][i]] = terms[i]; + } + if( d_term_db->isEntailed( f[1], subs, false, true ) ){ + Trace("inst-add-debug") << " -> Currently entailed." << std::endl; + return false; + } + } //check for duplication - ///* bool alreadyExists = false; if( options::incrementalSolving() ){ Trace("inst-add-debug") << "Adding into context-dependent inst trie, modEq = " << modEq << ", modInst = " << modInst << std::endl; @@ -575,7 +661,7 @@ bool QuantifiersEngine::addInstantiation( Node f, std::vector< Node >& terms, bo ++(d_statistics.d_inst_duplicate_eq); return false; } - //*/ + //add the instantiation bool addedInst = addInstantiation( f, d_term_db->d_vars[f], terms ); @@ -608,18 +694,21 @@ bool QuantifiersEngine::addSplitEquality( Node n1, Node n2, bool reqPhase, bool return addSplit( fm ); } -void QuantifiersEngine::flushLemmas( OutputChannel* out ){ +void QuantifiersEngine::flushLemmas(){ if( !d_lemmas_waiting.empty() ){ - if( !out ){ - out = &getOutputChannel(); - } //take default output channel if none is provided d_hasAddedLemma = true; for( int i=0; i<(int)d_lemmas_waiting.size(); i++ ){ - out->lemma( d_lemmas_waiting[i], false, true ); + getOutputChannel().lemma( d_lemmas_waiting[i], false, true ); } d_lemmas_waiting.clear(); } + if( !d_phase_req_waiting.empty() ){ + for( std::map< Node, bool >::iterator it = d_phase_req_waiting.begin(); it != d_phase_req_waiting.end(); ++it ){ + getOutputChannel().requirePhase( it->first, it->second ); + } + d_phase_req_waiting.clear(); + } } void QuantifiersEngine::getPhaseReqTerms( Node f, std::vector< Node >& nodes ){ @@ -793,7 +882,6 @@ Node EqualityQueryQuantifiersEngine::getInternalRepresentative( Node a, Node f, //if cbqi is active, do not choose instantiation constant terms if( !options::cbqi() || !quantifiers::TermDb::hasInstConstAttr(eqc[i]) ){ int score = getRepScore( eqc[i], f, index ); - //score prefers earliest use of this term as a representative if( r_best.isNull() || ( score>=0 && ( r_best_score<0 || score<r_best_score ) ) ){ r_best = eqc[i]; r_best_score = score; @@ -945,8 +1033,21 @@ int getDepth( Node n ){ } } +//smaller the score, the better int EqualityQueryQuantifiersEngine::getRepScore( Node n, Node f, int index ){ - return d_rep_score.find( n )==d_rep_score.end() ? -1 : d_rep_score[n]; //initial + int s; + if( options::instMaxLevel()!=-1 ){ + //score prefer lowest instantiation level + if( n.hasAttribute(InstLevelAttribute()) ){ + s = n.getAttribute(InstLevelAttribute()); + }else{ + s = options::instLevelInputOnly() ? -1 : 0; + } + }else{ + //score prefers earliest use of this term as a representative + s = d_rep_score.find( n )==d_rep_score.end() ? -1 : d_rep_score[n]; + } + return s; //return ( d_rep_score.find( n )==d_rep_score.end() ? 100 : 0 ) + getDepth( n ); //term depth } diff --git a/src/theory/quantifiers_engine.h b/src/theory/quantifiers_engine.h index 7786e0b70..e914280c5 100644 --- a/src/theory/quantifiers_engine.h +++ b/src/theory/quantifiers_engine.h @@ -52,7 +52,7 @@ public: /* reset at a round */ virtual void reset_round( Theory::Effort e ){} /* Call during quantifier engine's check */ - virtual void check( Theory::Effort e ) = 0; + virtual void check( Theory::Effort e, unsigned quant_e ) = 0; /* Called for new quantifiers */ virtual void registerQuantifier( Node q ) = 0; virtual void assertNode( Node n ) = 0; @@ -73,6 +73,7 @@ namespace quantifiers { class QuantConflictFind; class RewriteEngine; class RelevantDomain; + class ConjectureGenerator; }/* CVC4::theory::quantifiers */ namespace inst { @@ -112,6 +113,14 @@ private: quantifiers::QuantConflictFind* d_qcf; /** rewrite rules utility */ quantifiers::RewriteEngine * d_rr_engine; + /** subgoal generator */ + quantifiers::ConjectureGenerator * d_sg_gen; +public: //effort levels + enum { + QEFFORT_CONFLICT, + QEFFORT_STANDARD, + QEFFORT_MODEL, + }; private: /** list of all quantifiers seen */ std::vector< Node > d_quants; @@ -120,8 +129,12 @@ private: BoolMap d_lemmas_produced_c; /** lemmas waiting */ std::vector< Node > d_lemmas_waiting; + /** phase requirements waiting */ + std::map< Node, bool > d_phase_req_waiting; /** has added lemma this round */ bool d_hasAddedLemma; + /** has a conflict been found */ + bool d_conflict; /** list of all instantiations produced for each quantifier */ std::map< Node, inst::InstMatchTrie > d_inst_match_trie; std::map< Node, inst::CDInstMatchTrie* > d_c_inst_match_trie; @@ -192,7 +205,9 @@ private: /** instantiate f with arguments terms */ bool addInstantiation( Node f, std::vector< Node >& vars, std::vector< Node >& terms ); /** set instantiation level attr */ - void setInstantiationLevelAttr( Node n, Node qn, uint64_t level, std::vector< Node >& inst_terms ); + static void setInstantiationLevelAttr( Node n, Node qn, uint64_t level ); + /** flush lemmas */ + void flushLemmas(); public: /** get instantiation */ Node getInstantiation( Node f, std::vector< Node >& vars, std::vector< Node >& terms ); @@ -206,6 +221,8 @@ public: bool existsInstantiation( Node f, InstMatch& m, bool modEq = true, bool modInst = false ); /** add lemma lem */ bool addLemma( Node lem, bool doCache = true ); + /** add require phase */ + void addRequirePhase( Node lit, bool req ); /** do instantiation specified by m */ bool addInstantiation( Node f, InstMatch& m, bool mkRep = true, bool modEq = false, bool modInst = false ); /** add instantiation */ @@ -216,10 +233,12 @@ public: bool addSplitEquality( Node n1, Node n2, bool reqPhase = false, bool reqPhasePol = true ); /** has added lemma */ bool hasAddedLemma() { return !d_lemmas_waiting.empty() || d_hasAddedLemma; } - /** flush lemmas */ - void flushLemmas( OutputChannel* out = NULL ); /** get number of waiting lemmas */ int getNumLemmasWaiting() { return (int)d_lemmas_waiting.size(); } + /** set instantiation level attr */ + static void setInstantiationLevelAttr( Node n, uint64_t level ); + /** is term eligble for instantiation? */ + bool isTermEligibleForInstantiation( Node n, Node f, bool print = false ); public: /** get number of quantifiers */ int getNumQuantifiers() { return (int)d_quants.size(); } diff --git a/src/theory/rep_set.cpp b/src/theory/rep_set.cpp index 954272549..5a9b92fa0 100644 --- a/src/theory/rep_set.cpp +++ b/src/theory/rep_set.cpp @@ -38,6 +38,7 @@ int RepSet::getNumRepresentatives( TypeNode tn ) const{ } void RepSet::add( TypeNode tn, Node n ){ + Assert( n.getType()==tn ); d_tmap[ n ] = (int)d_type_reps[tn].size(); Trace("rsi-debug") << "Add rep #" << d_type_reps[tn].size() << " for " << tn << " : " << n << std::endl; d_type_reps[tn].push_back( n ); diff --git a/src/theory/strings/kinds b/src/theory/strings/kinds index 4266c02f5..0f68d1207 100644 --- a/src/theory/strings/kinds +++ b/src/theory/strings/kinds @@ -88,6 +88,11 @@ operator REGEXP_LOOP 2:3 "regexp loop" operator REGEXP_EMPTY 0 "regexp empty" operator REGEXP_SIGMA 0 "regexp all characters" +#internal +operator REGEXP_RV 1 "regexp rv (internal use only)" +typerule REGEXP_RV ::CVC4::theory::strings::RegExpRVTypeRule + +#typerules typerule REGEXP_CONCAT ::CVC4::theory::strings::RegExpConcatTypeRule typerule REGEXP_UNION ::CVC4::theory::strings::RegExpUnionTypeRule typerule REGEXP_INTER ::CVC4::theory::strings::RegExpInterTypeRule diff --git a/src/theory/strings/regexp_operation.cpp b/src/theory/strings/regexp_operation.cpp index 369278994..e769eb712 100644 --- a/src/theory/strings/regexp_operation.cpp +++ b/src/theory/strings/regexp_operation.cpp @@ -1183,8 +1183,19 @@ void RegExpOpr::getCharSet( Node r, std::set<unsigned> &pcset, SetNodes &pvset ) } } +bool RegExpOpr::isPairNodesInSet(std::set< PairNodes > &s, Node n1, Node n2) { + for(std::set< PairNodes >::const_iterator itr = s.begin(); + itr != s.end(); ++itr) { + if(itr->first == n1 && itr->second == n2 || + itr->first == n2 && itr->second == n1) { + return true; + } + } + return false; +} Node RegExpOpr::intersectInternal( Node r1, Node r2, std::map< unsigned, std::set< PairNodes > > cache, bool &spflag ) { + Trace("regexp-intersect") << "Starting INTERSECT:\n "<< mkString(r1) << ",\n " << mkString(r2) << std::endl; if(spflag) { //TODO: var return Node::null(); @@ -1230,11 +1241,18 @@ Node RegExpOpr::intersectInternal( Node r1, Node r2, std::map< unsigned, std::se spflag = true; } } + if(Trace.isOn("regexp-debug")) { + Trace("regexp-debug") << "Try CSET( " << cset.size() << " ) = "; + for(std::set<unsigned>::const_iterator itr = cset.begin(); + itr != cset.end(); itr++) { + Trace("regexp-debug") << *itr << ", "; + } + Trace("regexp-debug") << std::endl; + } for(std::set<unsigned>::const_iterator itr = cset.begin(); itr != cset.end(); itr++) { CVC4::String c( CVC4::String::convertUnsignedIntToChar(*itr) ); - std::pair< Node, Node > p(r1, r2); - if(cache[ *itr ].find(p) == cache[ *itr ].end()) { + if(!isPairNodesInSet(cache[ *itr ], r1, r2)) { Node r1l = derivativeSingle(r1, c); Node r2l = derivativeSingle(r2, c); std::map< unsigned, std::set< PairNodes > > cache2(cache); @@ -1263,10 +1281,208 @@ Node RegExpOpr::intersectInternal( Node r1, Node r2, std::map< unsigned, std::se Trace("regexp-intersect") << "INTERSECT( " << mkString(r1) << ", " << mkString(r2) << " ) = " << mkString(rNode) << std::endl; return rNode; } + +bool RegExpOpr::containC2(unsigned cnt, Node n) { + if(n.getKind() == kind::REGEXP_RV) { + unsigned y = n[0].getConst<Rational>().getNumerator().toUnsignedInt(); + return cnt == y; + } else if(n.getKind() == kind::REGEXP_CONCAT) { + for( unsigned i=0; i<n.getNumChildren(); i++ ) { + if(containC2(cnt, n[i])) { + return true; + } + } + } else if(n.getKind() == kind::REGEXP_STAR) { + return containC2(cnt, n[0]); + } else if(n.getKind() == kind::REGEXP_UNION) { + for( unsigned i=0; i<n.getNumChildren(); i++ ) { + if(containC2(cnt, n[i])) { + return true; + } + } + } + return false; +} +Node RegExpOpr::convert1(unsigned cnt, Node n) { + Trace("regexp-debug") << "Converting " << n << " at " << cnt << "... " << std::endl; + Node r1, r2; + convert2(cnt, n, r1, r2); + Trace("regexp-debug") << "... getting r1=" << r1 << ", and r2=" << r2 << std::endl; + Node ret = NodeManager::currentNM()->mkNode(kind::REGEXP_CONCAT, + NodeManager::currentNM()->mkNode(kind::REGEXP_STAR, r1), r2); + ret = Rewriter::rewrite( ret ); + Trace("regexp-debug") << "... done convert at " << cnt << ", with return " << ret << std::endl; + return ret; +} +void RegExpOpr::convert2(unsigned cnt, Node n, Node &r1, Node &r2) { + if(n == d_emptyRegexp) { + r1 = d_emptyRegexp; + r2 = d_emptyRegexp; + } else if(n == d_emptySingleton) { + r1 = d_emptySingleton; + r2 = d_emptySingleton; + } else if(n.getKind() == kind::REGEXP_RV) { + unsigned y = n[0].getConst<Rational>().getNumerator().toUnsignedInt(); + r1 = d_emptySingleton; + if(cnt == y) { + r2 = d_emptyRegexp; + } else { + r2 = n; + } + } else if(n.getKind() == kind::REGEXP_CONCAT) { + //TODO + //convert2 x (r@(Seq l r1)) + // | contains x r1 = let (r2,r3) = convert2 x r1 + // in (Seq l r2, r3) + // | otherwise = (Empty, r) + bool flag = true; + std::vector<Node> vr1, vr2; + for( unsigned i=0; i<n.getNumChildren(); i++ ) { + if(containC2(cnt, n[i])) { + Node t1, t2; + convert2(cnt, n[i], t1, t2); + vr1.push_back(t1); + r1 = vr1.size()==0 ? d_emptyRegexp : vr1.size()==1 ? vr1[0] : + NodeManager::currentNM()->mkNode(kind::REGEXP_CONCAT, vr1); + vr2.push_back(t2); + for( unsigned j=i+1; j<n.getNumChildren(); j++ ) { + vr2.push_back(n[j]); + } + r2 = vr2.size()==0 ? d_emptyRegexp : vr2.size()==1 ? vr2[0] : + NodeManager::currentNM()->mkNode(kind::REGEXP_CONCAT, vr2); + flag = false; + break; + } else { + vr1.push_back(n[i]); + } + } + if(flag) { + r1 = d_emptySingleton; + r2 = n; + } + } else if(n.getKind() == kind::REGEXP_UNION) { + std::vector<Node> vr1, vr2; + for( unsigned i=0; i<n.getNumChildren(); i++ ) { + Node t1, t2; + convert2(cnt, n[i], t1, t2); + vr1.push_back(t1); + vr2.push_back(t2); + } + r1 = NodeManager::currentNM()->mkNode(kind::REGEXP_UNION, vr1); + r2 = NodeManager::currentNM()->mkNode(kind::REGEXP_UNION, vr2); + } else if(n.getKind() == kind::STRING_TO_REGEXP) { + r1 = d_emptySingleton; + r2 = n; + } else { + //is it possible? + } +} +Node RegExpOpr::intersectInternal2( Node r1, Node r2, std::map< PairNodes, Node > cache, bool &spflag, unsigned cnt ) { + Trace("regexp-intersect") << "Starting INTERSECT:\n "<< mkString(r1) << ",\n " << mkString(r2) << std::endl; + //if(Trace.isOn("regexp-debug")) { + // Trace("regexp-debug") << "... with cache:\n"; + // for(std::map< PairNodes, Node >::const_iterator itr=cache.begin(); + // itr!=cache.end();itr++) { + // Trace("regexp-debug") << "(" << itr->first.first << "," << itr->first.second << ")->" << itr->second << std::endl; + // } + //} + if(spflag) { + //TODO: var + return Node::null(); + } + std::pair < Node, Node > p(r1, r2); + std::map < std::pair< Node, Node >, Node >::const_iterator itr = d_inter_cache.find(p); + Node rNode; + if(itr != d_inter_cache.end()) { + rNode = itr->second; + } else { + if(r1 == d_emptyRegexp || r2 == d_emptyRegexp) { + rNode = d_emptyRegexp; + } else if(r1 == d_emptySingleton || r2 == d_emptySingleton) { + Node exp; + int r = delta((r1 == d_emptySingleton ? r2 : r1), exp); + if(r == 0) { + //TODO: variable + spflag = true; + } else if(r == 1) { + rNode = d_emptySingleton; + } else { + rNode = d_emptyRegexp; + } + } else if(r1 == r2) { + rNode = convert1(cnt, r1); + } else { + PairNodes p(r1, r2); + std::map< PairNodes, Node >::const_iterator itrcache = cache.find(p); + if(itrcache != cache.end()) { + rNode = itrcache->second; + } else { + if(checkConstRegExp(r1) && checkConstRegExp(r2)) { + std::vector< unsigned > cset; + std::set< unsigned > cset1, cset2; + std::set< Node > vset1, vset2; + firstChars(r1, cset1, vset1); + firstChars(r2, cset2, vset2); + std::set_intersection(cset1.begin(), cset1.end(), cset2.begin(), cset1.end(), + std::inserter(cset, cset.begin())); + std::vector< Node > vec_nodes; + Node delta_exp; + int flag = delta(r1, delta_exp); + int flag2 = delta(r2, delta_exp); + if(flag != 2 && flag2 != 2) { + if(flag == 1 && flag2 == 1) { + vec_nodes.push_back(d_emptySingleton); + } else { + //TODO + spflag = true; + } + } + if(Trace.isOn("regexp-debug")) { + Trace("regexp-debug") << "Try CSET( " << cset.size() << " ) = "; + for(std::vector<unsigned>::const_iterator itr = cset.begin(); + itr != cset.end(); itr++) { + CVC4::String c( CVC4::String::convertUnsignedIntToChar(*itr) ); + Trace("regexp-debug") << c << ", "; + } + Trace("regexp-debug") << std::endl; + } + for(std::vector<unsigned>::const_iterator itr = cset.begin(); + itr != cset.end(); itr++) { + CVC4::String c( CVC4::String::convertUnsignedIntToChar(*itr) ); + Node r1l = derivativeSingle(r1, c); + Node r2l = derivativeSingle(r2, c); + std::map< PairNodes, Node > cache2(cache); + PairNodes p(r1, r2); + cache2[ p ] = NodeManager::currentNM()->mkNode(kind::REGEXP_RV, NodeManager::currentNM()->mkConst(CVC4::Rational(cnt))); + Node rt = intersectInternal2(r1l, r2l, cache2, spflag, cnt+1); + rt = convert1(cnt, rt); + if(spflag) { + //TODO: + return Node::null(); + } + rt = Rewriter::rewrite( NodeManager::currentNM()->mkNode(kind::REGEXP_CONCAT, + NodeManager::currentNM()->mkNode(kind::STRING_TO_REGEXP, NodeManager::currentNM()->mkConst(c)), rt) ); + vec_nodes.push_back(rt); + } + rNode = vec_nodes.size()==0 ? d_emptyRegexp : vec_nodes.size()==1 ? vec_nodes[0] : + NodeManager::currentNM()->mkNode(kind::REGEXP_UNION, vec_nodes); + rNode = Rewriter::rewrite( rNode ); + } else { + //TODO: non-empty var set + spflag = true; + } + } + } + d_inter_cache[p] = rNode; + } + Trace("regexp-intersect") << "End of INTERSECT( " << mkString(r1) << ", " << mkString(r2) << " ) = " << mkString(rNode) << std::endl; + return rNode; +} Node RegExpOpr::intersect(Node r1, Node r2, bool &spflag) { - std::map< unsigned, std::set< PairNodes > > cache; + //std::map< unsigned, std::set< PairNodes > > cache; + std::map< PairNodes, Node > cache; if(checkConstRegExp(r1) && checkConstRegExp(r2)) { - return intersectInternal(r1, r2, cache, spflag); + return intersectInternal2(r1, r2, cache, spflag, 1); } else { spflag = true; return Node::null(); @@ -1516,6 +1732,12 @@ std::string RegExpOpr::mkString( Node r ) { retStr += "]"; break; } + case kind::REGEXP_RV: { + retStr += "<"; + retStr += r[0].getConst<Rational>().getNumerator().toString(); + retStr += ">"; + break; + } default: Trace("strings-error") << "Unsupported term: " << r << " in RegExp." << std::endl; //Assert( false ); diff --git a/src/theory/strings/regexp_operation.h b/src/theory/strings/regexp_operation.h index e4ae1208d..2ae578cd6 100644 --- a/src/theory/strings/regexp_operation.h +++ b/src/theory/strings/regexp_operation.h @@ -69,9 +69,14 @@ private: std::string niceChar( Node r ); int gcd ( int a, int b ); Node mkAllExceptOne( char c ); + bool isPairNodesInSet(std::set< PairNodes > &s, Node n1, Node n2); void getCharSet( Node r, std::set<unsigned> &pcset, SetNodes &pvset ); Node intersectInternal( Node r1, Node r2, std::map< unsigned, std::set< PairNodes > > cache, bool &spflag ); + bool containC2(unsigned cnt, Node n); + Node convert1(unsigned cnt, Node n); + void convert2(unsigned cnt, Node n, Node &r1, Node &r2); + Node intersectInternal2( Node r1, Node r2, std::map< PairNodes, Node > cache, bool &spflag, unsigned cnt ); void firstChars( Node r, std::set<unsigned> &pcset, SetNodes &pvset ); //TODO: for intersection diff --git a/src/theory/strings/theory_strings.cpp b/src/theory/strings/theory_strings.cpp index 2856ce1e0..30e529663 100644 --- a/src/theory/strings/theory_strings.cpp +++ b/src/theory/strings/theory_strings.cpp @@ -2500,6 +2500,7 @@ bool TheoryStrings::checkMemberships() { std::vector< Node > processed; std::vector< Node > cprocessed; + Trace("regexp-debug") << "Checking Memberships ... " << std::endl; //if(options::stringEIT()) { //TODO: Opt for normal forms for(NodeListMap::const_iterator itr_xr = d_str_re_map.begin(); @@ -2507,6 +2508,7 @@ bool TheoryStrings::checkMemberships() { bool spflag = false; Node x = (*itr_xr).first; NodeList* lst = (*itr_xr).second; + Trace("regexp-debug") << "Checking Memberships for " << x << std::endl; if(d_inter_index.find(x) == d_inter_index.end()) { d_inter_index[x] = 0; } @@ -2515,6 +2517,7 @@ bool TheoryStrings::checkMemberships() { if(lst->size() == 1) { d_inter_cache[x] = (*lst)[0]; d_inter_index[x] = 1; + Trace("regexp-debug") << "... only one choice " << std::endl; } else if(lst->size() > 1) { Node r; if(d_inter_cache.find(x) != d_inter_cache.end()) { @@ -2528,6 +2531,7 @@ bool TheoryStrings::checkMemberships() { for(int i=0; i<cur_inter_idx; i++) { ++itr_lst; } + Trace("regexp-debug") << "... staring from : " << cur_inter_idx << ", we have " << lst->size() << std::endl; for(;itr_lst != lst->end(); ++itr_lst) { Node r2 = *itr_lst; r = d_regexp_opr.intersect(r, r2, spflag); @@ -2561,6 +2565,7 @@ bool TheoryStrings::checkMemberships() { } //} + Trace("regexp-debug") << "... No Intersec Conflict in Memberships " << std::endl; if(!addedLemma) { for( unsigned i=0; i<d_regexp_memberships.size(); i++ ) { //check regular expression membership diff --git a/src/theory/strings/theory_strings_rewriter.cpp b/src/theory/strings/theory_strings_rewriter.cpp index 12ff92b5e..e37cabfb6 100644 --- a/src/theory/strings/theory_strings_rewriter.cpp +++ b/src/theory/strings/theory_strings_rewriter.cpp @@ -164,8 +164,12 @@ Node TheoryStringsRewriter::prerewriteOrRegExp(TNode node) { for(unsigned i=0; i<node.getNumChildren(); ++i) { if(node[i].getKind() == kind::REGEXP_UNION) { Node tmpNode = prerewriteOrRegExp( node[i] ); - for(unsigned int j=0; j<tmpNode.getNumChildren(); ++j) { - node_vec.push_back( tmpNode[j] ); + if(tmpNode.getKind() == kind::REGEXP_UNION) { + for(unsigned int j=0; j<tmpNode.getNumChildren(); ++j) { + node_vec.push_back( tmpNode[j] ); + } + } else { + node_vec.push_back( tmpNode ); } flag = true; } else if(node[i].getKind() == kind::REGEXP_EMPTY) { @@ -200,6 +204,7 @@ bool TheoryStringsRewriter::checkConstRegExp( TNode t ) { bool TheoryStringsRewriter::testConstStringInRegExp( CVC4::String &s, unsigned int index_start, TNode r ) { Assert( index_start <= s.size() ); + Trace("regexp-debug") << "Checking " << s << " in " << r << ", starting at " << index_start << std::endl; int k = r.getKind(); switch( k ) { case kind::STRING_TO_REGEXP: { @@ -278,7 +283,7 @@ bool TheoryStringsRewriter::testConstStringInRegExp( CVC4::String &s, unsigned i return false; } case kind::REGEXP_SIGMA: { - if(s.size() == 1) { + if(s.size() == index_start + 1) { return true; } else { return false; @@ -302,7 +307,7 @@ Node TheoryStringsRewriter::rewriteMembership(TNode node) { if(node[1].getKind() == kind::REGEXP_EMPTY) { retNode = NodeManager::currentNM()->mkConst( false ); - } else if( x.getKind() == kind::CONST_STRING && checkConstRegExp(node[1]) ) { + } else if(x.getKind()==kind::CONST_STRING && checkConstRegExp(node[1])) { //test whether x in node[1] CVC4::String s = x.getConst<String>(); retNode = NodeManager::currentNM()->mkConst( testConstStringInRegExp( s, 0, node[1] ) ); @@ -311,10 +316,12 @@ Node TheoryStringsRewriter::rewriteMembership(TNode node) { retNode = one.eqNode(NodeManager::currentNM()->mkNode(kind::STRING_LENGTH, x)); } else if(node[1].getKind() == kind::REGEXP_STAR && node[1][0].getKind() == kind::REGEXP_SIGMA) { retNode = NodeManager::currentNM()->mkConst( true ); - } else if( x != node[0] ) { + } else if(node[1].getKind() == kind::STRING_TO_REGEXP) { + retNode = x.eqNode(node[1][0]); + } else if(x != node[0]) { retNode = NodeManager::currentNM()->mkNode( kind::STRING_IN_REGEXP, x, node[1] ); } - return retNode; + return retNode; } RewriteResponse TheoryStringsRewriter::postRewrite(TNode node) { diff --git a/src/theory/strings/theory_strings_type_rules.h b/src/theory/strings/theory_strings_type_rules.h index 6d1bb1c98..8a51ea36c 100644 --- a/src/theory/strings/theory_strings_type_rules.h +++ b/src/theory/strings/theory_strings_type_rules.h @@ -466,6 +466,21 @@ public: } }; +class RegExpRVTypeRule { +public: + inline static TypeNode computeType(NodeManager* nodeManager, TNode n, bool check) + throw (TypeCheckingExceptionPrivate, AssertionException) { + if( check ) { + TypeNode t = n[0].getType(check); + if (!t.isInteger()) { + throw TypeCheckingExceptionPrivate(n, "expecting an integer term in RV"); + } + } + return nodeManager->regexpType(); + } +}; + + }/* CVC4::theory::strings namespace */ }/* CVC4::theory namespace */ }/* CVC4 namespace */ diff --git a/src/theory/theory.h b/src/theory/theory.h index 7bfc7051f..ac3d018fb 100644 --- a/src/theory/theory.h +++ b/src/theory/theory.h @@ -678,7 +678,7 @@ public: * This function is called when an attribute is set by a user. In SMT-LIBv2 this is done * via the syntax (! n :attr) */ - virtual void setUserAttribute(const std::string& attr, Node n) { + virtual void setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value) { Unimplemented("Theory %s doesn't support Theory::setUserAttribute interface", identify().c_str()); } diff --git a/src/theory/theory_engine.cpp b/src/theory/theory_engine.cpp index eb1da84b2..1b0270b94 100644 --- a/src/theory/theory_engine.cpp +++ b/src/theory/theory_engine.cpp @@ -1668,11 +1668,11 @@ void TheoryEngine::ppUnconstrainedSimp(vector<Node>& assertions) } -void TheoryEngine::setUserAttribute(const std::string& attr, Node n) { +void TheoryEngine::setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value) { Trace("te-attr") << "set user attribute " << attr << " " << n << endl; if( d_attr_handle.find( attr )!=d_attr_handle.end() ){ for( size_t i=0; i<d_attr_handle[attr].size(); i++ ){ - d_attr_handle[attr][i]->setUserAttribute(attr, n); + d_attr_handle[attr][i]->setUserAttribute(attr, n, node_values, str_value); } } else { //unhandled exception? diff --git a/src/theory/theory_engine.h b/src/theory/theory_engine.h index e6684d56e..eec4f1168 100644 --- a/src/theory/theory_engine.h +++ b/src/theory/theory_engine.h @@ -820,7 +820,7 @@ public: * This function is called when an attribute is set by a user. In SMT-LIBv2 this is done * via the syntax (! n :attr) */ - void setUserAttribute(const std::string& attr, Node n); + void setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value); /** * Handle user attribute. diff --git a/test/regress/regress0/strings/Makefile.am b/test/regress/regress0/strings/Makefile.am index ddc0eae7c..233962d72 100644 --- a/test/regress/regress0/strings/Makefile.am +++ b/test/regress/regress0/strings/Makefile.am @@ -30,7 +30,6 @@ TESTS = \ str005.smt2 \ str006.smt2 \ str007.smt2 \ - fmf001.smt2 \ fmf002.smt2 \ type001.smt2 \ type003.smt2 \ @@ -53,6 +52,7 @@ TESTS = \ FAILING_TESTS = EXTRA_DIST = $(TESTS) \ + fmf001.smt2 \ regexp002.smt2 \ type002.smt2 diff --git a/test/regress/run_regression b/test/regress/run_regression index f0ffd765d..d234153a3 100755 --- a/test/regress/run_regression +++ b/test/regress/run_regression @@ -41,6 +41,10 @@ while [ $# -gt 2 ]; do shift done +[[ "$VALGRIND" = "1" ]] && { + wrapper="libtool --mode=execute valgrind $wrapper" +} + cvc4=$1 benchmark_orig=$2 benchmark="$benchmark_orig" @@ -250,7 +254,15 @@ fi # we have to actual error file same treatment as other files. differences in # versions of echo/bash were causing failure on some platforms and not on others +# (also grep out valgrind output, if 0 errors reported by valgrind) actual_error=$(cat $errfile) +if [[ "$VALGRIND" = "1" ]]; then + #valgrind_output=$(cat $errfile|grep -E "^==[0-9]+== "|) + valgrind_num_errors=$(cat $errfile|grep -E "^==[0-9]+== "|tail -n1|awk '{print $4}') + echo "valgrind errors (not suppressed): $valgrind_num_errors" 1>&2 + + ((valgrind_num_errors == 0)) && actual_error=$(echo "$actual_error"|grep -vE "^==[0-9]+== ") +fi if [ -z "$actual_error" ]; then # in case expected stderr output is empty, make sure we don't differ # by a newline, which we would if we echo "" >"$experrfile" diff --git a/test/unit/prop/cnf_stream_white.h b/test/unit/prop/cnf_stream_white.h index 665126059..679b68a2f 100644 --- a/test/unit/prop/cnf_stream_white.h +++ b/test/unit/prop/cnf_stream_white.h @@ -93,6 +93,9 @@ public: void renewVar(SatLiteral lit, int level = -1) { } + void spendResource() { + } + void interrupt() { } |