; expander.lisp  --  symbolic expansion utilities for ACL2
; Copyright (C) 2013, Regents of the University of Texas
; Originally written by Matt Kaufmann
; License: A 3-clause BSD license.  See the LICENSE file distributed with ACL2.

; Changes by Pete Manolios Wed Jul 15 21:22:03 EDT 2009
; Changes by Daron Vroon shortly thereafter.
; Made minor modifications and added simplification
; functions at the end of the file that allow us to simplify the
; "termination checkpoints" we generate. See the end of the file
; for documentation, examples, and ideas for extending this work.

; Historical comments:

;   Although some attempt has been made to bring it up to date with ACL2
;   Release 2.0, this file should be viewed as a set of routines that may prove
;   useful in using ACL2 but _not_ as code that can be trusted to the extent
;   that the ACL2 system prover may be trusted.

;   For ACL2 3.0, removed symsim-for-value (not clear that it's been used for a
;   long time).  And, we allow symsim to return multiple clauses.

; Top-level routines (only the first two have reasonable documentation):

; SYMSIM: See :doc string

; DEFTHM?: See :doc string

; TOOL1-FN: Takes a list of hypotheses and some hints and returns a simplified
; version, as a list of clauses.  Also returns a list of all runes used and a
; list of assumptions generated by forcing.

; TOOL2-FN: Takes a term and a list of hypotheses, together with some
; hints, and returns a term that is the result of rewriting the term
; under those hypotheses, using those hints.  Note that the hypotheses
; are used to build a context, using forward chaining and probably
; linear arithmetic as well, but are not simplified.  This tool also
; sends back a list of runes.

; Changes by Daron Vroon on June 4, 2007:

; TOOL1-FN and TOOL2-FN have now each been split into 2 functions: a
; "front end" that calculates the ctx, ens, and wrld to use, along
; with some other calculations, and a "back end" that uses the ctx,
; ens, and wrld to do what the original function did. The
; functionality of TOOL1-FN and TOOL2-FN have not been changed, and
; users of these functions should notice no difference.

; Splitting these functions in two allowed for the definition of two
; new functions, TOOL1-FN0 and TOOL2-FN0. These perform the same task
; as TOOL1-FN and TOOL2-FN, respectively, with one difference: the
; user must supply the ctx, ens, and wrld. This is helpful to people
; who want to simplify expressions in the midst of making other
; changes that require a modified world or a user-defined ctx.

; To certify this book:
; (certify-book "expander").

(in-package "ACL2")
(include-book "xdoc/top" :dir :system)

