Documentation

From Rosetta Code

Jump to: navigation, search
Documentation is a programming task. Visitors like you are encouraged to solve it according to the task description, using any language they may happen to know.
Add to BlogMarksAdd to del.icio.usAdd to diggAdd to NewsvineAdd to redditAdd to Slashdot
Show how to insert documentation for classes, functions, and/or variables in your language. If this documentation is built-in to the language, note it. If this documentation requires external tools, note them.

Contents

[edit] Clojure

(def 
#^{:doc "Metadata can contain documentation and can be added to vars like this."}
test1)
 
(defn test2
"defn and some other macros allow you add documentation like this. Works the same way"
[])

[edit] Eiffel

The Eiffel language was designed with a goal of producing documentation directly from software text. Certain comments, contracts for publicly accessible routines, and the class invariant are all extracted into the documentation views of a class.

The following is a simple class written in Eiffel:

note
description: "Objects that model Times of Day: 00:00:00 - 23:59:59"
author: "Eiffel Software Construction Students"
 
class
TIME_OF_DAY
create
make
 
feature -- Initialization
 
make
-- Initialize to 00:00:00
do
hour := 0
minute := 0
second := 0
ensure
initialized: hour = 0 and
minute = 0 and
second = 0
end
 
feature -- Access
 
hour: INTEGER
-- Hour expressed as 24-hour value
 
minute: INTEGER
-- Minutes past the hour
 
second: INTEGER
-- Seconds past the minute
 
feature -- Element change
 
set_hour (h: INTEGER)
-- Set the hour from `h'
require
argument_hour_valid: 0 <= h and h <= 23
do
hour := h
ensure
hour_set: hour = h
minute_unchanged: minute = old minute
second_unchanged: second = old second
end
 
set_minute (m: INTEGER)
-- Set the minute from `m'
require
argument_minute_valid: 0 <= m and m <= 59
do
minute := m
ensure
minute_set: minute = m
hour_unchanged: hour = old hour
second_unchanged: second = old second
end
 
set_second (s: INTEGER)
-- Set the second from `s'
require
argument_second_valid: 0 <= s and s <= 59
do
second := s
ensure
second_set: second = s
hour_unchanged: hour = old hour
minute_unchanged: minute = old minute
end
 
feature {NONE} -- Implementation
 
protected_routine
-- A protected routine (not available to client classes)
-- Will not be present in documentation (Contract) view
do
 
end
 
invariant
 
hour_valid: 0 <= hour and hour <= 23
minute_valid: 0 <= minute and minute <= 59
second_valid: 0 <= second and second <= 59
 
end -- class TIME_OF_DAY

Below is the Contract (documentation) view of the same class. It is the view that potential reuse consumers would reference when writing clients.

note
description: "Objects that model Times of Day: 00:00:00 - 23:59:59"
author: "Eiffel Software Construction Students"
 
class interface
TIME_OF_DAY
 
create
make
 
feature -- Initialization
 
make
-- Initialize to 00:00:00
ensure
initialized: hour = 0 and minute = 0 and second = 0
 
feature -- Access
 
hour: INTEGER_32
-- Hour expressed as 24-hour value
 
minute: INTEGER_32
-- Minutes past the hour
 
second: INTEGER_32
-- Seconds past the minute
 
feature -- Element change
 
set_hour (h: INTEGER_32)
-- Set the hour from `h'
require
argument_hour_valid: 0 <= h and h <= 23
ensure
hour_set: hour = h
minute_unchanged: minute = old minute
second_unchanged: second = old second
 
set_minute (m: INTEGER_32)
-- Set the minute from `m'
require
argument_minute_valid: 0 <= m and m <= 59
ensure
minute_set: minute = m
hour_unchanged: hour = old hour
second_unchanged: second = old second
 
set_second (s: INTEGER_32)
-- Set the second from `s'
require
argument_second_valid: 0 <= s and s <= 59
ensure
second_set: second = s
hour_unchanged: hour = old hour
minute_unchanged: minute = old minute
 
invariant
hour_valid: 0 <= hour and hour <= 23
minute_valid: 0 <= minute and minute <= 59
second_valid: 0 <= second and second <= 59
 
end -- class TIME_OF_DAY

It is important to notice what is missing from this view. It shows only the specification of the class. The implementations of routines and any routines which are not public are not visible. The notes and comments, public features (including contracts for routines), and the class invariant all remain as components of the specification.

This view was produced by EiffelStudio which also supports an Interface view which is similar to the Contract view above, but also includes contracts for any inherited routines, and the complete inherited class invariant. EiffelStudio can publish these and other documentation view in HTML and other formats suitable for sharing.

[edit] Factor

Factor has an extensive documentation system built in. See docs.factorcode.org : [1]

[edit] Haskell

Haddock is a popular documentation generator for the Haskell language.

-- |This is a documentation comment for the following function
square1 :: Int -> Int
square1 x = x * x
 
-- |It can even
-- span multiple lines
square2 :: Int -> Int
square2 x = x * x
 
square3 :: Int -> Int
-- ^You can put the comment underneath if you like, like this
square3 x = x * x
 
