[User]
Generate a defmacro form that transforms code like this:
(macroexpand-convention (form) (if (consp form) (expand-export-form-using-head (first form) form) form))

Pattern to recognize: Macro call that should be transformed by macroexpand-convention

(macroexpand-convention (form) (if (consp form) (expand-export-form-using-head (first form) form) form))

[Assistant]
(defmacro macroexpand-convention ((original-form) &body body)
  "Executes BODY as like `progn' and return the result as the first
value.  As the second value, returns a boolean whether the result is
not same with ORIGINAL-FORM or not.
This macro is designed to follow the `macroexpand' convention."
  `(multiple-value-bind (result expanded-p)
       (progn ,@body)
     (values result
             (or expanded-p
                 (not (eq result ,original-form))))))

;; macroexpand:
(multiple-value-bind (result expanded-p) (progn (if (consp form) (expand-export-form-using-head (first form) form) form)) (values result (or expanded-p (not (eq result form)))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(in-package nil)

What needs to change: Macro call that should be transformed by IN-PACKAGE

(in-package nil)

[Assistant]
(defmacro IN-PACKAGE ...)

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (setq *package*
          (sb-int:find-undeleted-package-or-lose #A((3) base-char . "NIL"))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(sif (list 1 2 3) (sif (car it) (setf it 'a) :foo))

What needs to change: Macro call that should be transformed by sif

(sif (list 1 2 3) (sif (car it) (setf it 'a) :foo))

[Assistant]
(defmacro sif (test then &optional else)
  "Like IF, except binds the test form to IT (via SYMBOL-MACROLET) for
the scope of the then and else expressions. IT can be set with SETF"
  `(symbolic if ,test ,then ,else))

;; macroexpand:
(symbolic if (list 1 2 3) (sif (car it) (setf it (quote a)) :foo) nil)


[User]
You are a Common Lisp macro expert. Given this code pattern:
(when (eql (info-size) 0) (format stream "~&"))

Write a macro that addresses: Macro call that should be transformed by when

(when (eql (info-size) 0) (format stream "~&"))

[Assistant]
(defmacro when (test &body forms)
  `(if ,test
	   ,(cl:if (cadr forms)
			   `(progn ,@forms)
			   (car forms))))

;; macroexpand:
(if (eql (info-size) 0) (format stream "~&"))


[User]
Write a Common Lisp macro to handle this code pattern:
(doseq (item seq) (accumulate collector item))

Problem: Macro call that should be transformed by doseq

(doseq (item seq) (accumulate collector item))

[Assistant]
(defmacro doseq (name/seq &body body)
  "Iterate over the elements of a single sequence SEQUENCE.

   Same as DO-SEQUENCES but for the special case of iterating over a
   single sequence.

   The macro arguments can be in one of the following two forms:

    1. (NAME (ELEMENT SEQUENCE &REST ARGS) &BODY BODY)

    2. ((ELEMENT SEQUENCE &REST ARGS) &BODY BODY)

   NAME is the block name, NIL if not given.

   ELEMENT is the variable to which each element of the sequence is
   bound.

   SEQUENCE is the sequence, with ARGS being the remaining arguments
   passed to the ITERATOR function.

   BODY is the list of forms evaluated on each iteration."

  (let-if ((name name/seq)
           (seq (first body) name/seq)
           (body (rest body) body))
      (symbolp name/seq)

    (destructuring-bind (element sequence &rest args) seq
      `(do-sequences ,name
         ((,element ,sequence ,@args))
         ,@body))))

;; macroexpand:
(do-sequences nil ((item seq)) (accumulate collector item))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(do-files (file (find-theme theme) "tmpl") (compile-template :common-lisp-backend file))

Write a macro that addresses: Macro call that should be transformed by do-files

(do-files (file (find-theme theme) "tmpl") (compile-template :common-lisp-backend file))

[Assistant]
(defmacro do-files ((var path &optional extension) &body body)
  "For each file under PATH, run BODY. If EXTENSION is provided, only run
BODY on files that match the given extension."
  (alexandria:with-gensyms (extension-p)
    `(flet ((,extension-p (file)
              (string= (pathname-type file) ,extension)))
       (cl-fad:walk-directory ,path (lambda (,var) ,@body)
                              :follow-symlinks nil
                              :test (if ,extension
                                        #',extension-p
                                        (constantly t))))))

;; macroexpand:
(flet ((#:extension-p288 (file) (string= (pathname-type file) "tmpl"))) (cl-fad:walk-directory (find-theme theme) (lambda (file) (compile-template :common-lisp-backend file)) :follow-symlinks nil :test (if "tmpl" (function #:extension-p288) (constantly t))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-shared-method nil
    (progn))

What needs to change: Macro call that should be transformed by DEFINE-SHARED-METHOD

(define-shared-method nil
    (progn))

[Assistant]
(defmacro DEFINE-SHARED-METHOD ...)

;; macroexpand:
(define-incongruent-method incongruent-methods.methods::nil
    (progn))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(with-html-string (:div (:section (:h2 (:p "hello")))))

What needs to change: Macro call that should be transformed by with-html

(with-html-string (:div (:section (:h2 (:p "hello")))))

[Assistant]
(defmacro with-html (&body body &environment env)
  "Interpret BODY as HTML. Consult README.txt for the syntax."
  `(let ((*html* (ensure-html-stream *html*)))
     ,(if (and (null (cdr body)) (atom (car body)))
          (car body)
          `(progn ,@(parse-html body env)))))

;; macroexpand:
(with-output-to-string (*html*) (with-html (:div (:section (:h2 (:p "hello"))))))


[User]
Write a Common Lisp macro to handle this code pattern:
(action (:after node-variable) #'propagate-constants-node-variable)

Problem: Macro call that should be transformed by action

(action (:after node-variable) #'propagate-constants-node-variable)

[Assistant]
(defmacro action ((when type &rest args) &body body)
  "Construct an action block, turning `body` into a lambda function
accepting `args` if `args` are provided. If there are no `args`, then
`body` is assumed to be a function object and is used directly with
`when` and `type` to create an `action` instance. Otherwise, the first
argument in `args` is declared to be a node of type `type`, and the
`args` and `body` are used to generate a lambda function."
  (check-type when keyword)
  (check-type type symbol)
  (assert (subtypep type 'node))
  (assert (or (not (endp args)) (= 1 (length body))))
  (if (endp args)
      `(make-action ',when ',type ,@body)
      `(make-action ',when ',type
                    (lambda (,@args)
                      (declare (type ,type ,(first args)))
                      ,@body))))

;; macroexpand:
(make-action (quote :after) (quote node-variable) (function propagate-constants-node-variable))


[User]
Define a macro that eliminates this repetitive pattern:
(unwind-protect-case (aborted-p) (random 42) (:always (setq result aborted-p)))

Issue: Macro call that should be transformed by unwind-protect-case

(unwind-protect-case (aborted-p) (random 42) (:always (setq result aborted-p)))

[Assistant]
(defmacro unwind-protect-case ((&optional abort-flag) protected-form &body clauses)
  "Like CL:UNWIND-PROTECT, but you can specify the circumstances that
the cleanup CLAUSES are run.

  clauses ::= (:NORMAL form*)* | (:ABORT form*)* | (:ALWAYS form*)*

Clauses can be given in any order, and more than one clause can be
given for each circumstance. The clauses whose denoted circumstance
occured, are executed in the order the clauses appear.

ABORT-FLAG is the name of a variable that will be bound to T in
CLAUSES if the PROTECTED-FORM aborted preemptively, and to NIL
otherwise.

Examples:

  (unwind-protect-case ()
       (protected-form)
     (:normal (format t \"This is only evaluated if PROTECTED-FORM executed normally.~%\"))
     (:abort  (format t \"This is only evaluated if PROTECTED-FORM aborted preemptively.~%\"))
     (:always (format t \"This is evaluated in either case.~%\")))

  (unwind-protect-case (aborted-p)
       (protected-form)
     (:always (perform-cleanup-if aborted-p)))
"
  (check-type abort-flag (or null symbol))
  (let ((gflag (gensym "FLAG+")))
    `(let ((,gflag t))
       (unwind-protect (multiple-value-prog1 ,protected-form (setf ,gflag nil))
	 (let ,(and abort-flag `((,abort-flag ,gflag)))
	   ,@(loop for (cleanup-kind . forms) in clauses
		   collect (ecase cleanup-kind
			     (:normal `(when (not ,gflag) ,@forms))
			     (:abort  `(when ,gflag ,@forms))
			     (:always `(progn ,@forms)))))))))

;; macroexpand:
(let ((#:flag+127 t)) (unwind-protect (multiple-value-prog1 (random 42) (setf #:flag+127 nil)) (let ((aborted-p #:flag+127)) (progn (setq result aborted-p)))))


[User]
Write a Common Lisp macro to handle this code pattern:
(make-name-transformer nil nil)

Problem: Macro call that should be transformed by MAKE-NAME-TRANSFORMER

(make-name-transformer nil nil)

[Assistant]
(defmacro MAKE-NAME-TRANSFORMER ...)

;; macroexpand:
(lambda (name definition)
  (declare (ignorable definition))
  (concatenate-symbol nil nil))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-simple-definition-resolver constant designator-constant-p)

What needs to change: Macro call that should be transformed by define-simple-definition-resolver

(define-simple-definition-resolver constant designator-constant-p)

[Assistant]
(defmacro define-simple-definition-resolver (class lookup-function &body body)
  (let ((package (gensym "PACKAGE")))
    `(define-definition-resolver ,class (,class ,package)
       (when (ignore-errors ,(if body
                                 `(let ((,(first lookup-function) ,class))
                                    ,@body)
                                 `(,lookup-function ,class)))
         (list (make-instance ',class :designator ,class :package ,package))))))

;; macroexpand:
(define-definition-resolver constant (constant #:package140) (when (ignore-errors (designator-constant-p constant)) (list (make-instance (quote constant) :designator constant :package #:package140))))


[User]
Write a Common Lisp macro to handle this code pattern:
(with-timeout (time-limit test) (loop for test in (tests test) do (funcall test)))

Problem: Macro call that should be transformed by with-timeout

(with-timeout (time-limit test) (loop for test in (tests test) do (funcall test)))

[Assistant]
(defmacro with-timeout (timeout &body body)
  #+(and clisp mt)
  `(mt:with-timeout (,timeout (error 'timeout))
     ,@body)
  #+(or allegro cmucl)
  `(mp:with-timeout (,timeout (error 'timeout))
     ,@body)
  #+sbcl
  `(sb-ext:with-timeout ,timeout
     ,@body)
  #-(or allegro (and clisp mt) cmucl sbcl)
  `(progn
     ,@body))

;; macroexpand:
(sb-ext:with-timeout (time-limit test) (loop for test in (tests test) do (funcall test)))


[User]
Define a macro that eliminates this repetitive pattern:
(ps-html nil :key nil)

Issue: Macro call that should be transformed by PS-HTML

(ps-html nil :key nil)

[Assistant]
(defmacro PS-HTML ...)

;; macroexpand:
(stringify nil #A((11) base-char . "<key></key>") nil)


[User]
You are a Common Lisp macro expert. Given this code pattern:
(nlet nil
    (progn))

Write a macro that addresses: Macro call that should be transformed by NLET

(nlet nil
    (progn))

[Assistant]
(defmacro NLET ...)

;; macroexpand:
(let* ((progn nil)))


[User]
Generate a defmacro form that transforms code like this:
(define-accumulation-binding counting ((var 0) form) (declare (type (integer 0) var)) `(when ,form (incf ,var)))

Pattern to recognize: Macro call that should be transformed by define-accumulation-binding

(define-accumulation-binding counting ((var 0) form) (declare (type (integer 0) var)) `(when ,form (incf ,var)))

[Assistant]
(defmacro define-accumulation-binding (name (var &rest args) &body body)
  `(define-form-binding ,name (,var ,@args)
     ,@(form-fiddle:lambda-declarations `(lambda () ,@body))
     (values
      (progn ,@(form-fiddle:lambda-forms `(lambda () ,@body)))
      (delist var))))

;; macroexpand:
(define-form-binding counting ((var 0) form) (declare (type (integer 0) var)) (values (progn (sb-int:quasiquote (when #S(sb-impl::comma :expr form :kind 0) (incf #S(sb-impl::comma :expr var :kind 0))))) (delist var)))


[User]
Generate a defmacro form that transforms code like this:
(ct-flet nil
  nil)

Pattern to recognize: Macro call that should be transformed by CT-FLET

(ct-flet nil
  nil)

[Assistant]
(defmacro CT-FLET ...)

;; macroexpand:
(cond (*within-captured-dynenv* (progn nil))
      (t
       (error
        "No macrodynamic environment has been captured to establish CT-FLET bindings.")))


[User]
Write a Common Lisp macro to handle this code pattern:
(defclause generating (var iteration) "Lazy version of FOR. The user must call UPDATE or TRY-UPDATE in the body of the DO+ form in order to compute new values for the variable(s). Initialization, instead, is *always* performed eagerly." (make-generator :name (if (symbolp var) var (extract-variables var)) :clauses `(for ,var ,iteration)))

Problem: Macro call that should be transformed by defclause

(defclause generating (var iteration) "Lazy version of FOR. The user must call UPDATE or TRY-UPDATE in the body of the DO+ form in order to compute new values for the variable(s). Initialization, instead, is *always* performed eagerly." (make-generator :name (if (symbolp var) var (extract-variables var)) :clauses `(for ,var ,iteration)))

[Assistant]
(defmacro defclause (name arglist &body body)
  "Same as cl:defmacro, but additionally records <name> in *clauses* as a known clause macro."
  `(progn
     (defmacro ,name ,arglist ,@body)
     (pushnew ',name *clauses*)))

;; macroexpand:
(progn (defmacro generating (var iteration) "Lazy version of FOR. The user must call UPDATE or TRY-UPDATE in the body of the DO+ form in order to compute new values for the variable(s). Initialization, instead, is *always* performed eagerly." (make-generator :name (if (symbolp var) var (extract-variables var)) :clauses (sb-int:quasiquote (for #S(sb-impl::comma :expr var :kind 0) #S(sb-impl::comma :expr iteration :kind 0))))) (pushnew (quote generating) *clauses*))


[User]
Define a macro that eliminates this repetitive pattern:
(with-mocks () (answer foo 1 2 3) (is (eql 1 (foo))) (is (eql 2 (foo))) (is (eql 3 (foo))) (is (eql 3 (foo))))

Issue: Macro call that should be transformed by with-mocks

(with-mocks () (answer foo 1 2 3) (is (eql 1 (foo))) (is (eql 2 (foo))) (is (eql 3 (foo))) (is (eql 3 (foo))))

[Assistant]
(defmacro with-mocks ((&key (recordp T)) &body body)
  "Execute BODY in a new mocking context.  Invocations will be recorded
if RECORDP is set (default true)."
  `(call-with-mocks
    (lambda () ,@body)
    :recordp ,recordp))

;; macroexpand:
(call-with-mocks (lambda nil (answer foo 1 2 3) (is (eql 1 (foo))) (is (eql 2 (foo))) (is (eql 3 (foo))) (is (eql 3 (foo)))) :recordp t)


[User]
Write a Common Lisp macro to handle this code pattern:
(dig nil)

Problem: Macro call that should be transformed by DIG

(dig nil)

[Assistant]
(defmacro DIG ...)

;; macroexpand:
(dig 1 nil)


[User]
Generate a defmacro form that transforms code like this:
(some->> nil (progn))

Pattern to recognize: Macro call that should be transformed by SOME->>

(some->> nil (progn))

[Assistant]
(defmacro SOME->> ...)

;; macroexpand:
(let* ((#:|some122| nil) (#:|some122| (when #:|some122| (progn #:|some122|))))
  #:|some122|)


[User]
Generate a defmacro form that transforms code like this:
(alist-bind (tag name id) form (let (symbol-type) (cond ((string= tag ":struct") (setf tag :struct) (setf symbol-type :cstruct)) ((string= tag ":union") (setf tag :union) (setf symbol-type :cunion)) ((string= tag ":enum") (setf tag :enum) (setf symbol-type :cenum)) (t (error "Unknown tag for MAKE-RECORD-REF: ~S" tag))) `((,tag (,(if (and (string= name "") (> id 0)) nil (foreign-type-symbol name symbol-type *package*)) ,@(when (and (string= name "") (> id 0)) `(:id ,id)))))))

Pattern to recognize: Macro call that should be transformed by alist-bind

(alist-bind (tag name id) form (let (symbol-type) (cond ((string= tag ":struct") (setf tag :struct) (setf symbol-type :cstruct)) ((string= tag ":union") (setf tag :union) (setf symbol-type :cunion)) ((string= tag ":enum") (setf tag :enum) (setf symbol-type :cenum)) (t (error "Unknown tag for MAKE-RECORD-REF: ~S" tag))) `((,tag (,(if (and (string= name "") (> id 0)) nil (foreign-type-symbol name symbol-type *package*)) ,@(when (and (string= name "") (> id 0)) `(:id ,id)))))))

[Assistant]
(defmacro alist-bind ((&rest vars) alist &body body)
  "Inefficient but doesn't really matter here"
  (once-only (alist)
    `(let (,@(mapcar (lambda (x)
                       (if (consp x)
                           `(,(car x) (aval ,(cadr x) ,alist))
                           `(,x (aval ,(make-keyword x) ,alist))))
                     vars))
       ,@body)))

;; macroexpand:
(let ((#:alist233 form)) (let ((tag (aval :tag #:alist233)) (name (aval :name #:alist233)) (id (aval :id #:alist233))) (let (symbol-type) (cond ((string= tag ":struct") (setf tag :struct) (setf symbol-type :cstruct)) ((string= tag ":union") (setf tag :union) (setf symbol-type :cunion)) ((string= tag ":enum") (setf tag :enum) (setf symbol-type :cenum)) (t (error "Unknown tag for MAKE-RECORD-REF: ~S" tag))) (sb-int:quasiquote ((#S(sb-impl::comma :expr tag :kind 0) (#S(sb-impl::comma :expr (if (and (string= name "") (> id 0)) nil (foreign-type-symbol name symbol-type *package*)) :kind 0) #S(sb-impl::comma :expr (when (and (string= name "") (> id 0)) (sb-int:quasiquote (:id #S(sb-impl::comma :expr id :kind 0)))) :kind 2))))))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(enable-quasi-quoted-bivalent-to-binary-emitting-form-syntax nil)

Write a macro that addresses: Macro call that should be transformed by ENABLE-QUASI-QUOTED-BIVALENT-TO-BINARY-EMITTING-FORM-SYNTAX

(enable-quasi-quoted-bivalent-to-binary-emitting-form-syntax nil)

[Assistant]
(defmacro ENABLE-QUASI-QUOTED-BIVALENT-TO-BINARY-EMITTING-FORM-SYNTAX ...)

;; macroexpand:
(eval-when (:compile-toplevel :execute)
  (setf *readtable* (copy-readtable *readtable*))
  (set-quasi-quoted-bivalent-to-binary-emitting-form-syntax-in-readtable nil
                                                                         :with-inline-emitting
                                                                         nil
                                                                         :declarations
                                                                         'nil
                                                                         :start-character
                                                                         nil
                                                                         :end-character
                                                                         nil
                                                                         :unquote-character
                                                                         #\COMMA
                                                                         :splice-character
                                                                         #\COMMERCIAL_AT
                                                                         :destructive-splice-character
                                                                         #\FULL_STOP
                                                                         :dispatched-quasi-quote-name
                                                                         "biv"
                                                                         :encoding
                                                                         *default-character-encoding*)
  (values))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(min-of nil
  :key
  nil)

Write a macro that addresses: Macro call that should be transformed by MIN-OF

(min-of nil
  :key
  nil)

[Assistant]
(defmacro MIN-OF ...)

;; macroexpand:
(lc (nil :key nil) minimize)


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-custom-var (:real *real-handler*))

What needs to change: Macro call that should be transformed by define-custom-var

(define-custom-var (:real *real-handler*))

[Assistant]
(defmacro define-custom-var ((key name) &rest other-args)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (progn (pushnew '(,name . ,key) *custom-vars* :test #'equal)
            (defvar ,name ,@other-args))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (progn (pushnew (quote (*real-handler* . :real)) *custom-vars* :test (function equal)) (defvar *real-handler*)))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(deferror "55P03" lock-not-available object-state-error)

What needs to change: Macro call that should be transformed by deferror

(deferror "55P03" lock-not-available object-state-error)

[Assistant]
(defmacro deferror (code typename &optional (superclass 'database-error))
  `(progn (define-condition ,typename (,superclass) ())
          (setf (gethash ,code *error-table*) ',typename)))

;; macroexpand:
(progn (define-condition lock-not-available (object-state-error) nil) (setf (gethash "55P03" *error-table*) (quote lock-not-available)))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(with-temp (d :directory t :debug (<= 1 *debug-prolog*)) (with-temp (input-file :tmpdir d :template "XXXXXX.prolog" :debug (<= 1 *debug-prolog*)) (with-open-file (s input-file :direction :output :if-does-not-exist :error) (dolist (r rules) (print-rule s r))) (run-command-with-debug-print `("swipl" "--quiet" "-l" ,input-file ,@args) :input input :output output :error error)))

Write a macro that addresses: Macro call that should be transformed by with-temp

(with-temp (d :directory t :debug (<= 1 *debug-prolog*)) (with-temp (input-file :tmpdir d :template "XXXXXX.prolog" :debug (<= 1 *debug-prolog*)) (with-open-file (s input-file :direction :output :if-does-not-exist :error) (dolist (r rules) (print-rule s r))) (run-command-with-debug-print `("swipl" "--quiet" "-l" ,input-file ,@args) :input input :output output :error error)))

[Assistant]
(defmacro with-temp ((var &key directory template (tmpdir "/tmp/") debug) &body body)
  "Create a temporary file, then remove the file by unwind-protect.
Most arguments are analogous to mktemp.
When DIRECTORY is non-nil, creates a directory instead.
DEBUG is a form.
When evaluated to non-nil, it does not remove the directory so that you can investigate what happened inside the directory.
It may be evaluated multiple times."
  (with-gensyms (command)
    `(let ((,var (uiop:run-program
                  (let ((,command (format nil "mktemp --tmpdir='~a' ~@[-d~*~] ~@[~a~]"
                                          ,tmpdir ,directory ,template)))
                    (when ,debug
                      (format *error-output* "~&; ~a~%" ,command))
                    ,command)
                  :output '(:string :stripped t))))
       (unwind-protect
            (progn ,@body)
         (if ,debug
             (format *error-output* "~&; not removing ~a for debugging~%" ,var)
             (uiop:run-program (format nil "rm -rf ~a" (namestring ,var)) :ignore-error-status t))))))

;; macroexpand:
(let ((d (uiop/run-program:run-program (let ((#:command175 (format nil "mktemp --tmpdir='~a' ~@[-d~*~] ~@[~a~]" "/tmp/" t nil))) (when (<= 1 *debug-prolog*) (format *error-output* "~&; ~a~%" #:command175)) #:command175) :output (quote (:string :stripped t))))) (unwind-protect (progn (with-temp (input-file :tmpdir d :template "XXXXXX.prolog" :debug (<= 1 *debug-prolog*)) (with-open-file (s input-file :direction :output :if-does-not-exist :error) (dolist (r rules) (print-rule s r))) (run-command-with-debug-print (sb-int:quasiquote ("swipl" "--quiet" "-l" #S(sb-impl::comma :expr input-file :kind 0) #S(sb-impl::comma :expr args :kind 2))) :input input :output output :error error))) (if (<= 1 *debug-prolog*) (format *error-output* "~&; not removing ~a for debugging~%" d) (uiop/run-program:run-program (format nil "rm -rf ~a" (namestring d)) :ignore-error-status t))))


[User]
Define a macro that eliminates this repetitive pattern:
(defpattern list (&rest args) (when args `(cons ,(car args) (list ,@(cdr args)))))

Issue: Macro call that should be transformed by defpattern

(defpattern list (&rest args) (when args `(cons ,(car args) (list ,@(cdr args)))))

[Assistant]
(defmacro defpattern (name lambda-list &body body)
  "Defines a derived pattern specifier named NAME. This is analogous
to DEFTYPE.

Examples:

    ;; Defines a LIST pattern.
    (defpattern list (&rest args)
      (when args
        `(cons ,(car args) (list ,@(cdr args)))))"
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf (pattern-expand-function ',name) (lambda ,lambda-list ,@body))))

;; macroexpand:
(%defpattern list (quote &rest) (quote args) (lambda (when args (quasiquote (cons #S(sb-impl::comma :expr (car args) :kind 0) (list #S(sb-impl::comma :expr (cdr args) :kind 2)))))))


[User]
Generate a defmacro form that transforms code like this:
(when specifier `(specifier (make-nodelist ,specifier)))

Pattern to recognize: Macro call that should be transformed by when

(when specifier `(specifier (make-nodelist ,specifier)))

[Assistant]
(defmacro when (test &body forms)
  `(if ,test
	   ,(cl:if (cadr forms)
			   `(progn ,@forms)
			   (car forms))))

;; macroexpand:
(if specifier (sb-int:quasiquote (specifier (make-nodelist #S(sb-impl::comma :expr specifier :kind 0)))))


[User]
Define a macro that eliminates this repetitive pattern:
(signal-syntax-error* (lexer-pos lexer) "Character missing after '\\c'")

Issue: Macro call that should be transformed by signal-syntax-error*

(signal-syntax-error* (lexer-pos lexer) "Character missing after '\\c'")

[Assistant]
(defmacro signal-syntax-error* (pos format-control &rest format-arguments)
  `(error 'ppcre-syntax-error
          :pos ,pos
          :format-control ,format-control
          :format-arguments (list ,@format-arguments)))

;; macroexpand:
(error (quote ppcre-syntax-error) :pos (lexer-pos lexer) :format-control "Character missing after '\\c'" :format-arguments (list))


[User]
Define a macro that eliminates this repetitive pattern:
(check-cursor-attached cluffer:line (cursor))

Issue: Macro call that should be transformed by check-cursor-attached

(check-cursor-attached cluffer:line (cursor))

[Assistant]
(defmacro check-cursor-attached (name arguments)
  (let ((args (substitute '(cursor cluffer:cursor) 'cursor arguments)))
    `(defmethod ,name :before ,args
       (declare (ignore ,@(set-difference (remove 'cursor arguments)
                                          lambda-list-keywords)))
       (unless (cluffer:cursor-attached-p cursor)
         (error 'cluffer:cursor-detached)))))

;; macroexpand:
(defmethod cluffer:line :before ((cursor cluffer:cursor)) (declare (ignore)) (unless (cluffer:cursor-attached-p cursor) (error (quote cluffer:cursor-detached))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(alist-bind (name type bit-size bit-offset bit-alignment) field (let ((symbol (foreign-type-symbol name field-type *package*))) (list* symbol `(,@(parse-type type (aval :tag type)) ,@(when (eq field-type :cfield) `(:bit-size ,bit-size :bit-offset ,bit-offset :bit-alignment ,bit-alignment))))))

Write a macro that addresses: Macro call that should be transformed by alist-bind

(alist-bind (name type bit-size bit-offset bit-alignment) field (let ((symbol (foreign-type-symbol name field-type *package*))) (list* symbol `(,@(parse-type type (aval :tag type)) ,@(when (eq field-type :cfield) `(:bit-size ,bit-size :bit-offset ,bit-offset :bit-alignment ,bit-alignment))))))

[Assistant]
(defmacro alist-bind ((&rest vars) alist &body body)
  "Inefficient but doesn't really matter here"
  (once-only (alist)
    `(let (,@(mapcar (lambda (x)
                       (if (consp x)
                           `(,(car x) (aval ,(cadr x) ,alist))
                           `(,x (aval ,(make-keyword x) ,alist))))
                     vars))
       ,@body)))

;; macroexpand:
(let ((#:alist240 field)) (let ((name (aval :name #:alist240)) (type (aval :type #:alist240)) (bit-size (aval :bit-size #:alist240)) (bit-offset (aval :bit-offset #:alist240)) (bit-alignment (aval :bit-alignment #:alist240))) (let ((symbol (foreign-type-symbol name field-type *package*))) (list* symbol (sb-int:quasiquote (#S(sb-impl::comma :expr (parse-type type (aval :tag type)) :kind 2) #S(sb-impl::comma :expr (when (eq field-type :cfield) (sb-int:quasiquote (:bit-size #S(sb-impl::comma :expr bit-size :kind 0) :bit-offset #S(sb-impl::comma :expr bit-offset :kind 0) :bit-alignment #S(sb-impl::comma :expr bit-alignment :kind 0)))) :kind 2)))))))


[User]
Write a Common Lisp macro to handle this code pattern:
(do+ (for x (in '(1 2 3 4))) (for z (previous y)) (for y (previous x)) (collect (list x y z)))

Problem: Macro call that should be transformed by do+

(do+ (for x (in '(1 2 3 4))) (for z (previous y)) (for y (previous x)) (collect (list x y z)))

[Assistant]
(defmacro do+ (&body body)
  "High-level, extensible iteration construct. Refer to the manual for syntax and semantics."
  `(do+/internal nil ,@body))

;; macroexpand:
(do+/internal nil (for x (in (quote (1 2 3 4)))) (for z (previous y)) (for y (previous x)) (collect (list x y z)))


[User]
Write a Common Lisp macro to handle this code pattern:
(is-values (values 1 2 nil 3) '(1 2 nil 3))

Problem: Macro call that should be transformed by is-values

(is-values (values 1 2 nil 3) '(1 2 nil 3))

[Assistant]
(defmacro is-values (got expected &rest args)
  `(is (multiple-value-list ,got) ,expected ,@args))

;; macroexpand:
(is (multiple-value-list (values 1 2 nil 3)) (quote (1 2 nil 3)))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(lret ((out (make-array (array-dimensions array) :element-type element-type))) (map-into (%flatten out) fn (%flatten array)))

What needs to change: Macro call that should be transformed by lret

(lret ((out (make-array (array-dimensions array) :element-type element-type))) (map-into (%flatten out) fn (%flatten array)))

[Assistant]
(defmacro lret ((&rest bindings) &body body)
  "Return the initial value of the last binding in BINDINGS. The idea
is to create something, initialize it, and then return it.

    (lret ((x 1)
           (y (make-array 1)))
      (setf (aref y 0) x))
    => #(1)

Note that the value returned is the value initially bound. Subsequent
assignments are ignored.

    (lret ((x 1))
      (setf x 2))
    => 1

Furthermore, on Lisps that support it, the variable may be made
read-only, making assignment a compiler-time error.

`lret' may seem trivial, but it fufills the highest purpose a macro
can: it eliminates a whole class of bugs (initializing an object, but
forgetting to return it).

Cf. `aprog1' in Anaphora."
  `(lret-aux let ,bindings
     ,@body))

;; macroexpand:
(lret-aux let ((out (make-array (array-dimensions array) :element-type element-type))) (map-into (%flatten out) fn (%flatten array)))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(list-of 'some-name)

What needs to change: Macro call that should be transformed by LIST-OF

(list-of 'some-name)

[Assistant]
(defmacro LIST-OF ...)

;; macroexpand:
(lc ('some-name) collect)


[User]
Write a Common Lisp macro to handle this code pattern:
(collect-sum nil (progn))

Problem: Macro call that should be transformed by COLLECT-SUM

(collect-sum nil (progn))

[Assistant]
(defmacro COLLECT-SUM ...)

;; macroexpand:
(compiler-let ((*optimize-series-expressions* nil)) (collect-sum nil (progn)))


[User]
Generate a defmacro form that transforms code like this:
(append-at-end nil :key nil)

Pattern to recognize: Macro call that should be transformed by APPEND-AT-END

(append-at-end nil :key nil)

[Assistant]
(defmacro APPEND-AT-END ...)

;; macroexpand:
(dolist (#:a122 nil)
  (typecase #:a122
    (list (collect-at-end nil :key #:a122))
    (t
     (let ((c (cons #:a122 nil)))
       (when (null nil) (setf nil c))
       (unless (null :key) (setf (cdr :key) c))
       (setf :key (last c))))))


[User]
Define a macro that eliminates this repetitive pattern:
(defgenerator ifilter (predicate generator) "Emits only those items in generator that are true by predicate. The generator equivalent of remove-if-not" (do-generator (g generator) (when (funcall predicate g) (yield g))))

Issue: Macro call that should be transformed by defgenerator

(defgenerator ifilter (predicate generator) "Emits only those items in generator that are true by predicate. The generator equivalent of remove-if-not" (do-generator (g generator) (when (funcall predicate g) (yield g))))

[Assistant]
(defmacro defgenerator (name arguments &body body)
  (multiple-value-bind (remaining-forms declarations doc-string)
      (alexandria:parse-body body :documentation t)
    `(defun ,name ,arguments
       ,doc-string
       ,@declarations
       (with-yield
	 ,@remaining-forms))))

;; macroexpand:
(defun ifilter (predicate generator) "Emits only those items in generator that are true by predicate. The generator equivalent of remove-if-not" (with-yield (do-generator (g generator) (when (funcall predicate g) (yield g)))))


[User]
Write a Common Lisp macro to handle this code pattern:
(define-custom-var (:array-type *json-array-type*) 'vector)

Problem: Macro call that should be transformed by define-custom-var

(define-custom-var (:array-type *json-array-type*) 'vector)

[Assistant]
(defmacro define-custom-var ((key name) &rest other-args)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (progn (pushnew '(,name . ,key) *custom-vars* :test #'equal)
            (defvar ,name ,@other-args))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (progn (pushnew (quote (*json-array-type* . :array-type)) *custom-vars* :test (function equal)) (defvar *json-array-type* (quote vector))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(dreletf nil
  :key
  nil)

Write a macro that addresses: Macro call that should be transformed by DRELETF

(dreletf nil
  :key
  nil)

[Assistant]
(defmacro DRELETF ...)

;; macroexpand:
(let ((#:symbol-store234
       (with-symbol-access
         (list))))
  (special-symbol-reprogv #:symbol-store234
      (list)
    (locally (declare (special)) :key nil)))


[User]
Define a macro that eliminates this repetitive pattern:
(newq nil (progn))

Issue: Macro call that should be transformed by NEWQ

(newq nil (progn))

[Assistant]
(defmacro NEWQ ...)

;; macroexpand:
(new 'nil (progn))


[User]
Write a Common Lisp macro to handle this code pattern:
(defclass/a dbi-driver () () (:documentation "Base class for DB driver."))

Problem: Macro call that should be transformed by defclass/a

(defclass/a dbi-driver () () (:documentation "Base class for DB driver."))

[Assistant]
(defmacro defclass/a (name superclasses slots &rest class-options)
  `(progn
     (defclass ,name ,superclasses ,slots ,@class-options)
     (deftype ,(intern (format nil "<~A>" (symbol-name name))) () ',name)
     (setf (find-class ',(intern (format nil "<~A>" (symbol-name name))))
           (find-class ',name))))

;; macroexpand:
(progn (defclass dbi-driver nil nil (:documentation "Base class for DB driver.")) (deftype <dbi-driver> nil (quote dbi-driver)) (setf (find-class (quote <dbi-driver>)) (find-class (quote dbi-driver))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(lambda-match
  'some-name)

What needs to change: Macro call that should be transformed by LAMBDA-MATCH

(lambda-match
  'some-name)

[Assistant]
(defmacro LAMBDA-MATCH ...)

;; macroexpand:
(lambda (#:arg150)
  (match #:arg150
    'some-name))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(with-access-values nil
    nil)

What needs to change: Macro call that should be transformed by WITH-ACCESS-VALUES

(with-access-values nil
    nil)

[Assistant]
(defmacro with-access-values ((&rest bindings) obj &body body)
  "A macro which binds local variables from accessed values on object
   according to bindings

   bindings: (local-symbol-and-access-key
              or (local-symbol access-key)
               ...)
   obj: the thing we are accessing data from
  "
  (flet ((key-for (it)
           (etypecase it
             (symbol `(quote ,it))
             ((or string keyword list) it))))
    (let* ((o (gensym "OBJ"))
           (expanded-bindings
             (iter (for b in (ensure-list bindings))
               (when (first-iteration-p)
                 (collect `(,o ,obj)))
               (typecase b
                 (null)
                 (list (collect `(,(first b) (access ,o ,(key-for (second b))))))
                 (symbol (collect `(,b (access ,o ,(key-for b)))))))))
      `(let* ,expanded-bindings
        ,@body))))

;; macroexpand:
(let* ())


[User]
You are a Common Lisp macro expert. Given this code pattern:
(collect-alist nil nil)

Write a macro that addresses: Macro call that should be transformed by COLLECT-ALIST

(collect-alist nil nil)

[Assistant]
(defmacro COLLECT-ALIST ...)

;; macroexpand:
(common-lisp:let* ((#:generator-430 (generator nil))
                   #:values-423
                   (#:generator-428 (generator nil))
                   #:keys-422
                   (#:alist-424 nil))
  (declare (type generator #:generator-430)
           (type generator #:generator-428)
           (type list #:alist-424))
  (tagbody
   #:ll-431
    (setq #:values-423 (next-in #:generator-430 (go end)))
    (setq #:keys-422 (next-in #:generator-428 (go end)))
    (setq #:alist-424 (cons (cons #:keys-422 #:values-423) #:alist-424))
    (go #:ll-431)
   end)
  #:alist-424)


[User]
You are a Common Lisp macro expert. Given this code pattern:
(declare-deprecated-operators nil nil)

Write a macro that addresses: Macro call that should be transformed by DECLARE-DEPRECATED-OPERATORS

(declare-deprecated-operators nil nil)

[Assistant]
(defmacro DECLARE-DEPRECATED-OPERATORS ...)

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (define-compiler-macro nil
      (&whole form &rest arguments)
    (declare (ignore arguments))
    (let ((where-from (or *compile-file-truename* *load-truename*)))
      (when *deprecation-warnings*
        (warn 'deprecation-warning :operator-name 'nil :source-file where-from
              :source-form form))
      (when where-from
        (pushnew where-from (gethash 'nil *deprecation-locations*) :test
                 #'equalp))
      form))
  (define-compiler-macro nil
      (&whole form &rest arguments)
    (declare (ignore arguments))
    (let ((where-from (or *compile-file-truename* *load-truename*)))
      (when *deprecation-warnings*
        (warn 'deprecation-warning :operator-name 'nil :source-file where-from
              :source-form form))
      (when where-from
        (pushnew where-from (gethash 'nil *deprecation-locations*) :test
                 #'equalp))
      form))
  (values))


[User]
Write a Common Lisp macro to handle this code pattern:
(log-message z z)

Problem: Macro call that should be transformed by log-message

(log-message z z)

[Assistant]
(defmacro log-message (category description &rest arguments)
  `(log-manager-message (log-manager) ,category ,description ,@arguments))

;; macroexpand:
(log-manager-message (log-manager) z z)


[User]
Generate a defmacro form that transforms code like this:
(signal-syntax-error* (1- (lexer-pos lexer)) "Quantifier '~A' not allowed." next-char)

Pattern to recognize: Macro call that should be transformed by signal-syntax-error*

(signal-syntax-error* (1- (lexer-pos lexer)) "Quantifier '~A' not allowed." next-char)

[Assistant]
(defmacro signal-syntax-error* (pos format-control &rest format-arguments)
  `(error 'ppcre-syntax-error
          :pos ,pos
          :format-control ,format-control
          :format-arguments (list ,@format-arguments)))

;; macroexpand:
(error (quote ppcre-syntax-error) :pos (1- (lexer-pos lexer)) :format-control "Quantifier '~A' not allowed." :format-arguments (list next-char))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(while 'some-name)

What needs to change: Macro call that should be transformed by WHILE

(while 'some-name)

[Assistant]
(defmacro WHILE ...)

;; macroexpand:
(loop while 'some-name
      do (progn))


[User]
Write a Common Lisp macro to handle this code pattern:
(with-reader-syntax (hash-table) (is (equalp (alexandria:plist-hash-table '(:a 1 :b 2) :test 'equalp) (er "{:a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table '(:a 1 :b 2) :test 'eq) (er "{eq :a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table '("a" 1.0 "b" 2) :test 'equalp) (er "{\"a\" 1 \"b\" 2}"))))

Problem: Macro call that should be transformed by with-reader-syntax

(with-reader-syntax (hash-table) (is (equalp (alexandria:plist-hash-table '(:a 1 :b 2) :test 'equalp) (er "{:a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table '(:a 1 :b 2) :test 'eq) (er "{eq :a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table '("a" 1.0 "b" 2) :test 'equalp) (er "{\"a\" 1 \"b\" 2}"))))

[Assistant]
(defmacro with-reader-syntax (reader-macro-identifiers &body body)
  "This macro is only made for use by read-and-eval functionality,
and rather directed towards tests than users. So, do not export."
  (let ((identifiers (loop :for identifier :in reader-macro-identifiers
                           :collect `(quote ,identifier))))
    `(let ((*array-function*         'make-t-array-from-initial-contents)
           (*hash-table-function*    'alexandria:plist-hash-table)
           (*get-val-function*       'get-val)
           (*get-val-array-function* 'cl:aref)
           (*set-function*           'cl:remove-duplicates)
           (*alists-are-lists*       nil)
           (*plists-are-lists*       nil)
           (*readtable*             (%enable-reader-syntax *readtable* ,@identifiers)))
       ,@body)))

;; macroexpand:
(let ((*array-function* (quote make-t-array-from-initial-contents)) (*hash-table-function* (quote alexandria:plist-hash-table)) (*get-val-function* (quote get-val)) (*get-val-array-function* (quote aref)) (*set-function* (quote remove-duplicates)) (*alists-are-lists* nil) (*plists-are-lists* nil) (*readtable* (%enable-reader-syntax *readtable* (quote hash-table)))) (is (equalp (alexandria:plist-hash-table (quote (:a 1 :b 2)) :test (quote equalp)) (er "{:a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table (quote (:a 1 :b 2)) :test (quote eq)) (er "{eq :a 1 :b 2}"))) (is (equalp (alexandria:plist-hash-table (quote ("a" 1.0 "b" 2)) :test (quote equalp)) (er "{\"a\" 1 \"b\" 2}"))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(is "<~S>" "<~S>")

Write a macro that addresses: Macro call that should be transformed by is

(is "<~S>" "<~S>")

[Assistant]
(defmacro is (got expected &rest args)
  (with-gensyms (duration result new-args desc)
    (once-only (expected)
      `(let* ((,new-args (list ,@args))
              (,desc (parse-description-and-test ,new-args)))
         (with-catching-errors (:description ,desc :expected ,expected)
           (with-duration ((,duration ,result) ,got)
             (test ,result ,expected ,new-args
                   :duration ,duration)))))))

;; macroexpand:
(let ((#:expected171 "<~S>")) (let* ((#:new-args169 (list)) (#:desc170 (parse-description-and-test #:new-args169))) (with-catching-errors (:description #:desc170 :expected #:expected171) (with-duration ((#:duration167 #:result168) "<~S>") (test #:result168 #:expected171 #:new-args169 :duration #:duration167)))))


[User]
Write a Common Lisp macro to handle this code pattern:
(define-test finish (finish T) (finish (error "NOPE")))

Problem: Macro call that should be transformed by define-test

(define-test finish (finish T) (finish (error "NOPE")))

[Assistant]
(defmacro define-test (name &body arguments-and-body)
  (destructuring-bind (nparent name) (if (listp name) name (list NIL name))
    (form-fiddle:with-body-options (body options parent home (test-class 'test) (compile-at :compile-time) defun) arguments-and-body
      (let ((body (remove 'define-test body :key (lambda (a) (when (listp a) (car a))) :test #'eql))
            (defs (remove 'define-test body :key (lambda (a) (when (listp a) (car a))) :test-not #'eql))
            (home-form (or home `(find-package ,(package-name *package*)))))
        (when (and parent nparent)
          (error "Cannot specify parent through name and through a keyword argument at the same time!"))
        `(let ((*package* (find-package ,(package-name *package*)))) ; Make sure package stays consistent throughout initialisation.
           (setf (find-test ',name ,home-form)
                 (ensure-test ',test-class
                              :name ',name
                              :home ,home-form
                              :tests (list ,@(loop for form in body
                                                   collect (ecase compile-at
                                                             (:compile-time `(lambda () ,form))
                                                             (:execute `(lambda () (call-compile ',form))))))
                              :parent ',(or parent nparent)
                              ,@(loop for option in options
                                      collect `',option)))
           ,@(loop for (def subname . body) in defs
                   collect `(,def (,name ,subname)
                              :home ,home
                              ,@body))
           ,@(when defun
               `((defun ,(if (stringp name) (read-symbol name) name) (&rest test-args)
                   (apply #'test (find-test ',name ,home-form) test-args))))
           ',name)))))

;; macroexpand:
(let ((*package* (find-package #A((9) base-char . "PARACHUTE")))) (setf (find-test (quote finish) (find-package #A((9) base-char . "PARACHUTE"))) (ensure-test (quote test) :name (quote finish) :home (find-package #A((9) base-char . "PARACHUTE")) :tests (list (lambda nil (finish t)) (lambda nil (finish (error "NOPE")))) :parent (quote nil))) (quote finish))


[User]
Generate a defmacro form that transforms code like this:
(flet* nil
  :key
  nil)

Pattern to recognize: Macro call that should be transformed by FLET*

(flet* nil
  :key
  nil)

[Assistant]
(defmacro FLET* ...)

;; macroexpand:
(flet ()
  :key
  nil)


[User]
Define a macro that eliminates this repetitive pattern:
(cond-> nil)

Issue: Macro call that should be transformed by COND->

(cond-> nil)

[Assistant]
(defmacro COND-> ...)

;; macroexpand:
(let* ((#:g138 nil))
  #:g138)


[User]
Create a Common Lisp macro for the following transformation. Before code:
(dotable (item _ set2) (add# item set))

What needs to change: Macro call that should be transformed by dotable

(dotable (item _ set2) (add# item set))

[Assistant]
(defmacro dotable ((k v table &optional rez) &body body)
  "Like DOLIST but iterates over key-value pairs (K V) in anything, that can be
   viewed as a table (hash-table, alist, plist, object).
   Autodeclares variables named _ as ignored."
  (with-gensyms (pair)
    (once-only (table)
      (let ((_ (find "_" (list k v)
                     :test 'string=
                     :key 'symbol-name)))
        `(block nil
           (etypecase ,table
             (hash-table (maphash (lambda (,k ,v)
                                    ,(when _ `(declare (ignore rutils.bind:_)))
                                    ,@body)
                                  ,table))

             (list (if (rutils.list:alistp ,table)
                       (dolist (,pair ,table)
                         (destructuring-bind (,k . ,v) ,pair
                           ,@(when _ `((declare (ignore ,_))))
                           ,@body))
                       (error 'simple-type-error
                              :format-control "Can't iterate over proper list ~
                                               in DOTABLE: need an alist"))))
           ,rez)))))

;; macroexpand:
(let ((#:table166 set2)) (block nil (etypecase #:table166 (hash-table (maphash (lambda (item _) (declare (ignore rutils.bind:_)) (|ADD#| item set)) #:table166)) (list (if (alistp #:table166) (dolist (#:g165 #:table166) (destructuring-bind (item . _) #:g165 (declare (ignore _)) (|ADD#| item set))) (error (quote simple-type-error) :format-control "Can't iterate over proper list ~
                                               in DOTABLE: need an alist")))) nil))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(do-generator (val generator) (yield (apply function val)))

What needs to change: Macro call that should be transformed by do-generator

(do-generator (val generator) (yield (apply function val)))

[Assistant]
(defmacro do-generator ((var &rest vars-and-generator) &body body)
  "Steps through the specified generator, binding the value it returns to var, then executing the body for each step. If multiple variables are specified and the generator returns multiple values, the extra values will be bound to the extra variables."
  (let ((g (gensym)))
    `(let ((,g ,(car (last vars-and-generator))))
       (loop
	  do (if-generator ((,var ,@(butlast vars-and-generator)) ,g)
			   (progn
			     ,@body)
			   (return))))))

;; macroexpand:
(let ((#:g166 generator)) (loop do (if-generator ((val) #:g166) (progn (yield (apply function val))) (return))))


[User]
Define a macro that eliminates this repetitive pattern:
(with-env (setp 5 [clos-object 'a]))

Issue: Macro call that should be transformed by with-env

(with-env (setp 5 [clos-object 'a]))

[Assistant]
(defmacro with-env (&body body)
  (let ((body-value (gensym)))
    `(let (,body-value)
       (defclass foo () ((a :initform 3)))
       (defmethod get-val ((object foo) &rest slot/s) (slot-value object (car slot/s)))
       (defmethod (setf get-val) (new-value (object foo) &rest slot/s)
         (setf (slot-value object (car slot/s)) new-value))
       (defstruct bar a)
       (setq ,body-value
             (let ((str (alexandria:copy-array "abcde"))
                   (vec (alexandria:copy-array #(a b c d e)))
                   (arr (alexandria:copy-array #2A((1 2 3)
                                                   (4 5 6))))
                   (list      (copy-list '(a b c d e)))
                   (ht        (eval (read-from-string "{'a 'b 'c 'd}")))
                   (ht-eq     (eval (read-from-string "{eq \"a\" 1
                                                    \"b\" 2}")))
                   (ht-equalp (eval (read-from-string "{equalp '(1 2 3) \"a\"
                                                               '(4 5 6) \"b\"}")))
                   (assoc-list (copy-tree '((a . 1) (b . 2))))
                   (plist      (copy-list '(:a 4 :c 5)))
                   (clos-object (make-instance 'foo))
                   (struct      (make-bar :a 3)))
               (declare (ignorable str vec arr list ht ht-eq ht-equalp
                                   assoc-list plist clos-object struct))
               ,@body))
       (setf (find-class 'foo nil) nil)
       (setf (find-class 'bar nil) nil)
       ,body-value))

;; macroexpand:
(let (#:g138) (defclass foo nil ((a :initform 3))) (defmethod get-val ((object foo) &rest slot/s) (slot-value object (car slot/s))) (defmethod (setf get-val) (new-value (object foo) &rest slot/s) (setf (slot-value object (car slot/s)) new-value)) (defstruct bar a) (setq #:g138 (let ((str (alexandria:copy-array "abcde")) (vec (alexandria:copy-array #(a b c d e))) (arr (alexandria:copy-array #2A((1 2 3) (4 5 6)))) (list (copy-list (quote (a b c d e)))) (ht (eval (read-from-string "{'a 'b 'c 'd}"))) (ht-eq (eval (read-from-string "{eq \"a\" 1
                                                    \"b\" 2}"))) (ht-equalp (eval (read-from-string "{equalp '(1 2 3) \"a\"
                                                               '(4 5 6) \"b\"}"))) (assoc-list (copy-tree (quote ((a . 1) (b . 2))))) (plist (copy-list (quote (:a 4 :c 5)))) (clos-object (make-instance (quote foo))) (struct (make-bar :a 3))) (declare (ignorable str vec arr list ht ht-eq ht-equalp assoc-list plist clos-object struct)) (setp 5 [clos-object (quote a])))) (setf (find-class (quote foo) nil) nil) (setf (find-class (quote bar) nil) nil) #:g138)


[User]
Define a macro that eliminates this repetitive pattern:
(deferror "42P01" undefined-table syntax-error-or-access-violation)

Issue: Macro call that should be transformed by deferror

(deferror "42P01" undefined-table syntax-error-or-access-violation)

[Assistant]
(defmacro deferror (code typename &optional (superclass 'database-error))
  `(progn (define-condition ,typename (,superclass) ())
          (setf (gethash ,code *error-table*) ',typename)))

;; macroexpand:
(progn (define-condition undefined-table (syntax-error-or-access-violation) nil) (setf (gethash "42P01" *error-table*) (quote undefined-table)))


[User]
Define a macro that eliminates this repetitive pattern:
(declare-unary-operator 'some-name)

Issue: Macro call that should be transformed by DECLARE-UNARY-OPERATOR

(declare-unary-operator 'some-name)

[Assistant]
(defmacro DECLARE-UNARY-OPERATOR ...)

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (infix-math/data::save-unary-operator ''some-name))


[User]
Generate a defmacro form that transforms code like this:
(do-subclasses (itype index) (discover itype))

Pattern to recognize: Macro call that should be transformed by do-subclasses

(do-subclasses (itype index) (discover itype))

[Assistant]
(defmacro do-subclasses ((var class) &body body)
  "Iterate over the subclasses of CLASS performing BODY with VAR
lexically bound to the current subclass."
  (alexandria:with-gensyms (klasses)
    `(let ((,klasses (all-subclasses (find-class ',class))))
       (loop for ,var in ,klasses do ,@body))))

;; macroexpand:
(let ((#:klasses284 (all-subclasses (find-class (quote index))))) (loop for itype in #:klasses284 do (discover itype)))


[User]
Write a Common Lisp macro to handle this code pattern:
(adding-smart-slot-methods obj slot (:= (slot-value obj slot) val))

Problem: Macro call that should be transformed by adding-smart-slot-methods

(adding-smart-slot-methods obj slot (:= (slot-value obj slot) val))

[Assistant]
(defmacro adding-smart-slot-methods (obj slot expr)
  (with-gensyms (err class name alt args val)
    `(handler-case ,expr
       (simple-error (,err)
         (let ((,class (class-of ,obj))
               (,name (symbol-name ,slot)))
           (dolist (,alt (c2mop:class-slots ,class)
                         (error ,err))
             (let ((,alt (c2mop:slot-definition-name ,alt)))
               (when (string= ,name (symbol-name ,alt))
                 (add-method (ensure-generic-function 'smart-slot-value)
                             (make-instance
                              'standard-method
                              :specializers
                              (list ,class
                                    (c2mop:intern-eql-specializer ,slot))
                              :lambda-list '(,obj ,slot)
                              :function
                              (lambda (,args _)
                                (declare (ignorable _))
                                (slot-value (first ,args) ,alt))))
                 (add-method (ensure-generic-function 'smart-set-slot-value)
                             (make-instance
                              'standard-method
                              :specializers
                              (list ,class
                                    (c2mop:intern-eql-specializer ,slot)
                                    (find-class 't))
                              :lambda-list '(,obj ,slot ,val)
                              :function
                              (lambda (,args _)
                                (declare (ignorable _))
                                (:= (slot-value (first ,args) ,alt)
                                    (third ,args)))))
                 (let ((,slot ,alt))
                   (return ,expr))))))))))

;; macroexpand:
(handler-case (:= (slot-value obj slot) val) (simple-error (#:g155) (let ((#:g156 (class-of obj)) (#:g157 (symbol-name slot))) (dolist (#:g158 (sb-mop:class-slots #:g156) (error #:g155)) (let ((#:g158 (sb-mop:slot-definition-name #:g158))) (when (string= #:g157 (symbol-name #:g158)) (add-method (ensure-generic-function (quote smart-slot-value)) (make-instance (quote standard-method) :specializers (list #:g156 (sb-mop:intern-eql-specializer slot)) :lambda-list (quote (obj slot)) :function (lambda (#:g159 _) (declare (ignorable _)) (slot-value (first #:g159) #:g158)))) (add-method (ensure-generic-function (quote smart-set-slot-value)) (make-instance (quote standard-method) :specializers (list #:g156 (sb-mop:intern-eql-specializer slot) (find-class (quote t))) :lambda-list (quote (obj slot #:g160)) :function (lambda (#:g159 _) (declare (ignorable _)) (:= (slot-value (first #:g159) #:g158) (third #:g159))))) (let ((slot #:g158)) (return (:= (slot-value obj slot) val)))))))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(ct-flet nil
  :key
  nil)

What needs to change: Macro call that should be transformed by CT-FLET

(ct-flet nil
  :key
  nil)

[Assistant]
(defmacro CT-FLET ...)

;; macroexpand:
(cond (*within-captured-dynenv* (progn :key nil))
      (t
       (error
        "No macrodynamic environment has been captured to establish CT-FLET bindings.")))


[User]
Define a macro that eliminates this repetitive pattern:
(define nil)

Issue: Macro call that should be transformed by DEFINE

(define nil)

[Assistant]
(defmacro DEFINE ...)

;; macroexpand:
(eval-when (:load-toplevel :execute)
  (check-if-bound 'nil)
  (setf (get 'nil 'read-macro)
          (lambda (#:stream145) (let ((*standard-input* #:stream145)))))
  'nil)


[User]
You are a Common Lisp macro expert. Given this code pattern:
(define-error env-parent-context-mismatch () (env-a env-b) "Attempting to make an environment with different context to it's parent ~s~%~s~%~s" (cons (v-context env-a) (v-context env-b)) env-a env-b)

Write a macro that addresses: Macro call that should be transformed by define-error

(define-error env-parent-context-mismatch () (env-a env-b) "Attempting to make an environment with different context to it's parent ~s~%~s~%~s" (cons (v-context env-a) (v-context env-b)) env-a env-b)

[Assistant]
(defmacro define-error (name (&key (error-type 'varjo-error) (prefix "Varjo"))
                            (&rest args) error-string &body body)
  `(defcondition ,name (:error-type ,error-type :prefix ,prefix) ,args
       ,error-string ,@body))

;; macroexpand:
(defcondition env-parent-context-mismatch (:error-type varjo-error :prefix "Varjo") (env-a env-b) "Attempting to make an environment with different context to it's parent ~s~%~s~%~s" (cons (v-context env-a) (v-context env-b)) env-a env-b)


[User]
Generate a defmacro form that transforms code like this:
(gen-lambda-with-sticky-stop () (unless (cdr ldata) (get-next)) (setf ldata (cdr ldata)) (if (eq (car ldata) 'generator-stop) (sticky-stop) (apply #'values (ensure-list (car ldata)))))

Pattern to recognize: Macro call that should be transformed by gen-lambda-with-sticky-stop

(gen-lambda-with-sticky-stop () (unless (cdr ldata) (get-next)) (setf ldata (cdr ldata)) (if (eq (car ldata) 'generator-stop) (sticky-stop) (apply #'values (ensure-list (car ldata)))))

[Assistant]
(defmacro gen-lambda-with-sticky-stop (&rest rest)
  `(make-instance
    'basic-generator
    :function (sticky-stop-lambda ,@rest)))

;; macroexpand:
(make-instance (quote basic-generator) :function (sticky-stop-lambda nil (unless (cdr ldata) (get-next)) (setf ldata (cdr ldata)) (if (eq (car ldata) (quote generator-stop)) (sticky-stop) (apply (function values) (ensure-list (car ldata))))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(action (:after node-variable node new-subs) (alexandria:when-let ((res (or (find (node-variable-value node) subs :key #'ast-substitution-from) (find (node-variable-value node) new-subs :key #'ast-substitution-from)))) (ast-substitution-to res)))

Write a macro that addresses: Macro call that should be transformed by action

(action (:after node-variable node new-subs) (alexandria:when-let ((res (or (find (node-variable-value node) subs :key #'ast-substitution-from) (find (node-variable-value node) new-subs :key #'ast-substitution-from)))) (ast-substitution-to res)))

[Assistant]
(defmacro action ((when type &rest args) &body body)
  "Construct an action block, turning `body` into a lambda function
accepting `args` if `args` are provided. If there are no `args`, then
`body` is assumed to be a function object and is used directly with
`when` and `type` to create an `action` instance. Otherwise, the first
argument in `args` is declared to be a node of type `type`, and the
`args` and `body` are used to generate a lambda function."
  (check-type when keyword)
  (check-type type symbol)
  (assert (subtypep type 'node))
  (assert (or (not (endp args)) (= 1 (length body))))
  (if (endp args)
      `(make-action ',when ',type ,@body)
      `(make-action ',when ',type
                    (lambda (,@args)
                      (declare (type ,type ,(first args)))
                      ,@body))))

;; macroexpand:
(make-action (quote :after) (quote node-variable) (lambda (node new-subs) (declare (type node-variable node)) (alexandria:when-let ((res (or (find (node-variable-value node) subs :key (function ast-substitution-from)) (find (node-variable-value node) new-subs :key (function ast-substitution-from))))) (ast-substitution-to res))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-modf-expander car 1 (expr val new-val) (declare (ignore expr)) `(cons ,new-val (cdr ,val)))

What needs to change: Macro call that should be transformed by define-modf-expander

(define-modf-expander car 1 (expr val new-val) (declare (ignore expr)) `(cons ,new-val (cdr ,val)))

[Assistant]
(defmacro define-modf-expander (name nth-arg
                                (expr val new-val)
                                &body body)
  "Define a new expander which inverts forms starting with NAME.  Your function
should return an expansion from EXPR to a form that will build a new object that
has NEW-VAL in the place specified by expr.  NTH-ARG marks which argument is
considered the actual data which will be inverted next."
  (setf
   (gethash name *modf-nth-arg*)
   nth-arg)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf
      (gethash ',name *modf-nth-arg*)
      ,nth-arg
      (gethash ',name *modf-expansions*)
      (lambda (,expr ,val ,new-val)
        ,@body))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash (quote car) *modf-nth-arg*) 1 (gethash (quote car) *modf-expansions*) (lambda (expr val new-val) (declare (ignore expr)) (sb-int:quasiquote (cons #S(sb-impl::comma :expr new-val :kind 0) (cdr #S(sb-impl::comma :expr val :kind 0)))))))


[User]
Generate a defmacro form that transforms code like this:
(true 2)

Pattern to recognize: Macro call that should be transformed by true

(true 2)

[Assistant]
(defmacro true (form &optional description &rest format-args)
  `(eval-in-context
    *context*
    (make-instance 'comparison-result
                   :expression '(true ,form)
                   :value-form ',form
                   :body (lambda () ,form)
                   :expected 'T
                   :comparison 'geq
                   ,@(when description
                       `(:description (format NIL ,description ,@format-args))))))

;; macroexpand:
(eval-in-context *context* (make-instance (quote comparison-result) :expression (quote (true 2)) :value-form (quote 2) :body (lambda nil 2) :expected (quote t) :comparison (quote geq)))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(defstruct-compile-time (variable (:print-function print-variable) (:predicate variable?) (:constructor make-variable-internal)) name (noticers nil) (enumerated-domain t) (enumerated-antidomain nil) value (possibly-integer? t) (possibly-noninteger-real? t) (possibly-nonreal-number? t) (possibly-boolean? t) (possibly-nonboolean-nonnumber? t) (lower-bound nil) (upper-bound nil))

What needs to change: Macro call that should be transformed by defstruct-compile-time

(defstruct-compile-time (variable (:print-function print-variable) (:predicate variable?) (:constructor make-variable-internal)) name (noticers nil) (enumerated-domain t) (enumerated-antidomain nil) value (possibly-integer? t) (possibly-noninteger-real? t) (possibly-nonreal-number? t) (possibly-boolean? t) (possibly-nonboolean-nonnumber? t) (lower-bound nil) (upper-bound nil))

[Assistant]
(defmacro defstruct-compile-time (options &body items)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (defstruct ,options ,@items)))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (defstruct (variable (:print-function print-variable) (:predicate variable?) (:constructor make-variable-internal)) name (noticers nil) (enumerated-domain t) (enumerated-antidomain nil) value (possibly-integer? t) (possibly-noninteger-real? t) (possibly-nonreal-number? t) (possibly-boolean? t) (possibly-nonboolean-nonnumber? t) (lower-bound nil) (upper-bound nil)))


[User]
Define a macro that eliminates this repetitive pattern:
(cond-> 'some-name)

Issue: Macro call that should be transformed by COND->

(cond-> 'some-name)

[Assistant]
(defmacro COND-> ...)

;; macroexpand:
(let* ((#:g140 'some-name))
  #:g140)


[User]
Write a Common Lisp macro to handle this code pattern:
(emit nil)

Problem: Macro call that should be transformed by EMIT

(emit nil)

[Assistant]
(defmacro EMIT ...)

;; macroexpand:
(let ((#:ast181 nil))
  (progn
   (assert (typep #:ast181 'delayed-emitting) nil
           "Something went awry around the quasi quoted stuff, EMIT got a ~S."
           #:ast181)
   (funcall #:ast181)))


[User]
Define a macro that eliminates this repetitive pattern:
(define-custom-var (:array-type *json-array-type*) 'vector "The Lisp sequence type to which JSON Arrays are to be coerced.")

Issue: Macro call that should be transformed by define-custom-var

(define-custom-var (:array-type *json-array-type*) 'vector "The Lisp sequence type to which JSON Arrays are to be coerced.")

[Assistant]
(defmacro define-custom-var ((key name) &rest other-args)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (progn (pushnew '(,name . ,key) *custom-vars* :test #'equal)
            (defvar ,name ,@other-args))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (progn (pushnew (quote (*json-array-type* . :array-type)) *custom-vars* :test (function equal)) (defvar *json-array-type* (quote vector) "The Lisp sequence type to which JSON Arrays are to be coerced.")))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(define-modf-rewrite funcall (expr) (cons (cadadr expr) (cddr expr)))

Write a macro that addresses: Macro call that should be transformed by define-modf-rewrite

(define-modf-rewrite funcall (expr) (cons (cadadr expr) (cddr expr)))

[Assistant]
(defmacro define-modf-rewrite (name (expr) &body body)
  "Define a new rewrite rule.  If a form starting with NAME is encountered, call
the defined function to return a form that we can deal with (i.e. one defined
via DEFINE-MODF-EXPANDER, DEFINE-MODF-FUNCTION, and DEFINE-MODF-METHOD)."
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf (gethash ',name *modf-rewrites*)
           (lambda (,expr)
             ,@body))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash (quote funcall) *modf-rewrites*) (lambda (expr) (cons (cadadr expr) (cddr expr)))))


[User]
Generate a defmacro form that transforms code like this:
(c? (when (< (depth self) 4) (loop repeat (1+ (depth self)) collecting (make-kid 'bftree :depth (1+ (depth self))))))

Pattern to recognize: Macro call that should be transformed by c?

(c? (when (< (depth self) 4) (loop repeat (1+ (depth self)) collecting (make-kid 'bftree :depth (1+ (depth self))))))

[Assistant]
(defmacro c? (&body body)
  `(make-c-dependent
    :code ',body
    :value-state :unevaluated
    :rule (c-lambda ,@body)))

;; macroexpand:
(make-c-dependent :code (quote ((when (< (depth self) 4) (loop repeat (1+ (depth self)) collecting (make-kid (quote bftree) :depth (1+ (depth self))))))) :value-state :unevaluated :rule (c-lambda (when (< (depth self) 4) (loop repeat (1+ (depth self)) collecting (make-kid (quote bftree) :depth (1+ (depth self)))))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(do-generators ((a (repeat 2)) (:list b '(4 5 6)) (c (list->generator '(8 9)) :fill-value 30)) (print (* a (+ b c))))

What needs to change: Macro call that should be transformed by do-generators

(do-generators ((a (repeat 2)) (:list b '(4 5 6)) (c (list->generator '(8 9)) :fill-value 30)) (print (* a (+ b c))))

[Assistant]
(defmacro do-generators (genspecs &body body)
  "Simultaneously iterate through multiple generators at once. By default
do-generators terminates when the shortest generator ends, but individual
generators can be padded out with the :fill-value keyword. Do-generators can
also iterate over lists in parallel with generators. To use lists, start the genspec with the :list keyword. Eg:
  (do-generators ((a (repeat 2))
			 (:list b '(4 5 6))
			 (c (list->generator '(8 9)) :fill-value 30))
	   (print (* a (+ b c))))
24
28
72
NIL"
  (let ((genspecs (mapcar #'proc-list-spec genspecs))
	(genr (gensym))
	(data (gensym))
	(sig (gensym)))
    (multiple-value-bind (varnames specs)
	(process-genspecs genspecs)

      `(let ((,genr (multi-gen ,@specs)))
	 (loop do
	   (destructuring-bind (,sig . ,data)
	       (multiple-value-list (next-generator-value ,genr))
	     (unless ,sig
	       (return))
	     ,(bind-clause data varnames body)))))))

;; macroexpand:
(let ((#:g126 (multi-gen (repeat 2) (list->generator (quote (4 5 6))) (list (list->generator (quote (8 9))) :fill-value 30)))) (loop do (destructuring-bind (#:g128 . #:g127) (multiple-value-list (next-generator-value #:g126)) (unless #:g128 (return)) (let ((a (elt (elt #:g127 0) 0)) (b (elt (elt #:g127 1) 0)) (c (elt (elt #:g127 2) 0))) (print (* a (+ b c)))))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(with-yield
  nil)

What needs to change: Macro call that should be transformed by WITH-YIELD

(with-yield
  nil)

[Assistant]
(defmacro WITH-YIELD ...)

;; macroexpand:
(isolate-cont
  (enable-yield
    nil
    nil))


[User]
Write a Common Lisp macro to handle this code pattern:
(defmacro/ps nil
    :key
  nil)

Problem: Macro call that should be transformed by DEFMACRO/PS

(defmacro/ps nil
    :key
  nil)

[Assistant]
(defmacro DEFMACRO/PS ...)

;; macroexpand:
(progn (defmacro nil :key nil) (import-macros-from-lisp 'nil))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(ψ nil (progn))

Write a macro that addresses: Macro call that should be transformed by Ψ

(ψ nil (progn))

[Assistant]
(defmacro Ψ ...)

;; macroexpand:
(mapcar (λ (progn)) nil)


[User]
Generate a defmacro form that transforms code like this:
(defconstant +newline+ (make-string 1 :initial-element #\Newline) "Used for indentation.")

Pattern to recognize: Macro call that should be transformed by defconstant

(defconstant +newline+ (make-string 1 :initial-element #\Newline) "Used for indentation.")

[Assistant]
(defmacro defconstant (name value &optional doc)
  "Make sure VALUE is evaluated only once \(to appease SBCL & clasp)."
  `(cl:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
     ,@(when doc (list doc))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (sb-impl::%defconstant (quote +newline+) (make-string 1 :initial-element #\Newline) (sb-c:source-location) (quote "Used for indentation.")))


[User]
Write a Common Lisp macro to handle this code pattern:
(when (not (slot-value (node-slot parameters) 'nodes)) (format stream "void"))

Problem: Macro call that should be transformed by when

(when (not (slot-value (node-slot parameters) 'nodes)) (format stream "void"))

[Assistant]
(defmacro when (test &body forms)
  `(if ,test
	   ,(cl:if (cadr forms)
			   `(progn ,@forms)
			   (car forms))))

;; macroexpand:
(if (not (slot-value (node-slot parameters) (quote nodes))) (format stream "void"))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(do+ (with (x 1)) (terminate nil x))

Write a macro that addresses: Macro call that should be transformed by do+

(do+ (with (x 1)) (terminate nil x))

[Assistant]
(defmacro do+ (&body body)
  "High-level, extensible iteration construct. Refer to the manual for syntax and semantics."
  `(do+/internal nil ,@body))

;; macroexpand:
(do+/internal nil (with (x 1)) (terminate nil x))


[User]
Generate a defmacro form that transforms code like this:
(with-output-to-file (output to :element-type element-type :if-exists if-to-exists) (copy-stream input output :element-type element-type :finish-output finish-output))

Pattern to recognize: Macro call that should be transformed by with-output-to-file

(with-output-to-file (output to :element-type element-type :if-exists if-to-exists) (copy-stream input output :element-type element-type :finish-output finish-output))

[Assistant]
(defmacro with-output-to-file ((stream-name file-name &rest args
                                            &key (direction nil direction-p)
                                            &allow-other-keys)
			       &body body)
  "Evaluate BODY with STREAM-NAME to an output stream on the file
FILE-NAME. ARGS is sent as is to the call to OPEN except EXTERNAL-FORMAT,
which is only sent to WITH-OPEN-FILE when it's not NIL."
  (declare (ignore direction))
  (when direction-p
    (error "Can't specify :DIRECTION for WITH-OUTPUT-TO-FILE."))
  `(with-open-file* (,stream-name ,file-name :direction :output ,@args)
     ,@body))

;; macroexpand:
(with-open-file* (output to :direction :output :element-type element-type :if-exists if-to-exists) (copy-stream input output :element-type element-type :finish-output finish-output))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(with-foreign-pointer-as-string ((buf buf-size) 255) (foreign-funcall "snprintf" :pointer buf :int buf-size :string "%d %f #x%x!" :int 666 :double (coerce pi 'double-float) :unsigned-int #xcafebabe :void))

What needs to change: Macro call that should be transformed by with-foreign-pointer

(with-foreign-pointer-as-string ((buf buf-size) 255) (foreign-funcall "snprintf" :pointer buf :int buf-size :string "%d %f #x%x!" :int 666 :double (coerce pi 'double-float) :unsigned-int #xcafebabe :void))

[Assistant]
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
  "Bind 'var to 'size bytes of foreign memory during 'body.  The
  pointer in 'var is invalid beyond the dynamic extent of 'body, and
  may be stack-allocated if supported by the implementation.  If
  'size-var is supplied, it will be bound to 'size during 'body."
  (unless size-var
    (setf size-var (gensym (symbol-name '#:size))))
  ;; If the size is constant we can stack-allocate.
  (cond ((constantp size)
         (let ((alien-var (gensym (symbol-name '#:alien))))
           `(with-alien ((,alien-var (array (unsigned 8) ,(eval size))))
             (let ((,size-var ,size)
                   (,var (alien-sap ,alien-var)))
               (declare (ignorable ,size-var))
               ,@body))))
        (t
         `(let ((,size-var ,size))
            (alien:with-bytes (,var ,size-var)
              ,@body)))))

;; macroexpand:
(with-foreign-pointer-as-string ((buf buf-size) 255) (foreign-funcall "snprintf" :pointer buf :int buf-size :string "%d %f #x%x!" :int 666 :double (coerce pi (quote double-float)) :unsigned-int 3405691582 :void))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-alist-cache content-type-cache)

What needs to change: Macro call that should be transformed by define-alist-cache

(define-alist-cache content-type-cache)

[Assistant]
(defmacro define-alist-cache (cache-name)
  (let ((var (intern (format nil "*~A*" cache-name))))
  `(progn
     (defvar ,var)
     (defun ,(intern (format nil "LOOKUP-IN-~A" cache-name)) (elt)
       (when (boundp ',var)
         (alexandria:assoc-value ,var elt)))
     (defun (setf ,(intern (format nil "LOOKUP-IN-~A" cache-name))) (val elt)
       (when (boundp ',var)
         (setf (alexandria:assoc-value ,var elt) val))
       val))))

;; macroexpand:
(progn (defvar *content-type-cache*) (defun lookup-in-content-type-cache (elt) (when (boundp (quote *content-type-cache*)) (assoc-value *content-type-cache* elt))) (defun (setf lookup-in-content-type-cache) (val elt) (when (boundp (quote *content-type-cache*)) (setf (assoc-value *content-type-cache* elt) val)) val))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(with-cached-reader-conditionals
  nil
  :key
  nil)

Write a macro that addresses: Macro call that should be transformed by WITH-CACHED-READER-CONDITIONALS

(with-cached-reader-conditionals
  nil
  :key
  nil)

[Assistant]
(defmacro WITH-CACHED-READER-CONDITIONALS ...)

;; macroexpand:
(call-with-cached-reader-conditionals (lambda () nil :key nil))


[User]
Define a macro that eliminates this repetitive pattern:
(action (:before node-direct-application node new-subs) (when (find (node-direct-application-rator node) subs :key #'ast-substitution-from) (util:coalton-bug "Failure to apply ast substitution on variable ~A to node-direct-application" (node-direct-application-rator node))) (alexandria:when-let ((res (find (node-direct-application-rator node) new-subs :key #'ast-substitution-from))) (make-node-direct-application :type (node-type node) :properties (node-properties node) :rator-type (node-direct-application-rator-type node) :rator (node-variable-value (ast-substitution-to res)) :rands (node-direct-application-rands node) :keyword-rands (node-direct-application-keyword-rands node))))

Issue: Macro call that should be transformed by action

(action (:before node-direct-application node new-subs) (when (find (node-direct-application-rator node) subs :key #'ast-substitution-from) (util:coalton-bug "Failure to apply ast substitution on variable ~A to node-direct-application" (node-direct-application-rator node))) (alexandria:when-let ((res (find (node-direct-application-rator node) new-subs :key #'ast-substitution-from))) (make-node-direct-application :type (node-type node) :properties (node-properties node) :rator-type (node-direct-application-rator-type node) :rator (node-variable-value (ast-substitution-to res)) :rands (node-direct-application-rands node) :keyword-rands (node-direct-application-keyword-rands node))))

[Assistant]
(defmacro action ((when type &rest args) &body body)
  "Construct an action block, turning `body` into a lambda function
accepting `args` if `args` are provided. If there are no `args`, then
`body` is assumed to be a function object and is used directly with
`when` and `type` to create an `action` instance. Otherwise, the first
argument in `args` is declared to be a node of type `type`, and the
`args` and `body` are used to generate a lambda function."
  (check-type when keyword)
  (check-type type symbol)
  (assert (subtypep type 'node))
  (assert (or (not (endp args)) (= 1 (length body))))
  (if (endp args)
      `(make-action ',when ',type ,@body)
      `(make-action ',when ',type
                    (lambda (,@args)
                      (declare (type ,type ,(first args)))
                      ,@body))))

;; macroexpand:
(make-action (quote :before) (quote node-direct-application) (lambda (node new-subs) (declare (type node-direct-application node)) (when (find (node-direct-application-rator node) subs :key (function ast-substitution-from)) (util:coalton-bug "Failure to apply ast substitution on variable ~A to node-direct-application" (node-direct-application-rator node))) (alexandria:when-let ((res (find (node-direct-application-rator node) new-subs :key (function ast-substitution-from)))) (make-node-direct-application :type (node-type node) :properties (node-properties node) :rator-type (node-direct-application-rator-type node) :rator (node-variable-value (ast-substitution-to res)) :rands (node-direct-application-rands node) :keyword-rands (node-direct-application-keyword-rands node)))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(make-stream-method pp-xml-value (s value &optional colon-p at-p) (declare (ignore colon-p at-p)) (format s "~A" value))

What needs to change: Macro call that should be transformed by make-stream-method

(make-stream-method pp-xml-value (s value &optional colon-p at-p) (declare (ignore colon-p at-p)) (format s "~A" value))

[Assistant]
(defmacro make-stream-method (name (s &rest args) &body body)
  `(progn
     (defmethod ,name ((,s stream) ,@args)
       ,@body)
     #+abcl
     (defmethod ,name ((,s xp::xp-structure) ,@args)
       ,@body)))

;; macroexpand:
(progn (defmethod pp-xml-value ((s stream) value &optional colon-p at-p) (declare (ignore colon-p at-p)) (format s "~A" value)))


[User]
Write a Common Lisp macro to handle this code pattern:
(with-cache ("none" :expire 2 :store storage) (error "SHOULD BE ERROR"))

Problem: Macro call that should be transformed by with-cache

(with-cache ("none" :expire 2 :store storage) (error "SHOULD BE ERROR"))

[Assistant]
(defmacro with-cache ((key &key store expire) &body body)
  "If a cache indicated by KEY exists, this just returns the cache
value without evaluating BODY. Otherwise, this evaluates BODY and
stores the evaluated value into STORE with KEY and EXPIRE. KEY is a
form that an evaluated value indicates the cache key.

Example:

    (defun f (x)
      (with-cache (x *store*)
        (very-complex-computation x)))"
  (once-only (key store expire)
    (with-gensyms (value exists-p)
      `(multiple-value-bind (,value ,exists-p)
           (getcache ,key ,store)
         (if ,exists-p
             ,value
             (let ((,value (progn ,@body)))
               (setcache ,key ,value ,store :expire ,expire)
               ,value))))))

;; macroexpand:
(let ((#:key262 "none") (#:store263 storage) (#:expire264 2)) (multiple-value-bind (#:value265 #:exists-p266) (getcache #:key262 #:store263) (if #:exists-p266 #:value265 (let ((#:value265 (progn (error "SHOULD BE ERROR")))) (setcache #:key262 #:value265 #:store263 :expire #:expire264) #:value265))))


[User]
Generate a defmacro form that transforms code like this:
(define-custom-var (:end-of-array *end-of-array-handler*))

Pattern to recognize: Macro call that should be transformed by define-custom-var

(define-custom-var (:end-of-array *end-of-array-handler*))

[Assistant]
(defmacro define-custom-var ((key name) &rest other-args)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (progn (pushnew '(,name . ,key) *custom-vars* :test #'equal)
            (defvar ,name ,@other-args))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (progn (pushnew (quote (*end-of-array-handler* . :end-of-array)) *custom-vars* :test (function equal)) (defvar *end-of-array-handler*)))


[User]
Generate a defmacro form that transforms code like this:
(if-it (mismatch prefix string :test test :start2 start) (= it (length prefix)) t)

Pattern to recognize: Macro call that should be transformed by if-it

(if-it (mismatch prefix string :test test :start2 start) (= it (length prefix)) t)

[Assistant]
(defmacro if-it (test then &optional else)
  "Like IF. IT is bound to TEST."
  `(let ((it ,test))
     (if it ,then ,else)))

;; macroexpand:
(let ((it (mismatch prefix string :test test :start2 start))) (if it (= it (length prefix)) t))


[User]
Write a Common Lisp macro to handle this code pattern:
(with-decoder-simple-list-semantics (let ((good-symbols "{\"car\":1,\"cdr\":2}") (bad-symbols "{\"could-be\":1,\"a-denial-of-service-attack\":2}") (*json-symbols-package* (find-package :cl)) (*identifier-name-to-key* #'safe-json-intern)) (is (equal '((car . 1) (cdr . 2)) (decode-json-from-string good-symbols))) (signals unknown-symbol-error (decode-json-from-string bad-symbols))))

Problem: Macro call that should be transformed by with-decoder-simple-list-semantics

(with-decoder-simple-list-semantics (let ((good-symbols "{\"car\":1,\"cdr\":2}") (bad-symbols "{\"could-be\":1,\"a-denial-of-service-attack\":2}") (*json-symbols-package* (find-package :cl)) (*identifier-name-to-key* #'safe-json-intern)) (is (equal '((car . 1) (cdr . 2)) (decode-json-from-string good-symbols))) (signals unknown-symbol-error (decode-json-from-string bad-symbols))))

[Assistant]
(defmacro with-decoder-simple-list-semantics (&body body)
  "Execute BODY in a dynamic environement where the decoder semantics
is such as set by SET-DECODER-SIMPLE-LIST-SEMANTICS."
  `(with-shadowed-custom-vars
     (set-decoder-simple-list-semantics)
     ,@body))

;; macroexpand:
(with-shadowed-custom-vars (set-decoder-simple-list-semantics) (let ((good-symbols "{\"car\":1,\"cdr\":2}") (bad-symbols "{\"could-be\":1,\"a-denial-of-service-attack\":2}") (*json-symbols-package* (find-package :cl)) (*identifier-name-to-key* (function safe-json-intern))) (is (equal (quote ((car . 1) (cdr . 2))) (decode-json-from-string good-symbols))) (signals unknown-symbol-error (decode-json-from-string bad-symbols))))


[User]
Create a Common Lisp macro for the following transformation. Before code:
(letrec ((x 1) (y (lambda () y))) (is (functionp y)) (is (functionp (funcall y))) (is (numberp x)))

What needs to change: Macro call that should be transformed by letrec

(letrec ((x 1) (y (lambda () y))) (is (functionp y)) (is (functionp (funcall y))) (is (numberp x)))

[Assistant]
(defmacro letrec ((&rest bindings) &body body)
  "Recursive LET.
The idea is that functions created in BINDINGS can close over one
another, and themselves.

Note that `letrec' only binds variables: it can define recursive
functions, but can't bind them as functions. (But see `fbindrec'.)"
  `(letrec-with psetq ,bindings
     ,@body))

;; macroexpand:
(letrec-with psetq ((x 1) (y (lambda nil y))) (is (functionp y)) (is (functionp (funcall y))) (is (numberp x)))


[User]
Generate a defmacro form that transforms code like this:
(define-generic generic (a b &key c) (declare (optimize speed (space 2))) (declare (ignorable a b c)) (+ a b c))

Pattern to recognize: Macro call that should be transformed by define-generic

(define-generic generic (a b &key c) (declare (optimize speed (space 2))) (declare (ignorable a b c)) (+ a b c))

[Assistant]
(defmacro define-generic (name (&rest arglist) &body body)
  "Convenience macro to define generics as if they were methods.
ARGLIST can be a method arglist, in which case it's parsed into
generic function arglist by removing method-specific args.

BODY can be a list of `defgeneric' options (processed as-is, even
:method ones) intermixed with other Lisp forms:
- If there's a docstring as the first form, it's processed into
  :documentation option of `defgeneric'.
- If there are non-option forms, they are put together into a separate
  :method option under ARGLIST.
- If there's a `declare' form:
  - If it's generic-friendly (optimize for speed or space), then it's
    put into both generic body and :method body (if any).
  - Otherwise it's only put into :method (creating it if necessary).
- If there's an `:export-generic-name-p' boolean option, export (T) or
  don't export (NIL) the generic symbol.

Example:

\(define-generic add ((a integer) (b integer) &key coerce-to-fixnum &allow-other-keys)
  \"Adds A and B, coercing them to fixnum if the sum is too big.\"
  (if coerce-to-fixnum
      (coerce (+ a b) 'fixnum)
      (+ a b))
  (:method ((a string) (b integer))
   (error \"Cannot use `add' on strings!\")))
=>
\(defgeneric add (a b &key &allow-other-keys)
  (:method ((a integer) (b integer) &key coerce-to-fixnum &allow-other-keys)
   (if coerce-to-fixnum
      (coerce (+ a b) 'fixnum)
      (+ a b)))
  (:method ((a string) (b integer))
   (error \"Cannot use `add' on strings!\"))
  (:documentation \"Adds A and B, coercing them to fixnum if the sum is too big.\"))"
  (multiple-value-bind (body declarations documentation)
      (uiop:parse-body body :documentation t)
    (when (and (= 1 (length body))
               (stringp (first body)))
      (style-warn "Body of DEFINE-GENERIC contains a single string:
~s.
It's interpreted as a method body by default.

If you meant this string to be a generic docstring, and not a method
body, add an explicit NIL or some other body form:
(define-generic name (arg1 arg2)
  \"Docstring\"
  'body-form)

If you meant it as a body form, do nothing, or provide explicit
documentation or any other option:
(define-generic name (arg1 arg2)
  \"Docstring\"
  (:documentation \"Real docstring\"))" (first body)))
    (let* ((generic-declarations (remove-if (lambda (d)
                                              (or (> (length d) 2)
                                                  (not (eq 'optimize (first (second d))))
                                                  (notevery (lambda (o)
                                                              (let ((feature (first (uiop:ensure-list o))))
                                                                (or (eq feature 'speed)
                                                                    (eq feature 'space))))
                                                            (rest (second d)))))
                                            declarations))
           (options (remove-if-not (lambda (form)
                                     (keywordp (first (uiop:ensure-list form))))
                                   body))
           (method-body (remove-if (lambda (f) (member f options :test #'equal)) body))
           (export-generic-name-p (find :export-generic-name-p options :key #'first))
           (options (remove export-generic-name-p options :test #'equal))
           (export-p (if export-generic-name-p
                         (second export-generic-name-p)
                         *export-generic-name-p*))
           (generalized-arglist (generalize-arglist arglist)))
      (when (and (not (equal generalized-arglist arglist))
                 (every #'null (list method-body options)))
        (style-warn "Specialized arglist used without method body in define-generic: ~a" arglist))
      `(prog1
           (defgeneric ,name ,generalized-arglist
             ,@generic-declarations
             ,@(when (or method-body
                         (not (equal generic-declarations
                                     declarations)))
                 `((:method ,arglist
                     ,@declarations
                     ,@method-body)))
             ,@options
             ,@(when documentation
                 `((:documentation ,documentation))))
         ;; FIXME: Maybe only export if package of generic function name
         ;; matches *PACKAGE*?
         ,@(when export-p
             `((eval-when (:compile-toplevel :load-toplevel :execute)
                 (export ',name ,(package-name *package*)))))
         ,@(let ((documentation (or documentation
                                    (second (first (member :documentation options :key #'first))))))
             (when documentation
               `((setf (documentation ',name 'function) ,documentation)
                 (setf (documentation (fdefinition ',name) 'function) ,documentation))))))))

;; macroexpand:
(prog1 (defgeneric generic (a b &key c) (declare (optimize speed (space 2))) (:method (a b &key c) (declare (optimize speed (space 2))) (declare (ignorable a b c)) (+ a b c))))


[User]
Write a Common Lisp macro to handle this code pattern:
(declare-deprecated-operators nil)

Problem: Macro call that should be transformed by DECLARE-DEPRECATED-OPERATORS

(declare-deprecated-operators nil)

[Assistant]
(defmacro DECLARE-DEPRECATED-OPERATORS ...)

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (define-compiler-macro nil
      (&whole form &rest arguments)
    (declare (ignore arguments))
    (let ((where-from (or *compile-file-truename* *load-truename*)))
      (when *deprecation-warnings*
        (warn 'deprecation-warning :operator-name 'nil :source-file where-from
              :source-form form))
      (when where-from
        (pushnew where-from (gethash 'nil *deprecation-locations*) :test
                 #'equalp))
      form))
  (values))


[User]
Define a macro that eliminates this repetitive pattern:
(defjsmacro nil :key nil)

Issue: Macro call that should be transformed by DEFJSMACRO

(defjsmacro nil :key nil)

[Assistant]
(defmacro DEFJSMACRO ...)

;; macroexpand:
(defpsmacro nil
    :key
  nil)


[User]
Create a Common Lisp macro for the following transformation. Before code:
(define-modf-rewrite seventh (expr) `(caddr (cddddr ,(second expr))))

What needs to change: Macro call that should be transformed by define-modf-rewrite

(define-modf-rewrite seventh (expr) `(caddr (cddddr ,(second expr))))

[Assistant]
(defmacro define-modf-rewrite (name (expr) &body body)
  "Define a new rewrite rule.  If a form starting with NAME is encountered, call
the defined function to return a form that we can deal with (i.e. one defined
via DEFINE-MODF-EXPANDER, DEFINE-MODF-FUNCTION, and DEFINE-MODF-METHOD)."
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf (gethash ',name *modf-rewrites*)
           (lambda (,expr)
             ,@body))))

;; macroexpand:
(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash (quote seventh) *modf-rewrites*) (lambda (expr) (sb-int:quasiquote (caddr (cddddr #S(sb-impl::comma :expr (second expr) :kind 0)))))))


[User]
Define a macro that eliminates this repetitive pattern:
(*> (string "!!!") (take-until (char #\')))

Issue: Macro call that should be transformed by *>

(*> (string "!!!") (take-until (char #\')))

[Assistant]
(defmacro *> (parser &rest parsers)
  "Combination of parsers yielding the result of the rightmost one."
  (let ((offset (gensym "*>-OFFSET")))
    `(lambda (,offset)
       ,(reduce (lambda (i p)
                  (let ((res  (gensym "*>-RES"))
                        (next (gensym "*>-NEXT")))
                    `(multiple-value-bind (,res ,next) ,i
                       (if (ok? ,res)
                           (funcall ,p ,next)
                           (fail ,next)))))
                parsers
                :initial-value `(funcall ,parser ,offset)))))

;; macroexpand:
(lambda (#:*>-offset122) (multiple-value-bind (#:*>-res123 #:*>-next124) (funcall (string "!!!") #:*>-offset122) (if (ok? #:*>-res123) (funcall (take-until (char #\APOSTROPHE)) #:*>-next124) (fail #:*>-next124))))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(dlet nil
  nil)

Write a macro that addresses: Macro call that should be transformed by DLET

(dlet nil
  nil)

[Assistant]
(defmacro DLET ...)

;; macroexpand:
(dynamic-let nil
  nil)


[User]
Define a macro that eliminates this repetitive pattern:
(with-rules nil
  (progn))

Issue: Macro call that should be transformed by WITH-RULES

(with-rules nil
  (progn))

[Assistant]
(defmacro WITH-RULES ...)

;; macroexpand:
(dolist (nil (alexandria:hash-table-keys cl-rules.core::*rules*)) (progn))


[User]
You are a Common Lisp macro expert. Given this code pattern:
(when (node-slot initializer) (make-proxy initializer initializer))

Write a macro that addresses: Macro call that should be transformed by when

(when (node-slot initializer) (make-proxy initializer initializer))

[Assistant]
(defmacro when (test &body forms)
  `(if ,test
	   ,(cl:if (cadr forms)
			   `(progn ,@forms)
			   (car forms))))

;; macroexpand:
(if (node-slot initializer) (make-proxy initializer initializer))