Version 4 of docstring

Updated 2004-11-18 09:53:50 by suchenwi

if 0 {Richard Suchenwirth 2004-01-25 - Languages like Lisp and Python have the docstring feature, where a string in the beginning of a function can be retrieved for on-line (or printed) documentation. Tcl doesn't have this mechanism built-in (and it would be hard to do it exactly the same way, because everything is a string), but a similar mechanism can easily be adopted, and it doesn't look bad in comparison:

  • Common Lisp: (documentation 'foo 'function)
  • Python: foo.__doc__
  • Tcl: docstring foo

If the docstring is written in comments at the top of a proc body, it is easy to parse it out. In addition, for all procs, even without docstring, you get the "signature" (proc name and arguments with defaults). The code below also serves as usage example: }

 proc docstring procname {
    # reports a proc's args and leading comments.
    # Multiple documentation lines are allowed.
    set res "{usage: $procname [args $procname]}"
    # This comment should not appear in the docstring
    foreach line [split [info body $procname] \n] {
        if {[string trim $line] eq ""} continue
        if ![regexp {\s*#(.+)} $line -> line] break
        lappend res [string trim $line]
    }
    join $res \n
 }
 proc args procname {
    # Signature of a proc: arguments with defaults
    set res ""
    foreach a [info args $procname] {
        if [info default $procname $a default] {
            lappend a $default
        }
        lappend res $a
    }
    set res
 }

if 0 {Testing:

 % docstring docstring
 usage: docstring procname
 reports a proc's args and leading comments.
 Multiple documentation lines are allowed.

.

 % docstring args
 usage: args procname
 Signature of a proc: arguments with defaults

}


Arts and crafts of Tcl-Tk programming