yonh
yonh

Reputation: 73

How can I view the definition of a function in lisp (sbcl)?

I use sbcl+emacs+slime.
I writing a function in lisp, I use C-c C-c compile, but i've already deleted it.
I can't find it. I want to know how I define it.

I tried use function-lambda-expression, but I get this:

(function-lambda-expression #'b)
T
B

I hope someone can give me some help.Thanks very much in advance!


Thanks Vsevolod. If function define in repl, i can use (descri #'function-name) get how i define the function, but if i through C-c C-c define it, i just get source file

My attempt

Upvotes: 7

Views: 4407

Answers (2)

c2d7fa
c2d7fa

Reputation: 11

As already pointed out, (describe #'b) can be used to print a description of the function that includes its source form, and (function-lambda-expression #'b) can be used to retrieve the definition directly as a value.

For these functions to work, however, the source form of b must have been saved. For SBCL, this is guaranteed to happen when the debug policy is set to 2 or higher, or when sb-c:store-source-form is set to 3. When sb-c:store-source-form is set to 1, then the source form is saved sometimes and other times not. Notably, the defaults (in my instance of SBCL 2.5.0 at least) are (debug 1) and (sb-c:store-source-form 1), which means that source forms are sometimes saved and sometimes not.

Thus, if you want to guarantee that the source form of any function can be inspected, you can use either of these top-level declarations:

(declaim (optimize sb-c:store-source-form))
(declaim (optimize (debug 2))

Or, for a single function:

(defun b ()
  (declare (optimize sb-c:store-source-form))
  (format t "hello from b~%"))

Then the source code can be inspected:

(describe #'b)
(function-lambda-expression #'b)

Notes:

  • For the effects of (optimize (debug n)), see https://www.sbcl.org/manual/#Debugger-Policy-Control.
  • Use (sb-ext:describe-compiler-policy) to see the currently active declarations.
  • The notation (declare (optimize x)) is simply an abbreviation for (declare (optimize (x 3)).
  • I could not find any user-facing documentation for sb-c:store-source-form, but a comment in the source code explains: If compiling to a file, we only store sources if the STORE-SOURCE quality value is 3. If to memory, any nonzero value will do.

Upvotes: 1

Vsevolod Dyomkin
Vsevolod Dyomkin

Reputation: 9451

Depending on your settings for debug and optimization you may be able to get it via describe:

CL-USER> (defun f (a) (print a))
F
CL-USER> (describe #'f)
#<FUNCTION F>
  [compiled function]

Lambda-list: (A)
Derived type: (FUNCTION (T) (VALUES T &OPTIONAL))
Source form:
  (SB-INT:NAMED-LAMBDA F
      (A)
    (BLOCK F (PRINT A)))

You can see the definition here in the Source form part.

Upvotes: 13

Related Questions