(defxdoc expander
  :parents (miscellaneous)
  :short "Routines for simplifying terms."
  :long "<p>The routines provided by the expander can be useful in generating
theorems and simplifying expressions, under given assumptions.</p>

<p>They were developed rather in a hurry and should be used without expecting
the usual standards of care present in development of ACL2 code.  Once these
routines are used to generate theorems for you, you should check the theorems
directly with ACL2.</p>

<p>To load the expander, run:</p>

@({
   (include-book \"misc/expander\" :dir :system)
})")

; We know what we are doing when using state:
(set-state-ok t)

(encapsulate
 ((hidden-expander-function (x) t))
 (logic)
 (local (defun hidden-expander-function (x) x)))

(defun silly-rec-fn-for-rewrite* (x)
  (declare (xargs :verify-guards t))
  (if (consp x)
      (silly-rec-fn-for-rewrite* (cdr x))
    x))

;; (verify-guards silly-rec-fn-for-rewrite*)

(program)

(defconst *valid-output-names-except-error*
  (set-difference-eq *valid-output-names* '(error)))

(defmacro tool1 (hyps &key hints (prove-assumptions 't) inhibit-output)
  `(er-progn (tool1-fn ',hyps state ',hints ',prove-assumptions
                       ',inhibit-output
                       t t)
             (value :invisible)))

(defun pop-clauses (pool)
  (mv-let (signal pool-lst cl-set hint-settings pop-history new-pool)
          (pop-clause1 pool nil)
          (declare (ignore pool-lst hint-settings pop-history))
          (cond
           ((or (eq signal 'win) (eq signal 'lose))
            (mv signal cl-set))
           (t
            (mv-let (signal rest-clauses)
                    (pop-clauses new-pool)
                    (cond
                     ((eq signal 'win) (mv 'win (append cl-set rest-clauses)))
                     (t (mv signal nil))))))))

(defun prove-loop1-clauses (pool-lst clauses pspv hints ens wrld ctx state)

; Based on prove-loop1, except returns (mv erp ttree clauses pairs
; new-pspv state), where pairs is a list of pairs (assumnotes
; . clause), suitable for the third argument of prove-loop1 starting
; with forcing round 1.

  (sl-let (erp pspv jppl-flg state)
          (waterfall 0 pool-lst clauses pspv hints ens wrld ctx state
                     (initial-step-limit wrld state))
          (declare (ignore jppl-flg))
          (cond
           (erp (mv step-limit t nil nil nil nil state))
           (t
            (mv-let
             (signal new-clauses)
             (pop-clauses (access prove-spec-var pspv :pool))
             (cond
              ((eq signal 'lose)
               (mv step-limit t nil nil nil nil state))
              (t
               (mv-let
                (pairs new-pspv state)

; Forcing round...

                (process-assumptions 0 pspv wrld state)
                (mv-let
                 (erp ttree state)
                 (accumulate-ttree-and-step-limit-into-state
                  (access prove-spec-var new-pspv :tag-tree)
                  step-limit
                  state)
                 (assert$
                  (null erp)
                  (mv step-limit nil ttree new-clauses pairs new-pspv
                      state)))))))))))

(defun prove-loop-clauses (clauses pspv hints ens wrld ctx state)

; We either cause an error or return a ttree.  If the ttree contains
; :byes, the proof attempt has technically failed, although it has
; succeeded modulo the :byes.

  (pprogn
   (increment-timer 'other-time state)
   (sl-let (erp ttree new-clauses pairs new-pspv state)
           (prove-loop1-clauses nil
                                clauses
                                pspv
                                hints ens wrld ctx state)
           (pprogn
            (increment-timer 'prove-time state)
            (cond
             (erp (mv step-limit erp nil nil nil nil state))
             (t (mv step-limit nil ttree new-clauses pairs new-pspv
                    state)))))))

(defun prove-clauses (term pspv hints ens wrld ctx state)

; Adapted from prove.

  (prog2$
   (initialize-brr-stack state)
   (sl-let (erp ttree1 clauses pairs new-pspv state)
           (prove-loop-clauses (list (list term))
                               (change prove-spec-var pspv
                                       :user-supplied-term term
                                       :orig-hints hints)
                               hints ens wrld ctx state)
           (cond
            (erp (mv step-limit t nil nil nil nil state))
            (t
             (mv-let
              (erp val state)
              (chk-assumption-free-ttree ttree1 ctx state)
              (declare (ignore val))
              (cond
               (erp (mv step-limit t nil nil nil nil state))
               (t (pprogn
                   (let ((byes (tagged-objects :bye ttree1)))
                     (cond
                      (byes
                       (pprogn

; The use of ~*1 below instead of just ~&1 forces each of the defthm
; forms to come out on a new line indented 5 spaces.  As is already
; known with ~&1, it can tend to scatter the items randomly -- some on
; the left margin and others indented -- depending on where each item
; fits flat on the line first offered.

                        (io? prove nil state
                             (wrld byes)
                             (fms "To complete this proof you should try to ~
                                   admit the following ~
                                   event~#0~[~/s~]~|~%~*1~%See the discussion ~
                                   of :by hints in :DOC hints regarding the ~
                                   name~#0~[~/s~] displayed above."
                                  (list (cons #\0 byes)
                                        (cons #\1
                                              (list ""
                                                    "~|~     ~q*."
                                                    "~|~     ~q*,~|and~|"
                                                    "~|~     ~q*,~|~%"

                                                    (make-defthm-forms-for-byes
                                                     byes wrld))))
                                  (proofs-co state)
                                  state
                                  nil))
                        state))
                      (t state)))
                   (mv step-limit erp ttree1 clauses pairs
                       (change prove-spec-var new-pspv
                               :pool nil)
                       state))))))))))

(defun chk-for-hidden-expander-function1 (cl)
  (let ((term (car (last cl))))
    (case-match term
                (('hide ('hidden-expander-function &))
                 term)
                (t
                 (er hard 'chk-for-hidden-expander-function1
                     "Expected clause to end with hidden call of ~
                      HIDDEN-EXPANDER-FUNCTION, but instead clause is ~p0."
                     cl)))))

(defun chk-for-hidden-expander-function (clauses)
  (cond ((null clauses) nil)
        (t (and (chk-for-hidden-expander-function1 (car clauses))
                (chk-for-hidden-expander-function (cdr clauses))))))

(defun untranslate-clause-lst (cl-lst wrld)
  (cond
   ((null cl-lst)
    nil)
   (t
    (cons (prettyify-clause1 (car cl-lst) wrld)
          (untranslate-clause-lst (cdr cl-lst) wrld)))))

(defun tool1-print (print-flg runes clauses state)
  (cond
   (print-flg
    (fms "~%***OUTPUT OF TOOL1***~%~%Tag tree:~%  ~p0~%~%List of simplified ~
          hypotheses:~%  ~p1~|~%"
         (list (cons #\0 runes)
               (cons #\1
                     (untranslate-clause-lst clauses (w state))))
         *standard-co* state nil))
   (t state)))

(defun hide-special-hyps (lst)
  "We do this stuff so that equalities and SYNP hyps won't be thrown out.
   Perhaps what we really need is a hyp simplifier with less aggressive
   heuristics."
  (cond
   ((null lst) nil)
   (t (let ((hyp (car lst)))
        (let ((new-hyp
               (case-match hyp
                 (('equal x y)
                  (let ((x1 (if (variablep x)
                                (list 'hide x)
                              x))
                        (y1 (if (variablep y)
                                (list 'hide y)
                              y)))
                    (list 'equal x1 y1)))
                 (('synp . x) (list 'hide (cons 'synp x)))
                 (& hyp))))
          (cons new-hyp (hide-special-hyps (cdr lst))))))))

(defun fix-special-hyps (lst)
  (cond
   ((null lst) nil)
   (t (let ((hyp (car lst)))
        (let ((new-hyp
               (case-match hyp
                           (('not ('equal ('hide x) ('hide y)))
                            (list 'not (list 'equal x y)))
                           (('not ('equal ('hide x) y))
                            (list 'not (list 'equal x y)))
                           (('not ('equal y ('hide x)))
                            (list 'not (list 'equal y x)))
                           (('not ('hide ('synp . x)))
                            (list 'not (cons 'synp x)))
                           (& hyp))))
          (cons new-hyp (fix-special-hyps (cdr lst))))))))

(defun remove-hidden-terms (cl-set)
  (cond
   ((null cl-set)
    nil)
   (t (cons (fix-special-hyps (butlast (car cl-set) 1))
            (remove-hidden-terms (cdr cl-set))))))

(defun add-key-val-pair-to-key-val-alist (key key1 val alist)
  ;; adapted from ACL2 function add-to-set-equal-in-alist
  (cond ((null alist) (list (list key key1 val)))
        ((equal key (caar alist))
         (cons (list* key key1 val (cdar alist))
               (cdr alist)))
        (t (cons (car alist)
                 (add-key-val-pair-to-key-val-alist key key1 val (cdr
                                                                  alist))))))

(defun remove-hidden-expander-term-from-cl (cl)
  (cond ((endp cl) nil)
        (t (let ((term (car cl)))
             (case-match term
               (('HIDE ('HIDDEN-EXPANDER-FUNCTION &))
                (cdr cl))
               (& (cons (car cl)
                        (remove-hidden-expander-term-from-cl (cdr cl)))))))))

(defun remove-hidden-expander-term-from-cl-list (cl-list)
  (cond ((endp cl-list)
         nil)
        (t (cons (remove-hidden-expander-term-from-cl (car cl-list))
                 (remove-hidden-expander-term-from-cl-list (cdr cl-list))))))

(defun get-assns (ttree remove-hidden)
  (cond (remove-hidden
         (remove-hidden-expander-term-from-cl-list
          (strip-cdrs (tagged-objects :bye ttree))))
        (t
         (strip-cdrs (tagged-objects :bye ttree)))))

(defun tool1-fn1 (hyps ctx ens wrld state hints prove-assumptions inhibit-output
                       translate-flg print-flg)

; Returns error triple with value (list* runes clauses assumptions), where
; assumptions is nil if prove-assumptions is t (because they must be proved) or
; nil (because they are ignored).

  (er-let* ((hints (if (alistp hints)
                       (value (add-key-val-pair-to-key-val-alist
                               "Goal"
                               ;; only preprocess and simplify are allowed
                               :do-not
                               (list 'quote '(generalize
                                              eliminate-destructors
                                              fertilize
                                              eliminate-irrelevance))
                               hints))
                     (er soft ctx
                         "The hints must be an alist, but ~p0 is not."
                         hints)))
            (thints (translate-hints 'tool1 hints ctx wrld state))
            (thyps0
             (if translate-flg
                 (translate-term-lst hyps t t t ctx wrld state)
               (value hyps)))
            (thyps
             (value (hide-special-hyps thyps0)))
            (vars
             (value (all-vars1-lst thyps nil)))
            (tconc
             (translate (list 'hide
                              (list 'hidden-expander-function
                                    (cons 'list vars)))
                        t t t  ctx wrld state))
            (tterm (value (implicate (conjoin thyps) tconc))))
           (sl-let
            (erp ttree clauses pairs new-pspv state)
            (prove-clauses tterm
                           (make-pspv ens wrld state
                                      :displayed-goal
                                      (untranslate tterm t wrld)
                                      :otf-flg t)
                           thints ens wrld ctx state)
            (prog2$
             (chk-for-hidden-expander-function clauses)
             (cond
              (erp
               (mv erp nil state))
              (prove-assumptions
               (er-let* ((thints
                          (if (eq prove-assumptions t)
                              (value thints)
                            (translate-hints 'tool1
                                             *bash-skip-forcing-round-hints*
                                             ctx wrld state))))
                        (state-global-let*
                         ((inhibit-output-lst
                           (if (eq prove-assumptions t)
                               (@ inhibit-output-lst)
                             (if (eq inhibit-output :prove)
                                 (remove1-eq 'prove (@ inhibit-output-lst))
                               (@ inhibit-output-lst)))))
                         (er-let*
                          ((new-ttree
                            (prove-loop1 1 nil pairs new-pspv
                                         thints ens wrld ctx state)))
                          (let ((runes (all-runes-in-ttree
                                        new-ttree
                                        (all-runes-in-ttree ttree nil)))
                                (assumptions (get-assns new-ttree t)))
                            (pprogn
                             (tool1-print print-flg runes clauses state)
                             (value (list* runes
                                           (dumb-negate-lit-lst-lst
                                            (remove-hidden-terms clauses))
                                           assumptions))))))))
              (t (let ((runes (all-runes-in-ttree ttree nil)))
                   (pprogn
                    (tool1-print print-flg runes clauses state)
                    (value (list* runes
                                  (dumb-negate-lit-lst-lst
                                   (remove-hidden-terms clauses))
                                  nil))))))))))

(defun tool1-fn (hyps state hints prove-assumptions inhibit-output
                      translate-flg print-flg)

; Returns error triple with value (list* runes clauses assumptions), where
; assumptions is nil if prove-assumptions is t (because they must be proved) or
; nil (because they are ignored).

  (state-global-let*
   ((ld-skip-proofsp nil)
    (inhibit-output-lst
     (if inhibit-output
         (if (eq inhibit-output :prove)
             (union-eq '(proof-tree prove) (@ inhibit-output-lst))
           *valid-output-names-except-error*)
       (@ inhibit-output-lst))))
   (with-ctx-summarized
    "( TOOL1 ...)"
    (let ((wrld (w state))
          (ens (ens state)))
      (tool1-fn1 hyps ctx ens wrld state hints prove-assumptions inhibit-output
                      translate-flg print-flg)))))

(defun tool1-fn0 (hyps ctx ens wrld state hints prove-assumptions inhibit-output
                       translate-flg print-flg)

; same as tool1-fn, except the user must supply their own wrld, ens, and ctx.

  (state-global-let*
   ((ld-skip-proofsp nil)
    (inhibit-output-lst
     (if inhibit-output
         (if (eq inhibit-output :prove)
             (union-eq '(proof-tree prove) (@ inhibit-output-lst))
           *valid-output-names-except-error*)
       (@ inhibit-output-lst))))
   (tool1-fn1 hyps ctx ens wrld state hints prove-assumptions inhibit-output
              translate-flg print-flg)))

;;;;;;; Tool 2

(defmacro tool2 (term hyps
                      &key hints equiv (prove-assumptions 't) inhibit-output)
  `(tool2-fn ',term ',hyps ',equiv state ',hints ',prove-assumptions
             ',inhibit-output t t))

(defun tool2-print (print-flg runes rewritten-term state)
  (cond
   (print-flg
    (fms "~%***OUTPUT OF TOOL2***~%~%Tag tree:~%  ~p0~%~%Rewritten term:~% ~
          ~p1~|~%"
         (list (cons #\0 runes)
               (cons #\1 (untranslate rewritten-term nil (w state))))
         *standard-co* state nil))
   (t state)))

(defun expander-repeat-limit (state)
  (if (f-boundp-global 'expander-repeat-limit state)
      (f-get-global 'expander-repeat-limit state)
    3))

(defun rewrite* (term hyps ctx
                      repeat-limit
                      completed-iterations
                      ;; alist bkptr
                      ;; &extra formals
                      type-alist
                      ;; obj
                      geneqv wrld state
                      ;; fnstack ancestors backchain-limit
                      step-limit
                      simplify-clause-pot-lst
                      rcnst gstack ttree
                      ;;DARON: added must-rewrite-flg, which is T if we want to
                      ;;throw an error if the term fails to rewrite, and NIL
                      ;;otherwise.
                      must-rewrite-flg)

; Rewrite term repeatedly, (- repeat-limit completed-iterations) times.  Note
; that hyps is T after the first time through.

  (sl-let (val new-ttree)
          (rewrite-entry (rewrite term nil 1)
                         :obj '?
                         :fnstack
; We want to fool rewrite-fncall on lambdas.
                         '(silly-rec-fn-for-rewrite*)
                         :pre-dwp nil  ;; RBK:
                         :ancestors nil
                         :backchain-limit 500
                         :step-limit step-limit ; explicit to avoid decrement
                         :rdepth (rewrite-stack-limit wrld)
                         :pequiv-info nil)
          (cond
           ((equal val term)
            (cond
             ;; DARON: if must-rewrite-flg is NIL, we just return the term.
             ((or (not must-rewrite-flg)
                  (eq hyps t))
              (mv step-limit term ttree state))
             ;; otherwise, we throw the error.
             (t (prepend-step-limit
                 (erp val state)
                 (er soft ctx
                     "The term~%  ~p0~%failed to rewrite to a new term under ~
                      hypotheses~%  ~p1."
                     (untranslate val nil wrld)
                     (untranslate-lst hyps t wrld))))))
           ((= repeat-limit completed-iterations)
            (pprogn
             ;; DARON: wrapped this fms in an io? so we can inhibit it if we
             ;; want.
             (io? prove nil state
                  (completed-iterations)
                  (fms "OUT OF PATIENCE!  Completed ~n0 iterations."
                       (list (cons #\0 (list completed-iterations)))
                       *standard-co* state nil))
             (mv step-limit val new-ttree state)))
           (t (pprogn (if (eql completed-iterations 0)
                          state
                        ;; DARON: wrapped this fms in an io? so we can inhibit
                        ;; output if we want.
                        (io? prove nil state
                             (completed-iterations)
                             (fms "NOTE:  Starting ~n0 repetition of rewrite.~%"
                                  (list (cons #\0 (list (1+ completed-iterations))))
                                  *standard-co* state nil)))
                      (rewrite* val t ctx
                                repeat-limit
                                (1+ completed-iterations)
                                type-alist geneqv wrld state step-limit
                                simplify-clause-pot-lst rcnst gstack
                                new-ttree
                                ;; DARON: we must pass must-rewrite-flg to
                                ;; subsequent iterations.
                                must-rewrite-flg))))))

(defun tool2-fn1
  (term hyps equiv ctx ens wrld state thints prove-assumptions
        inhibit-output translate-flg print-flg must-rewrite-flg)

; Returns error triple with value (list* runes rewritten-term assumptions).
; But assumptions is nil if prove-assumptions is nil (we don't collect them) or
; is t (we insist that all forced assumptions be proved).

  (let* ((saved-pspv (make-pspv ens wrld state
                                :displayed-goal term ; from, e.g., thm-fn
                                :user-supplied-term term ;from, e.g., prove
                                :orig-hints thints))) ;from, e.g., prove
    (er-let*
     ((thyps (if translate-flg
                 (translate-term-lst hyps t t t ctx wrld state)
               (value hyps)))
      (tterm (if translate-flg
                 (translate term t t t ctx wrld state)
               (value term))))
     (mv-let                            ;from waterfall1
      (erp pair state)
      (find-applicable-hint-settings
       *initial-clause-id*
       (add-literal tterm (dumb-negate-lit-lst thyps) t)
       nil saved-pspv ctx
       thints wrld nil state)
      (cond
       (erp (silent-error state))
       (t
        (let ((hint-settings (car pair))
              (thints (cdr pair)))
          (mv-let
           (hint-settings state)
           (cond ((null hint-settings)
                  (mv nil state))
                 (t (thanks-for-the-hint nil hint-settings state))) ;BB
           (er-let* ((pspv (load-hint-settings-into-pspv
                            t hint-settings saved-pspv nil wrld ctx state)))
                    (cond
                     ((intersectp-eq
                       '(:do-not-induct :do-not :induct :use :cases :by)
                       (strip-cars hint-settings))
                      (er soft ctx
                          "It makes no sense for TOOL2 to be given hints ~
                                for \"Goal\" that include any of ~
                                :do-not-induct, :do-not,:induct, :use, ~
                                :cases, or :by.  The hint ~p0 is therefore ~
                                illegal."
                          (cons "Goal" hint-settings)))
                     (t
                      (pprogn
                       (initialize-proof-tree ;from waterfall
                        *initial-clause-id*
                        (list (list (implicate (conjoin thyps) tterm)))
                        ctx
                        state)
                       (let*            ;from simplify-clause1
                           ((current-clause (dumb-negate-lit-lst thyps))
                            (rcnst
                             (change rewrite-constant
                                     (access prove-spec-var pspv :rewrite-constant)
                                     :force-info
                                     (if (ffnnamep-lst 'if current-clause)
                                         'weak
                                       t)))
                            (pts
                             ;; (current-clause-pts (enumerate-elements current-clause 0))
                             nil))
                         (mv-let        ;from simplify-clause1
                          (contradictionp type-alist fc-pair-lst)
                          (forward-chain current-clause
                                         pts
                                         (access rewrite-constant
                                                 rcnst :force-info)
                                         nil wrld ens
                                         (access rewrite-constant rcnst
                                                 :oncep-override)
                                         state)
                          (declare (ignore fc-pair-lst))
                          (cond
                           (contradictionp
                            (er soft ctx
                                "Contradiction found in hypotheses~%  ~
                                      ~p0~%using type-set reasoning!"
                                hyps))
                           (t
                            (sl-let     ;from simplify-clause1
                             (contradictionp simplify-clause-pot-lst)
                             (setup-simplify-clause-pot-lst current-clause
                                                            (pts-to-ttree-lst
                                                             pts)
                                                            nil ; fc-pair-lst  ;; RBK:
                                                            type-alist
                                                            rcnst
                                                            wrld state
                                                            (initial-step-limit
                                                             wrld state))
                             (cond
                              (contradictionp
                               (er soft ctx
                                   "Contradiction found in hypotheses~%  ~
                                    ~p0~%using linear reasoning!"
                                   hyps))
                              (t

; We skip the call of process-equational-polys in simplify-clause1; I think
; that we can assume that by the time tool2 is called, that call wouldn't have
; any effect anyhow.  By the way, we skipped remove-trivial-equivalence
; earlier.

; Now we continue as in rewrite-clause.

                               (mv-let
                                (not-flg atm)
                                (strip-not tterm)
                                (let ((local-rcnst
                                       (change rewrite-constant rcnst
                                               :current-literal
                                               (make current-literal
                                                     :not-flg not-flg
                                                     :atm atm)))
                                      (gstack (initial-gstack 'simplify-clause
                                                              nil current-clause)))
                                  (sl-let
                                   (val ttree state)
                                   (rewrite* atm hyps ctx
                                             (expander-repeat-limit state)
                                             0
                                             type-alist
                                             (cadr (car (last (getprop
                                                               equiv
                                                               'congruences
                                                               nil
                                                               'current-acl2-world
                                                               wrld))))
                                             wrld state step-limit
                                             simplify-clause-pot-lst rcnst gstack
                                             nil
                                             must-rewrite-flg)
                                   (cond
                                    ((equal val t)
                                     (mv t nil state))
                                    (t
                                     (sl-let
                                      (bad-ass ttree)
                                      (resume-suspended-assumption-rewriting
                                       ttree
                                       nil
                                       gstack
                                       simplify-clause-pot-lst
                                       local-rcnst
                                       wrld
                                       state
                                       step-limit)
                                      (cond
                                       (bad-ass
                                        (er soft ctx
                                            "Generated false assumption, ~p0! ~
                                              So, rewriting is aborted, just ~
                                             as it would be in the course of ~
                                             a regular Acl2 proof."
                                            bad-ass))
                                       (t
                                        (let ((rewritten-term
                                               (if not-flg
                                                   (dumb-negate-lit val)
                                                 val)))
                                          (cond
                                           (prove-assumptions
                                            (mv-let
                                             (pairs pspv state)
                                             (process-assumptions
                                              0
                                              (change prove-spec-var saved-pspv
                                                      :tag-tree
                                                      (set-cl-ids-of-assumptions
                                                       ttree *initial-clause-id*))
                                              wrld state)
                                             (er-let*
                                              ((ttree
                                                (accumulate-ttree-and-step-limit-into-state
                                                 (access prove-spec-var pspv :tag-tree)
                                                 step-limit
                                                 state))
                                               (thints
                                                (if (eq prove-assumptions t)
                                                    (value thints)
                                                  (translate-hints 'tool2
                                                                   *bash-skip-forcing-round-hints*
                                                                   ctx wrld state))))
                                              (state-global-let*
                                               ((inhibit-output-lst
                                                 (if (or (eq prove-assumptions t)
                                                         (eq inhibit-output t))
                                                     (@ inhibit-output-lst)
                                                   (if (eq inhibit-output
                                                           :prove)
                                                       (remove1-eq
                                                        'prove
                                                        (@ inhibit-output-lst))
                                                     (@ inhibit-output-lst)))))
                                               (er-let* ((new-ttree
                                                          (prove-loop1
                                                           1 nil pairs pspv
                                                           thints ens wrld
                                                           ctx state)))
                                                 (let* ((runes
                                                         (all-runes-in-ttree
                                                          new-ttree
                                                          (all-runes-in-ttree
                                                           ttree nil)))
                                                        (byes (get-assns
                                                               new-ttree
                                                               nil))
                                                        (val (list* runes
                                                                    rewritten-term
                                                                    byes)))
                                                   (pprogn (tool2-print print-flg runes
                                                                        rewritten-term state)
                                                           (f-put-global 'tool2-error
                                                                         nil state)
                                                           (f-put-global
                                                            'tool2-result
                                                            val
                                                            state)
                                                           (value val))))))))
                                           (t (let* ((runes (all-runes-in-ttree
                                                             ttree nil))
                                                     (val (list* runes
                                                                 rewritten-term
                                                                 nil)))
                                                (pprogn
                                                 (tool2-print print-flg runes
                                                              rewritten-term
                                                              state)
                                                 (f-put-global 'tool2-error
                                                               nil state)
                                                 (f-put-global
                                                  'tool2-result
                                                  val
                                                  state)
                                                 (value val)))))))))))))))))))))))))))))))))

(defun tool2-fn0
  (term hyps equiv ctx ens wrld state hints prove-assumptions
        inhibit-output translate-flg print-flg must-rewrite-flg)

; Same as tool2-fn, except the user must supply the ctx, ens, and wrld.
; DARON: added must-rewrite-flg to formals of tool2-fn0.

  (state-global-let*
   ((inhibit-output-lst
     (if inhibit-output
         (if (eq inhibit-output :prove)
             (union-eq '(proof-tree prove) (@ inhibit-output-lst))
           *valid-output-names-except-error*)
       (@ inhibit-output-lst))))
   (prog2$
    (initialize-brr-stack state)
    (er-let*
     ((thints (translate-hints 'tool2 hints ctx wrld state)))
     (tool2-fn1 term hyps equiv ctx ens wrld state thints prove-assumptions
                inhibit-output translate-flg print-flg must-rewrite-flg)))))

(defun tool2-fn
  (term hyps equiv state hints prove-assumptions inhibit-output translate-flg
        print-flg)

; Returns error triple with value (list* runes rewritten-term assumptions).
; But assumptions is nil if prove-assumptions is nil (we don't collect them) or
; is t (we insist that all forced assumptions be proved).

; DARON: there was a bunch of duplicated code here, so I simplified tool2-fn to
; call tool2-fn0. Note that the signature of tool2-fn is still the same. By
; default it sets the must-rewrite-flg to T, which gives it the same behavior
; as before.

  (let ((ctx 'TOOL2)
        (wrld (w state))
        (ens (ens state)))
    (tool2-fn0 term hyps equiv ctx ens wrld state hints prove-assumptions
               inhibit-output translate-flg print-flg t)))


;;;;;;; Hooking them together

(defun tool2-fn-lst
  (term runes hyps-lst assns equiv state hints prove-assumptions inhibit-output
        print-flg)

; Returns the result of mapping tool2-fn over the list hyps-lst, pairing each
; result with the corresponding member of hyps-lst.  Assumes hyps-lst is
; already translated.  The value returned is actually a list of tuples
; (list* runes hyps rewritten-term assumptions).

  (cond
   ((null hyps-lst)
    (value nil))
   (t
    (mv-let
     (erp x state)
     (tool2-fn term (car hyps-lst) equiv state hints prove-assumptions
               inhibit-output nil print-flg)
     (cond
      (erp
       (tool2-fn-lst term runes (cdr hyps-lst) assns equiv state
                     hints prove-assumptions inhibit-output print-flg))
      (t
       (er-let*
        ((rst (tool2-fn-lst term runes (cdr hyps-lst) assns equiv
                            state
                            hints prove-assumptions inhibit-output print-flg)))
        (value (cons (list* (union-equal runes (car x))
                            (car hyps-lst)
                            (cadr x)
                            (union-equal assns (cddr x)))
                     rst)))))))))

(defun simplify-hyps
  (remaining-hyps rewritten-previous-hyps-rev runes assns equiv state hints
                  prove-assumptions inhibit-output print-flg)

; Returns the result of mapping tool2-fn over each hyp in remaining-hyps, where
; the hyps in rewritten-previous-hyps-rev and (cdr remaining-hyps) are assumed.
; Assumes all hyps are already translated.  The value returned is actually a
; list (list* runes (list rewritten-hyp-list) assumptions).

  (cond
   ((null remaining-hyps)
    (value (list* runes (list (reverse rewritten-previous-hyps-rev)) assns)))
   (t (er-let*
       ((x (tool2-fn (car remaining-hyps)
                     (revappend rewritten-previous-hyps-rev
                                (cdr remaining-hyps))
                     equiv state hints prove-assumptions
                     inhibit-output nil print-flg)))
       (simplify-hyps (cdr remaining-hyps)
                      (cons (cadr x) rewritten-previous-hyps-rev)
                      (union-equal (car x) runes)
                      (union-equal (cddr x) assns)
                      equiv state hints prove-assumptions inhibit-output
                      print-flg)))))

(defun tool-fn
  (term hyps simplify-hyps-p equiv state hints prove-assumptions inhibit-output
        print-flg ctx)

; Term and hyps are in translated form.  Returns a list of tuples
; (list* runes hyps rewritten-term assumptions).

  (er-let* ((runes-hyps-assns
             (cond
              ((eq simplify-hyps-p :no-split)
               (simplify-hyps hyps nil nil nil equiv state hints
                              prove-assumptions inhibit-output print-flg))
              ((eq simplify-hyps-p t)
               (tool1-fn hyps state hints prove-assumptions inhibit-output
                         nil print-flg))
              (simplify-hyps-p
                (value (er hard 'tool-fn
                           "Bad :simplify-hyps-p argument (should be ~v0): ~x1"
                           (list t nil :no-split)
                           simplify-hyps-p)))
              (t (value (list* nil (list hyps) nil))))))
           (cond
            ((null (cdr runes-hyps-assns))
             (er soft ctx
                 "It does not make sense to simplify the term ~p0, because the ~
                  hypothesis list ~p1 is contradictory."
                 (untranslate term nil (w state))
                 (untranslate-lst hyps t (w state))))
            (t
             (pprogn
              (cond (print-flg
                     (fms "***NOTE***:  Starting TOOL2.~%" nil *standard-co* state nil))
                    (t state))
              (er-let*
               ((x (tool2-fn-lst term
                                 (car runes-hyps-assns)
                                 (cadr runes-hyps-assns)
                                 (cddr runes-hyps-assns)
                                 equiv state hints prove-assumptions
                                 inhibit-output print-flg)))
               (cond
                ((not (= (length x) (length (cadr runes-hyps-assns))))
                 (er soft ctx
                     "Unable to successfully simplify term~%  ~p0~%and ~
                      hypotheses~%  ~p1 in every case generated."
                     (untranslate term nil (w state))
                     (untranslate-lst hyps t (w state))))
                (x (value x))
                (t (er soft ctx
                       "No theorems were suggested for term~%  ~p0~%and ~
                        hypotheses~%  ~p1.")))))))))

(defxdoc defthm?
  :parents (expander)
  :short "Generate a theorem."
  :long "<p>Example:</p>

@({
  (defthm? app-simplify
    (implies (true-listp x)
             (equal (append x y)
                    ?))
    :hints ((\"Goal\" :expand ((true-listp x)
                             (true-listp (cdr x))
                             (append x y))))
    ; show some output
    :print-flg t)
})

<p>General Forms:</p>

@({
  (DEFTHM? name
    (IMPLIES hyps (equiv term ?))
    :hints             hints
    :prove-assumptions prove-flg ; t or nil, default t
    :print-flg         print-flg ; t or nil, default nil
    :simplify-hyps-p   flg       ; t, nil, or :no-split; default t
  )

  (DEFTHM? name
    (equiv term ?)
    :hints             hints
    :prove-assumptions prove-flg ; t or nil, default t
    :print-flg         print-flg ; t or nil, default nil
    :simplify-hyps-p   flg       ; t, nil, or :no-split; default t
  )
})

<p>where @('name') is a new symbolic name (see @(see name)), @('term') is a
term to be simplified assuming @('hyps') is true, and @(see hints) is as
described in its @(see documentation).  The four keyword arguments above are
all optional, and behave as you might expect.  In particular, set
@(':simplify-hyps-p') to @('nil') if you do not want the @('hyps') to be
simplified; otherwise, case splitting may occur in the course of their
simplification.</p>

<p>If the given @('term') cannot be simplified, then the event fails.
Otherwise, the result is an @(see encapsulate) event with one or more @(see
defthm) events of the form of the theorem, except with @('hyps')
simplified (and even omitted if simplified to @('t')) and @('term') simplified
under the assumption that @('hyps') is true.  The reason that there can be more
than one @(see defthm) event is that @('hyps') may simplify to an expression
that generates a case split, for example if it simplifies to an @(see if)
expression that does not represent a conjunction.</p>

<p>In general, simplification may generate assumptions because of @(see force).
By default, an attempt is made to prove these assumptions, which must succeed
or else this event fails.  However, if @(':prove-assumptions') is @('nil'),
then roughly speaking, no proof of forced hypotheses is attempted until after
simplification is complete.  The documentation of :prove-assumptions is
admittedly weak here; feel free to experiment.</p>

<p>Also see @(see symsim).</p>

<p>Here are some examples, including the one above.  Try them out and see what
happens.</p>

  @({

  ; Doesn't simplify, so fails:
  (defthm? app-simplify
    (implies (true-listp x)
             (equal (append x y)
                    ?))
    :hints ((\"Goal\" :expand (true-listp x))))

  :pbt 0

  ; The following creates one event, but maybe we'd prefer cases to be
  ; broken out into separate events.  That comes next.
  (defthm? app-simplify
    (implies (true-listp x)
             (equal (append x y)
                    ?))
    :hints ((\"Goal\" :expand (append x y))))

  :pbt 0
  :pe :here
  :pe APP-SIMPLIFY
  :u

  (defthm? app-simplify
    (implies (true-listp x)
             (equal (append x y)
                    ?))
    :hints ((\"Goal\" :expand ((true-listp x)
                             (true-listp (cdr x))
                             (append x y))))
    ; show some extra output; this is optional
    :print-flg t)

  :pe :here
  :u
  })")

(defmacro defthm?
  (name term &key hints (prove-assumptions 't) (simplify-hyps-p 't) print-flg)
  (let* ((form0
          `(defthm?-fn ',name ',term ',simplify-hyps-p ',hints
             ',prove-assumptions ',print-flg (w state) state))
         (form `(er-let* ((val ,form0))
                         (pprogn (f-put-global 'defthm?-result val state)
                                 (value :invisible)))))

    `(state-global-let*
      ((defthm?-result nil))
      (er-progn (ld '(,form)
                    :ld-pre-eval-print nil
                    :ld-prompt nil)
                (value (f-get-global 'defthm?-result state))))))

; This is new in 8/97.  If we don't include executable counterparts of some
; functions, one of the examples in the documentation fails to simplify.
; Try the following.  If you define *adjust-hints-exec-theory* to be nil
; instead, the defthm? will still fail, but it will get more stuck in the
; final proof attempt than it should.
#|
(defthm true-listp-expand-append
  (implies (and (force (true-listp x))
                x)
           (equal (append x y)
                  (cons (car x) (append (cdr x) y)))))
(defthm? foo (implies (consp x) (equal (append X Y) ?))
  :prove-assumptions nil)
|#
(defconst *adjust-hints-exec-theory*
  '(definition-runes
     (union-eq '(iff) *expandable-boot-strap-non-rec-fns*)
     t
     world))

(defun adjust-hints-with-runes1 (hint runes)

; hint is an alternating list of keywords and hints, e.g.,
; (:expand (foo x) :in-theory *s-prop-theory*)

  (cond
   ((null hint)
    (list :in-theory
          (list 'union-theories
                *adjust-hints-exec-theory*
                (list 'quote runes))))
   ((eq (car hint) :in-theory)
    (list* :in-theory
           (list 'union-theories
                 *adjust-hints-exec-theory*
                 `(intersection-theories ',runes ,(cadr hint)))
           (cddr hint)))
   (t
    (list* (car hint)
           (cadr hint)
           (adjust-hints-with-runes1 (cddr hint) runes)))))

(defun adjust-hints-with-runes (hints runes top-goal-seen-p)

; We know that only runes were used in the proof, and we want to adjust hints
; correspondingly.

  (cond
   ((null hints)
    (if top-goal-seen-p
        nil
      `(("Goal" :in-theory (union-theories
                            ,*adjust-hints-exec-theory*
                            ',runes)))))
   (t (cons (cons (caar hints) (adjust-hints-with-runes1 (cdar hints) runes))
            (adjust-hints-with-runes (cdr hints) runes
                                     (or top-goal-seen-p
                                         (equal (caar hints) "Goal")))))))

(defconst *fake-runes*
  (list *fake-rune-for-anonymous-enabled-rule*
        *fake-rune-for-type-set*
        *fake-rune-for-linear*))

(defun defthm-?-fn-forms1-lst (name index x equiv lhs hints wrld)

; x is from the output of tool-fn:  a list of elements of the form
; (list* runes hyps rewritten-term assumptions)
; If there is only one lemma, it has the name <name>, else we create
; <name>$0, ... <name>$n etc.

  (cond
   ((null x)
    nil)
   (t (let ((runes (set-difference-equal (car (car x))
                                         *fake-runes*))
            (hyps (cadr (car x)))
            (rhs (caddr (car x)))
            (assumptions (cdddr (car x))))
        (cons `(defthm
                 ,(if (and (zerop index) (null (cdr x)))
                      name
                    (packn (list name '$ index)))
                 ,(untranslate (implicate (conjoin (append assumptions hyps))
                                          (fcons-term* equiv lhs rhs))
                               t wrld)
                 :hints ,(adjust-hints-with-runes hints runes nil))
              (defthm-?-fn-forms1-lst name (1+ index) (cdr x) equiv lhs hints wrld))))))

(defun defthm?-fn-forms
  (name form simplify-hyps-p hints prove-assumptions inhibit-output print-flg wrld state)
  (with-ctx-summarized
   (cons 'defthm? name)
   (er-let*
    ((tform (translate form t t t ctx wrld state)))
    (let* ((x (unprettyify tform))
           (hyps (car (car x)))
           (concl (cdr (car x))))
      (cond
       ((and (null (cdr x))
             (not (variablep concl))
             (not (fquotep concl))
             (variablep (fargn concl 2)))
        (cond
         ((equivalence-relationp (ffn-symb concl) wrld)
          (er-let*
           ((x (tool-fn (fargn concl 1) hyps simplify-hyps-p (ffn-symb concl)
                        state hints prove-assumptions inhibit-output print-flg
                        ctx)))
           (value (defthm-?-fn-forms1-lst name 0 x (ffn-symb concl)
                    (fargn concl 1) hints wrld))))
         (t (er soft ctx
                "The form supplied to DEFTHM? must be of the form ~p0 or ~p1, ~
                 where equiv is an equivalence relation.  However, ~p2 is not ~
                 an equivalence relation in the current world."
                '(implies hyps (equiv lhs var))
                '(equiv lhs var)
                (ffn-symb concl)))))
       (t (er soft ctx
              "The form supplied to DEFTHM? must be of the form ~p0 or ~p1,~
               where var is a variable.  But ~p2 is not of this form."
              '(implies hyps (equiv lhs var))
              '(equiv lhs var)
              form)))))))

(defun defthm?-fn
  (name term simplify-hyps-p hints prove-assumptions print-flg wrld state)
  (state-global-let*
   ((inhibit-output-lst
     (if (boundp-global 'defthm?-inhibit-output-lst state)
; Suggestion:  '(warning observation prove event summary proof-tree)
         (f-get-global 'defthm?-inhibit-output-lst state)
       (@ inhibit-output-lst))))
   (er-let* ((forms (defthm?-fn-forms name term simplify-hyps-p hints
                      prove-assumptions nil print-flg wrld state)))
            (er-progn (encapsulate-fn nil (cons '(logic) forms) state nil)
                      (value (list* 'encapsulate () forms))))))

(defxdoc symsim
  :parents (expander)
  :short "Simplify given term and hypotheses."
  :long "<p>Example:</p>

@({
  (symsim (append x y)
          ((not (atom x)) (not (cdr x)))
          :hints ((\"Goal\" :expand
                   ((true-listp x)
                    (true-listp (cdr x))
                    (append x y)))))
})

<p>yields</p>

@({
  Simplified term:
    (CONS (CAR X) Y)
  Simplified hyps:
   ((CONSP X) (NOT (CDR X)))~/

  General Form:
  (symsim term hyps
          :hints             hints
          :inhibit-output    inhibit-flg ; t, :prove, or nil, default t
          :prove-assumptions prove-flg   ; t, nil, or (default) any other value
          :print-flg         print-flg   ; t or nil, default nil
          :simplify-hyps-p   flg         ; t, nil, or :no-split; default t
  )
})

<p>where @('term') is a term to be simplified assuming that each @('hyp') in
the list @('hyps') is true, and @(see hints) is as described in its @(see
documentation).  The keyword arguments above are all optional, and behave as
you might expect.  In particular, set @(':simplify-hyps-p') to @('nil') if you
do not want the @('hyps') to be simplified; otherwise, case splitting may occur
in the course of their simplification.</p>

<p>Prover output is inhibited if @(':inhibit-output') is @('t') (the default).
Only proof output is inhibited if @(':inhibit-output') is @(':prover') (so for
example, summaries and warnings are printed), and all prover output is shown if
@(':inhibit-output') is @('nil').</p>

<p>Also see @(see defthm?), which has a related functionality and is a bit more
thoroughly documented.  Here are some examples that should help give an idea of
how @('symsim') works.  (The name, by the way, is short for \"symbolically
simulate\".)  Try these, as well as the examples shown above.</p>

  @({

  (symsim (append x y)
          nil
          :hints ((\"Goal\" :expand
                   ((true-listp x)
                    (append x y)
                    (append (cdr x) y)))))

  ; Generates three cases:
  (symsim (append x y)
          ((true-listp x))
          :hints ((\"Goal\" :expand
                   ((true-listp x)
                    (true-listp (cdr x))
                    (append x y)
                    (append (cdr x) y)))))

  ; Let's illustrate the role of FORCE.  The following rule
  ; forces append to open up, and comes into play below.
  (defthm true-listp-expand-append
    (implies (and (force (true-listp x))
                  x)
             (equal (append x y)
                    (cons (car x) (append (cdr x) y)))))

  ; Generates assumption forced by preceding rule.
  (symsim (append x y)
          ((not (atom x))))

  ; But now we fail; but why?  See next form.
  (symsim (append x y)
          ((consp x))
          :prove-assumptions t)

  ; Let's not inhibit output.  Then we can see the failed forcing round.
  (symsim (append x y)
          ((consp x))
          :prove-assumptions t
          :inhibit-output nil)

  ; As above, but doesn't deal with generated forced assumptions at all (just
  ; drops them on the floor).
  (symsim (append x y)
          ((consp x))
          :prove-assumptions nil)
  })")

(defmacro symsim
  (term hyps &key
        hints (prove-assumptions 'try) (inhibit-output 't) (simplify-hyps-p 't)
        print-flg)
  `(symsim-fn ',term ',hyps ',simplify-hyps-p ',hints ',prove-assumptions
              ',inhibit-output ',print-flg (w state) state))

(defun symsim-fn-print-lst (tuples n total wrld state)
  (cond ((null tuples)
         (fms "========================================~%~%"
              (list (cons #\0 n))
              *standard-co* state nil))
        (t
         (let ((tuple (car tuples)))
           (pprogn
            (fms "========== Generated case #~x0 of ~x1 ==========~%"
                 (list (cons #\0 n)
                       (cons #\1 total))
                 *standard-co* state nil)
            (fms "Runes:~%  ~p0~%Simplified hyps:~% ~p1~%Simplified term:~%  ~p2~%Simplified ~
                  assumptions:~% ~p3~%"
                 (list (cons #\0 (car tuple))
                       (cons #\1 (untranslate-lst (cadr tuple) t wrld))
                       (cons #\2 (untranslate (caddr tuple) nil wrld))
                       (cons #\3 (prettyify-clause-lst
                                  (cdddr tuple)
                                  (let*-abstractionp state)
                                  wrld)))
                 *standard-co* state nil)
            (symsim-fn-print-lst (cdr tuples) (1+ n) total wrld state))))))

(defun symsim-fn (term hyps simplify-hyps-p hints prove-assumptions
                       inhibit-output print-flg wrld state)

; Returns a list of tuples of the form (list* runes hyps rewritten-term
; assumptions), after doing some appropriate printing.

  (er-let*
   ((tterm (translate term t t t 'top-level wrld state))
    (thyps (translate-term-lst hyps t t t 'top-level wrld state))
    (tuples-lst (tool-fn tterm thyps simplify-hyps-p 'equal state
                         hints prove-assumptions
                         inhibit-output
                         print-flg (cons 'symsim-fn term))))
   (pprogn (if print-flg
               (symsim-fn-print-lst tuples-lst 1 (length tuples-lst) wrld
                                    state)
             state)
           (value tuples-lst))))

; DARON: added the new function to streamline calls to normalize:

(defun normalize-no-ttree (term iff-flg type-alist ens wrld)
  (mv-let (x ttree)
          (normalize term iff-flg type-alist ens wrld nil)
          (declare (ignore ttree))
          x))


; PETE: new functions for ccg analysis.
; DARON: altered functions below to take ctx, ens, and wrld.

(defun simp-hyps-aux
  (hyps-remaining hyps-init hyps-res ctx ens wrld state hints
                  inhibit-output print-flg simp-flg)
  (cond
   ((null hyps-remaining)
    (value (reverse hyps-res)))
   (t (let* ((hyp0 (car hyps-remaining))
             (hyp (normalize-no-ttree hyp0 t nil ens wrld))
             (other-hyps (remove1-equal hyp0 hyps-init)))
        ;; DARON: changed this er-let* to an mv-let so we can catch any
        ;; errors. If there are errors, we simply use the original term.
        (mv-let
         (erp x state)
         (tool2-fn0 hyp
                    other-hyps
                    'iff ctx ens wrld state hints nil
                    inhibit-output nil print-flg nil)
         (let* ((res (if erp
                         hyp
                       (normalize-no-ttree (cadr x) t nil ens wrld)))
                (simplified-to-t? (equal res ''t))
                (simplified-to-nil? (equal res ''nil))
                (simplified? (term-order res hyp))
                (always-simp? (and (not (equal simp-flg :t))
                                   (not (equal simp-flg :term-order))))
                (nhyps-init
                 (cond (simplified-to-t?
                        other-hyps)
                       ((or always-simp?
                            (and simplified? (not (equal simp-flg :t))))
                        (append (flatten-ands-in-lit res)
                                other-hyps))
                       (t (append (flatten-ands-in-lit hyp)
                                  other-hyps))))
                (nhyps-res
                 (cond (simplified-to-t? hyps-res)
                       ((or always-simp?
                            (and simplified? (not (equal simp-flg :t))))
                        (append (flatten-ands-in-lit res)
                                hyps-res))
                       (t
                        (append (flatten-ands-in-lit hyp)
                                hyps-res)))))
           (if simplified-to-nil?
               (value nil)
             (simp-hyps-aux (cdr hyps-remaining)
                            nhyps-init
                            nhyps-res
                            ctx ens wrld state hints
                            inhibit-output print-flg simp-flg))))))))

; DARON: changed simp-hyps to simp-hyps0, requiring ctx, ens, and wrld from the
; user, and then wrote a new simp-hyps which simply calls simp-hyps0 with these
; values provided.

(defun simp-hyps0 (hyps ctx ens wrld state hints inhibit-output print-flg simp-flg)
  "See the documentation for simp-hyps. This function has the same
   functionality, but requires the user to provide the ctx, ens, and wrld."
  (let ((nd-hyps (remove-duplicates hyps)))
    (er-let*
     ((t-nd-hyps
       (simp-hyps-aux nd-hyps nd-hyps nil ctx ens wrld state hints
                      inhibit-output print-flg :t)))
     (if (equal simp-flg :t)
         (value t-nd-hyps)
       (simp-hyps-aux
        t-nd-hyps t-nd-hyps nil ctx ens wrld state hints
        inhibit-output print-flg simp-flg)))))

(defun simp-hyps (hyps state hints inhibit-output print-flg simp-flg)
  "Given a list of terms (hyps), return a list that is a subset
  of hyps. The conjunction of hyps should be equal to the
  conjuction of the returned list. If simp-flg is :t, all we do
  is to remove elements of hyps that can be proven to simplify to
  t, assuming the rest of the elements in hyps hold. If simp-flg
  is :term-order, then we replace elements of hyps with what they
  simplify to (again, assuming the rest of the elements in hyps
  hold) if we wind up with a smaller term (as determined by the
  function term-order). Otherwise, we replace elements of hyps
  with whatever they simplify to (again, assuming the rest of the
  elements in hyps hold). Some care is taken to deal with
  duplicates, and the like. For example, we always try with
  simp-flg set to :t first since this tends to return results
  that depend less on the order of arguments. To see this, note
  that if you give ((natp x) (integerp x)) as input, you would get
  different results when you change the order of the hyps (if you
  didn't try :t first). "
  (simp-hyps0 hyps 'SIMP-HYPS (ens state) (w state)
              state hints inhibit-output print-flg simp-flg))

#|
Testing code


(simp-hyps '((natp x) (natp x)) state nil t nil :t)
(simp-hyps '((natp x) (natp x)) state nil t nil :term-order)
(simp-hyps '((natp x) (natp x)) state nil t nil nil)

(simp-hyps '((natp x) (integerp x)) state nil t nil :t)
(simp-hyps '((natp x) (integerp x)) state nil t nil :term-order)
(simp-hyps '((natp x) (integerp x)) state nil t nil nil)

(simp-hyps '((integerp x) (natp x) (integerp x) (natp x)) state nil t nil :t)
(simp-hyps '((integerp x) (natp x) (integerp x) (natp x)) state nil t nil :term-order)
(simp-hyps '((integerp x) (natp x) (integerp x) (natp x)) state nil t nil nil)

(simp-hyps '((not (stringp x)) (integerp x) (natp x) (posp x)) state nil t nil :t)
(simp-hyps '((not (stringp x)) (integerp x) (natp x) (posp x)) state nil t nil :term-order)
(simp-hyps '((not (stringp x)) (integerp x) (natp x) (posp x)) state nil t nil nil)

(simp-hyps '((natp x) (integerp x) (< x 1)) state nil t nil :t)
(simp-hyps '((natp x) (integerp x) (< x 1)) state nil t nil :term-order)
(simp-hyps '((natp x) (integerp x) (< x 1)) state nil t nil nil)

(simp-hyps '((natp x) (integerp x) (< x 1)) state nil t nil :t)
(simp-hyps '((natp x) (integerp x) (< x 1)) state nil t nil :term-order)
(simp-hyps '((integerp x) (natp x) (< x 1)) state nil t nil nil)

(simp-hyps '((natp x) (stringp x)) state nil t nil :t)
(simp-hyps '((natp x) (stringp x)) state nil t nil :term-order)
(simp-hyps '((natp x) (stringp x)) state nil t nil nil)

|#

#|
For possible future work.

Consider

(simp-hyps '((natp x) (< x 1)) state nil t nil nil)

This doesn't lead to simplifications, but we can figure out that
x=0. Maybe we should think about how to do this and do it.


|#