{-|
Haskell block comments
are also supported
-}

square4 :: Int -> Int
square4 x = x * x
 
-- |This is a documentation comment for the following datatype
data Tree a = Leaf a | Node [Tree a]
 
-- |This is a documentation comment for the following type class
class Foo a where
bar :: a

See this chapter for more information about the markup.

[edit] J

Use scripdoc:

NB. =========================================================
NB.*apply v apply verb x to y
apply=: 128!:2
 
NB. =========================================================
NB.*def c : (explicit definition)
def=: :
 
NB.*define a : 0 (explicit definition script form)
define=: : 0
 
NB.*do v name for ".
do=: ".
 
NB.*drop v name for }.
drop=: }.

[edit] Java

Documentation is typically given using Javadoc comments. Documentation is generated from these comments using the Javadoc tool. The default output (from the standard doclet) takes the form of an HTML page with frames, so HTML is frequently embedded in the comments. The comments all start with /**, end with */, and usually have "tags" embedded starting with @.

/**
* This is a class documentation comment. This text shows at the top of the page for this class
* @author Joe Schmoe
*/

public class Doc{
/**
* This is a field comment for a variable
*/

private String field;
 
/**
* This is a method comment. It has parameter tags (param), an exception tag (throws),
* and a return value tag (return).
*
* @param num a number with the variable name "num"
* @throws BadException when something bad happens
* @return another number
*/

public int method(long num) throws BadException{
//...code here
}
}

[edit] OCaml

OCamldoc is a documentation generator that is included with OCaml. Documentation comments all start with (** (but no more than two asterisks) and end with *). Like Javadoc, "tags" can be embedded starting with @.

[edit] D

D compiler comes with a builtin documentation system called Ddoc. Alternative systems may be used (a common alternative is Doxygen which includes some D support).

/**
* This is a documentation comment for somefunc and somefunc2.
* Does not need to be preceded by '*' in every line - this is done purely for code style
* $(DDOC_COMMENT comment inside a documentation comment (results in a HTML comment not displayed by the browser))
* Header:
* content (does not need to be tabbed out; this is done for clarity of the comments and has no effect on the
* resulting documentation)
* Params:
* arg1 = Something (listed as "int <i>arg1</i> Something")
* arg2 = Something else
* Returns:
* Nothing
* TODO:
* Nothing at all
* BUGS:
* None found
*/

void somefunc(int arg1, int arg2)
{
}
// this groups this function with the above (both have the same doc and are listed together)
/// ditto
void somefunc2(int arg1, int arg2)
{
}
/++ Another documentation comment +/
void main()
{
}

[edit] Perl

Perl's documentation mechanism is called POD (Plain Old Documentation). Basically, any line that starts with an equal sign followed by a word (e.g. =head1) starts a documentation comment; and it lasts until a line that begins with =cut. Many formatting commands are recognized; for example, a line beginning with =item starts a section for an item, text wrapped in I< ... > is italicized, text wrapped in C< ... > is formatted as code, etc. See the perlpod and perlpodspec manuals for more details about the format.

[edit] PHP

phpDocumentor (phpdoc) is a documentor for PHP. The syntax is similar to Javadoc.

[edit] Python

A string literal which is the first expression in a class, function, or module definition is called a docstring. It can be subsequently accessed at runtime using the .__doc__ attribute of the class, function, or module.

class Doc(object):
"""
This is a class docstring. Traditionally triple-quoted strings are used because
they can span multiple lines and you can include quotation marks without escaping.
"""

def method(self, num):
"""This is a method docstring."""
pass

pydoc, a module of the Python standard library, can automatically generate documentation gleaned from docstrings of modules. The documentation can be presented as pages of text on a terminal; automatically served to a Web Browser; or saved as HTML. The command line pydoc command , in addition, can display docstring information in a TK based GUI browser.

The built-in help() function uses the pydoc module to display docstring information at the command prompt of the Python interactive shell.

>>> def somefunction():
"takes no args and returns None after doing not a lot"
 
 
>>> help(somefunction)
Help on function somefunction in module __main__:
 
somefunction()
takes no args and returns None after doing not a lot
 
>>>

[edit] Sphinx

The Sphinx Documentation generator suite is used to generate the new Python documentation.

[edit] R

R objects are documented in files written in "R documentation" (Rd) format, which is similar to LaTeX markup. See Chapter 2 of Writing R Extensions for the full details. Example function document files can be created using

example(package.skeleton)

An example documentation file for a function 'f', taking arguments 'x' and 'y' is

\name{f}
\Rdversion{1.1}
\alias{f}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
%% ~~function to do ... ~~
}
\description{
%% ~~ A concise (1-5 lines) description of what the function does. ~~
}
\usage{
f(x, y)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{x}{
%% ~~Describe \code{x} here~~
}
\item{y}{
%% ~~Describe \code{y} here~~
}
}
\details{
%% ~~ If necessary, more details than the description above ~~
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
}
\references{
%% ~put references to the literature/web site here ~
}
\author{
%% ~~who you are~~
}
\note{
%% ~~further notes~~
}
 
