[plt-scheme] How to get the source of procedure?

From: Dave Herman (dherman at ccs.neu.edu)
Date: Tue May 16 04:45:54 EDT 2006

Here is a module that defines a special lambda form that allows you to 
create a procedure with a documentation string and its source code 
represented as an S-expression.

Let me warn you about the perils of source code inspection, though. In 
JavaScript, you can access the source code of any function as a string. 
As a result, the browser vendors get bug reports every time they make 
even the slightest changes to the implementation of any function: users 
have written programs that rely on the exact representation of the 
source code, so changes to the implementation break the users' code -- 
sometimes even as mundane as whitespace changes! The situation is only 
marginally better with an S-expression representation.

Executive summary: violate abstraction boundaries, and you'll get what 
you deserve. :)

I'll add this to the Scheme Cookbook.

Dave

;; --

(module doc-lambda mzscheme
   (define-values (struct:doc-lambda make-doc-lambda doc-lambda? 
doc-lambda-ref doc-lambda-set!)
     (make-struct-type 'doc-lambda #f 3 0 #f null #f 0))

   (define doc-lambda-proc (make-struct-field-accessor doc-lambda-ref 0 
'proc))
   (define doc-lambda-doc (make-struct-field-accessor doc-lambda-ref 1 
'doc))
   (define doc-lambda-src (make-struct-field-accessor doc-lambda-ref 2 
'src))

   (define (procedure-doc x)
     (and (doc-lambda? x)
          (doc-lambda-doc x)))

   (define (procedure-source x)
     (and (doc-lambda? x)
          (doc-lambda-src x)))

   (define-syntax doc-lambda
     (syntax-rules ()
       [(_ doc-string args body0 body1 ...)
        (let ([doc-string-v doc-string])
          (make-doc-lambda
           (lambda args body0 body1 ...)
           doc-string-v
           `(doc-lambda ,doc-string-v args body0 body1 ...)))]))

   (provide doc-lambda procedure-doc procedure-source))

;; --

Dave



Posted on the users mailing list.