%% ~Make other sections like Warning with \section{Warning }{....} ~
 
\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
}
\examples{
##---- Should be DIRECTLY executable !! ----
##-- ==> Define data, use random,
##-- or do help(data=index) for the standard data sets.
 
## The function is currently defined as
function(x,y) x+y
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line

[edit] REBOL

rebol [
Title: "Documentation"
Date: 2009-12-14
Author: oofoe
URL: http://rosettacode.org/wiki/Documentation
Purpose: {To demonstrate documentation of REBOL pograms.}
]

 
; Notice the fields in the program header. The header is required for
; valid REBOL programs, although the fields don't have to be filled
; in. Standard fields are defined (see 'system/script/header'), but
; I can also define other fields as I like and they'll be available
; there.
 
; This is a comment. The semicolon can be inserted anywhere outside of
; a string and will escape to end of line. See the inline comments
; below.
 
; Functions can have a documentation string as the first part of the
; argument definition block. Each argument can specify what types it
; will accept as well as a description. All typing/documentation
; entries are optional. Notice that local variables can be documented
; as well.
 
sum: func [
"Add numbers in block."
data [block! list!] "List of numbers to add together."
/average "Calculate average instead of sum."
/local
i "Iteration variable."
x "Variable to hold results."
] [
x: 0 repeat i data [x: x + i]
either average [x / length? data][x] ; Functions return last result.
]
 
print [sum [1 2 3 4 5 6] crlf sum/average [7 8 9 10] crlf]
 
; The help message is constructed from the public information about
; the function. Internal variable information isn't shown.
 
help sum print ""
 
; The source command provides the source to any user functions,
; reconstructing the documentation strings if they're provided:
 
source sum print ""
 
; This is an object, describing a person, whose name is Bob.
 
bob: make object! [
name: "Bob Sorkopath"
age: 24
hi: func ["Say hello."][print "Hello!"]
]
 
; I can use the 'help' word to get a list of the fields of the object
 
help bob print ""
 
; If I want see the documentation or source for 'bob/hi', I have to
; get a little tricky to get it from the object's namespace:
 
x: get in bob 'hi help x print ""
 
probe get in bob 'hi

Output:

21
8.5

USAGE:
    SUM data /average

DESCRIPTION:
     Add numbers in block.
     SUM is a function value.

ARGUMENTS:
     data -- List of numbers to add together. (Type: block list)

REFINEMENTS:
     /average -- Calculate average instead of sum.

sum: func [
    "Add numbers in block."
    data [block! list!] "List of numbers to add together."
    /average "Calculate average instead of sum."
    /local
    i "Iteration variable."
    x "Variable to hold results."
][
    x: 0 repeat i data [x: x + i]
    either average [x / length? data] [x]
]

BOB is an object of value:
   name            string!   "Bob Sorkopath"
   age             integer!  24
   hi              function! Say hello.


USAGE:
    X

DESCRIPTION:
     Say hello.
     X is a function value.

func ["Say hello."][print "Hello!"]

[edit] Ruby

RDoc is the de-facto documentation tool that's bundled with Ruby distributions. From it's documentation:

Rdoc is an application that produces documentation for one or more Ruby source files. We work similarly to JavaDoc, parsing the source, and extracting the definition for classes, modules, and methods (along with includes and requires). We associate with these optional documentation contained in the immediately preceding comment block, and then render the result using a pluggable output formatter.

RDoc produces output that looks like this.

Ruby's documentation comments look like Perl's PODs. Translating Java's example:

=begin rdoc
RDoc is documented here[http://www.ruby-doc.org/core/classes/RDoc.html].
 
This is a class documentation comment. This text shows at the top of the page
for the class.
 
Comments can be written inside "=begin rdoc"/"end" blocks or
in normal '#' comment blocks.
 
There are no '@parameters' like javadoc, but 'name-value' lists can be written:
Author:: Joe Schmoe
Date:: today
=end

 
class Doc
# This is a comment for a Constant
Constant = nil
 
# This is a method comment. Parameters and return values can be named
# with the "call-seq" directive.
#
# call-seq:
# a_method(first_arg, second_arg) -> return_value
#
def a_method(arg1, arg2='default value')
do_stuff
end
 
# Class methods will be shown in a separate section of the generated documentation.
def self.class_method
Constant
end
end
 
# :include:boilerplate.txt

[edit] Tcl

Documentation for Tcl code is usually prepared in separate files using a tool like doctools, but inline docs (with all their inherent limitations) can be done with the likes of Robodoc. For example:

#****f* RosettaCode/TclDocDemo
# FUNCTION
# TclDocDemo is a simple illustration of how to do documentation
# of Tcl code using Robodoc.
# SYNOPSYS
# TclDocDemo foo bar
# INPUTS
# foo -- the first part of the message to print
# bar -- the last part of the message to print
# RESULT
# No result
# NOTES
# Prints a message based on a template by filling in with the
# supplied strings.
#*****
proc TclDocDemo {foo bar} {
puts [format "%s -- %s" $foo $bar]
}

Both doctools and robodoc can produce output in multiple formats.

Personal tools
Google AdSense