source: specdomain/trunk/src/specdomain/doc/style_guide.rst @ 1124

Last change on this file since 1124 was 1124, checked in by jemian, 10 years ago

fixes #35 and #36

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision URL Header
File size: 19.2 KB
Line 
1.. $Id: style_guide.rst 1124 2012-10-01 18:08:46Z jemian $
2
3.. index::  ! style guide
4
5===============================================================================
6SPEC Documentation Style Guide
7===============================================================================
8
9Some interesting and applicable words from the `Google Style Guide
10<http://google-styleguide.googlecode.com/svn/trunk/pyguide.html>`_:
11
12  BE CONSISTENT.
13 
14  If you're editing code, take a few minutes to look at the code around you
15  and determine its style. If they use spaces around all their arithmetic
16  operators, you should too. If their comments have little boxes of hash
17  marks around them, make your comments have little boxes of hash marks
18  around them too.
19 
20  The point of having style guidelines is to have a common vocabulary of
21  coding so people can concentrate on what you're saying rather than on
22  how you're saying it. We present global style rules here so people know
23  the vocabulary, but local style is also important. If code you add to a
24  file looks drastically different from the existing code around it, it
25  throws readers out of their rhythm when they go to read it. Avoid this.
26
27With these words in mind, this SPEC Documentation Style Guide documents
28the conventions set forth to use for SPEC macros at the APS.
29
30The concept of docstrings
31=========================
32
33In-line source documentation resides inside comment blocks directly within the
34SPEC macro files. In analogy to the python language, we will refer to these
35documentation comments as *docstrings*. These docstrings are processed by the
36specdomain package for the Sphinx documentation creator to produce user or
37reference manual in a variety of formats (html, pdf, man-pages, text files,
38etc.)
39
40The following section sets forth some formatting conventions for SPEC
41docstrings.
42
43One-line docstrings
44-------------------
45
46There are two distinct scenarios where one-line docstrings are appropriate or
47even necessary:
48
49#.  Obvious cases (where one line is completely sufficient to describe
50    the code).
51#.  Descriptive comments, that are used to document code objects
52    (variables, one-line ``rdef`` or ``def`` declarations, or ```cdef``
53    definitions) which cannot contain extended docstrings.
54   
55:Obvious cases:
56  Obvious cases are those where the macro or macro function definition is so
57  clear that no elaborate explanation is necessary. For example, the following
58  macro function definition can probably be documented in a one-liner::
59 
60    def sind(x) '{
61      """ Return the sine of x, where x is given in degrees."""
62     
63      return sin(x*PI/180)
64    }'
65   
66  One-liners need to be enclosed in triple double-quotes (``"""``) which are
67  placed on the same line as the docstring. A single space between the opening
68  quotes and the docstring is optional. A blank line after the docstring helps
69  to visually separate it from the actual code.
70 
71:Descriptive comments:
72  Descriptive comments are a new a construct which can be used to document
73  items that cannot contain extended comments (triple-quoted strings)
74  themselves, such as variable declarations, one-line ``def`` or ``rdef``
75  declarations, or ``cdef`` definitions.
76  They appear either as comments in the same line after the declaration
77  (in-line) or as a comment-only line immediately preceding the declaration
78  (one-liner). Descriptive comments are marked by a preceding ``#:``, which
79  lets them appear like normal SPEC comments, but the colon triggers the parser
80  to process the docstring::
81 
82    global TTH            #: The scattering angle two-theta [float].
83
84    #: Clear the ccd shutter handler
85    rdef ccdset_shutter ''
86
87    def do_nothing() ''   #: This macro does not do anything.
88
89
90Multi-line docstrings
91---------------------
92
93Multi-line docstrings are surrounded by a pair of triple double-quotes
94(``"""``), which should be placed on a line by themselves.
95For macro definitions, the opening quotes should appear on the next
96line immediately below the macro definition. It is recommended to insert a
97blank line between the last paragraph in a multi-line docstring and its closing
98quotes, followed by another blank line before the next code item begins.
99
100The entire docstring is indented the same as the quotes at its first line.
101Docstrings inside macro declarations should be indented from the definition
102statement by the same level as the code contained in the definition.
103
104Multi-line docstrings consist of a summary line just like a one-line docstring,
105followed by a blank line and then a more elaborate description. The summary
106line will be used by the specdomain indexing and summary tools. It is therefore
107important to make the summary lines very clear and concise. They should always
108be written as complete sentences, starting with a capital letter and ending
109with a period.
110
111
112Documentation of code objects
113=============================
114
115We will refer to certain types or components of the SPEC macro code as *code
116objects*. These may include:
117
118* Macro files
119* Macro definitions (``def``, ``rdef``, ``cdef``)
120* Variables (global, local, etc.)
121* Entire collections of macro files
122
123Each type of these code objects requires certain information to be included in
124the documentation. The following sections should help to ensure that all the
125required information is included and will appear in a consistent format.
126
127File headers
128------------
129The macro file header docstring provides information about the macro file as a
130whole (in the python world, this might be called a *module*).
131
132As with any docstring, the first item should be a concise summary line of what
133the macro file provides and which could be used in summary tables, indexes,
134etc.
135
136This is followed by sections about the detailed functionality, setup and
137configuration instructions, file information, and so on. The full power of
138Sphinx and ReST markup is available at this level, so sections can be broken up
139in subsections and subsubsections, tables may be included as well as figures or
140mathematical formulas.
141
142The following information should be included, and the below layout may aid in
143supplying a complete set of information. Note that this can always be changed
144to meet the particular requirements of individual macro files:
145
146**Description (top-level header)**:
147  A more elaborate description of the functionality provided in the macro file.
148  Include any number of subsections and subsubsections.
149
150**Notes (top-level header)**:
151  Any additional notes or comments about the file or its usage.
152 
153**Installation (top-level header)**:
154  Information on how to set up the macro functionality. This includes,
155  if applicable, the following subsections (second level headers):
156 
157  **Configuration**:
158    Prerequisites in the SPEC configuration. For example, the configuration of
159    dedicated counters may be necessary in order to use the macros.
160
161  **Setup**:
162    The steps necessary to set up the macro functionality. For example, loading
163    the macro file (``qdo``) and running the ``macro_init`` function.
164
165  **Dependencies**:
166    List all the dependencies on other macros, hardware, software, EPICS
167    channels, etc.
168
169  **Impact**:
170    Describe the impact that the use of the macro may have. For example, list
171    all the changes made to other ``cdef`` macro definitions by this macro
172    file.
173
174**File Information (top-level header)**:
175  All the information about the macro file itself, like authors, license,
176  version, etc.
177 
178  It is recommended to build up this section as a definition list. The headings
179  for each item are CAPITALIZED and end with a colon. The content under each of
180  these items should be indented one level. This results in a more lightweight
181  layout, and prevents cluttering the tables of content with too many
182  subsections.
183 
184  The following items should be included, preferably in this order:
185 
186  * AUTHOR(S):
187  * CREATION DATE:
188  * COPYRIGHT:
189  * LICENSE:
190  * VERSION:
191  * CHANGE LOG:
192  * TO DO:
193  * KNOWN BUGS:
194 
195  See the example below for more details on each of these items.
196 
197
198Example of a file header docstring
199~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
200
201::
202
203        """
204        Summary line: a concise sentence about what this macro file provides.
205       
206        Description
207        ===========
208        A more detailed description of the macro file and the functionality that the
209        library of macro definitions it contains provides.
210       
211        Note(s)
212        =======
213        Any special notes about the macro file, its usage, or its history can go here.
214       
215        Installation
216        ============
217        Describe, as applicable, the installation procedure, necessary changes in the
218        SPEC configuration, dependencies, and impact on chained macro definitions
219        (``cdef``) or redefinitions (``rdef``). The sections below give hypothetical
220        examples of what the content may look like.
221       
222        Configuration
223        -------------
224        For this macro to work, the SPEC configuration may need to be modified. The
225        following counters are required:
226       
227                ========  ============  ==============  =======================
228                Counter   Mnemonic      Type            Description
229                ========  ============  ==============  =======================
230                mycount1  mcnt1         None            My first counter
231                mycount2  mcnt2         Macro counter   My second counter
232                ========  ============  ==============  =======================
233       
234        Setup
235        -----
236        With the above configuration change, simply load the macro file
237        ``template.mac`` and run :spec:def:`template_setup`::
238       
239                > qdo template.mac
240                > template_setup
241       
242        Dependencies
243        ------------
244        This macro depends on the following macro files and macros:
245       
246        * filter.mac
247       
248                - :spec:def:`filter_trans`
249                - :spec:def:`filter_get_trans()`
250       
251        * bpm.mac
252       
253                - :spec:def:`bpm_get_pos`
254       
255        Impact
256        ------
257        The following chained macro definitions are affected by template.mac:
258       
259        * :spec:def:`user_precount`:  Adding :spec:def:`template_precount`
260        * :spec:def:`user_getcounts`: Adding :spec:def:`template_getcounts`
261                to the end ``(0x20)``
262       
263        File information
264        ================
265       
266        AUTHOR(S):
267       
268                * A.B. Sample (AS, asamp), asamp@aps.anl.gov, Argonne National Laboratory
269       
270        CREATION DATE:
271       
272                YYYY-MM-DD
273       
274        COPYRIGHT:
275       
276                .. automatically retrieve the current year:
277                .. |current_year| date:: %Y
278       
279                Copyright (c) 2010-|current_year|, UChicago Argonne, LLC
280                Operator of Argonne National Laboratory
281                All Rights Reserved
282       
283                APS SPEC macros
284       
285        LICENSE::
286       
287                OPEN SOURCE LICENSE
288       
289                Redistribution and use in source and binary forms, with or without
290                modification, are permitted provided that the following conditions are met:
291       
292                1. Redistributions of source code must retain the above copyright notice,
293                         this list of conditions and the following disclaimer.  Software changes,
294                         modifications, or derivative works, should be noted with comments and
295                         the author and organization's name.
296       
297                2. Redistributions in binary form must reproduce the above copyright notice,
298                         this list of conditions and the following disclaimer in the documentation
299                         and/or other materials provided with the distribution.
300       
301                3. Neither the names of UChicago Argonne, LLC or the Department of Energy
302                         nor the names of its contributors may be used to endorse or promote
303                         products derived from this software without specific prior written
304                         permission.
305       
306                4. The software and the end-user documentation included with the
307                         redistribution, if any, must include the following acknowledgment:
308       
309                         "This product includes software produced by UChicago Argonne, LLC
310                         under Contract No. DE-AC02-06CH11357 with the Department of Energy."
311       
312                *****************************************************************************
313       
314                DISCLAIMER
315       
316                THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND.
317       
318                Neither the United States GOVERNMENT, nor the United States Department
319                of Energy, NOR UChicago Argonne, LLC, nor any of their employees, makes
320                any warranty, express or implied, or assumes any legal liability or
321                responsibility for the accuracy, completeness, or usefulness of any
322                information, data, apparatus, product, or process disclosed, or
323                represents that its use would not infringe privately owned rights.
324       
325                *****************************************************************************
326       
327        VERSION::
328       
329                $Revision: 1124 $
330                $Date: 2012-10-01 18:08:46 +0000 (Mon, 01 Oct 2012) $
331                $Author: jemian $
332                $URL: specdomain/trunk/src/specdomain/doc/style_guide.rst $
333       
334        CHANGE LOG:
335       
336                YYYY-MM-DD (AS):
337       
338                - created first version of this macro.
339                - tested on a dummy SPEC version not connected to a diffractometer.
340       
341                YYYY-MM-DD (AS):
342       
343                - added a new macro definition: :spec:def:`new_macro` to display the status.
344       
345        TO DO:
346       
347                - List all the TODO items
348       
349        KNOWN BUGS:
350       
351                - List all the known bugs and limitations
352       
353        """
354
355Macro definition docstrings
356---------------------------
357
358The docstring for a macro or macro function definition should summarize its
359behavior and document its arguments, return value(s), side effects, and
360restrictions on when it can be called (all if applicable). A docstring should
361give enough information to write a call to the function without reading the
362function's code. A docstring should describe the function's calling syntax and
363its semantics, not its implementation.
364
365Certain aspects of a macro definition should be documented in special sections,
366listed below. Since Sphinx does not generally allow for the presence of any
367types of formal headings inside the code object docstrings, the docstring
368should be build up as a ReST definition list (see example below). The section
369titles are all CAPITALIZED for improved visibility and end with a colon. The
370contents for each section are indented by two spaces with respect to the
371section title.
372
373Sections
374~~~~~~~~
375
376The following sections should be included in the macro docstring after the
377summary line, in the below order, if applicable:
378
379DESCRIPTION:
380  A more elaborate description of the macro's functionality.
381 
382USAGE:
383  The syntax for calling the macro. This should contain all possible variants
384  of the macro call. Argument names are enclosed in angle brackets (``<>``) to
385  indicate that they should be replaced by actual values in the macro call.
386  Optional arguments are additionally enclosed in square brackets (``[]``).
387  The actual USAGE syntax should appear as pre-formatted text, and each input
388  line should start with a "``>``"-symbol to represent the SPEC command line
389  prompt::
390 
391    USAGE::
392   
393      > my_macro <pos1> [<pos2>]
394      > <return_value> = my_function(<input_value>)
395
396ARGUMENTS:
397  All the arguments to a function or macro call should be listed in the form of
398  a ReST field list. The argument name is enclosed between colons (``:``),
399  followed by the description, which can span several (indented) lines. It is
400  useful to specify also the type of the argument in square brackets (``[]``).
401 
402  If a macro call has both mandatory and optional arguments, list them in
403  separate lists::
404 
405    Required arguments:
406      :pos1:    Target position for motor [float].
407 
408    Optional arguments:
409      :timeout: The wait-time before giving up on serial port communication in
410        seconds [float].
411 
412  Note that a number of python projects use a special kind of argument
413  definition list which is processed by Sphinx to include more information,
414  for example, the type of an argument. Other projects, however, actively
415  discourage its use or prefer the above style for simplicity.
416  The syntax is as follows::
417 
418    :param str motor_name: name of motor to use.
419 
420  This syntax is perfectly acceptable also for SPEC documentation, however it
421  arguably results in harder to read in-line documentation and is often not
422  rendered very neatly in the final Sphinx output. Use this at your own
423  discretion.
424
425EXAMPLE:
426  A short example, illustrating the usage of the macro. As in the case of the
427  USAGE section, the syntax should appear as pre-formatted text, and each input
428  line should start with the "``>``"-symbol to represent the SPEC command line
429  prompt. Short explanation lines can be inserted as indented comment lines::
430 
431    EXAMPLE::
432   
433      > set_temperatures 23.5 50.0
434          # sets the two container temperatures to 23.5 and 50.0 degrees.
435
436NOTE(S):
437  Additional notes on the macro usage.
438
439SEE ALSO:
440  A list of other macros or documentation items to refer to for further
441  information. If possible, these should be dynamically linked using the
442  corresponding Sphinx specdomain roles::
443 
444    SEE ALSO:
445      * :spec:def:`my_other_macro`
446      * http://spec.examples.com/example3.html
447     
448Using the definition list syntax, other sections may be included, as necessary
449or appropriate for the particular macro.
450
451Example of a macro definition docstring
452~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
453
454::
455
456        """
457        Concise summary line.
458       
459        USAGE::
460               
461                > my_move <motor> <position> [<sleep_time>]
462               
463        ARGUMENTS:
464               
465                Required arguments:
466                        :motor:    The motor to be moved [str].
467                        :position: The position to move the motor to [float].
468               
469                Optional arguments:
470                        :sleep_time: Settling time after the move has finished [float].
471               
472        EXAMPLE::
473       
474                > my_move del 23.2346 0.3
475                                # move del to 23.2346 and wait for 0.3 seconds after move finishes.
476                               
477        NOTE:
478                Indicate any side effects, restrictions or other usage notes here.
479               
480        SEE ALSO:
481                * :spec:def:`my_move2`
482                * :spec:global:`MOVE_FLAG`
483                * http://www.certif.com/spec_help/prdef.html
484               
485        """
486
487This results in the following:
488
489        Concise summary line.
490               
491        USAGE::
492               
493                > my_move <motor> <position> [<sleep_time>]
494               
495        ARGUMENTS:
496               
497                Required arguments:
498                  :motor:    The motor to be moved [str].
499                  :position: The position to move the motor to [float].
500               
501                Optional arguments:
502                  :sleep_time: Settling time after the move has finished [float].
503               
504        EXAMPLE::
505       
506                > my_move del 23.2346 0.3
507                                # move del to 23.2346 and wait for 0.3 seconds after move finishes.
508                               
509        NOTE:
510                Indicate any side effects, restrictions or other usage notes here.
511               
512        SEE ALSO:
513                * :spec:def:`my_move2`
514                * :spec:global:`MOVE_FLAG`
515                * http://www.certif.com/spec_help/prdef.html
516   
517
518One-line docstrings
519-------------------
520
521As mentioned previously, one-line docstrings (also called *descriptive
522comments*) can be used to document code objects that cannot contain extended
523docstrings.
524
525One-line docstrings begin with a capital letter and end with a period.
526
527Variables
528~~~~~~~~~
529Docstrings for variables provide a short description of the variable. It is
530also recommended to specify the type of the variable in square brackets
531(``[]``). For example::
532
533  global TTH     #: The scattering angle two-theta [float].
534  local _ind     #: List index of the active reflection [int].
535 
536  #: Associate array with orientation reflection HKL-indices & angles [float].
537  global ORIENTATION_REFLECTIONS
538
539
540Macro definitions
541~~~~~~~~~~~~~~~~~
542
543One-line docstrings for macro definitions contain a short description of the
544purpose for the (re-)definition. For example::
545
546  #: Define the ccd shutter handler
547  rdef ccdset_shutter '_ccdset_shutter'
548
549  #: remove ccd_getcounts from user_getcounts
550  cdef("user_getcounts", "", "ccd_key", "delete")
551
552
553Macro collection docstrings
554----------------------------
555
556As of now, there is no standard yet for documenting entire collections of
557macros, as, for example, those collected in particular directories of the SVN
558source code repository.
559
560The documentation for such a collection should be in the form of normal ReST
561files (``*.rst``), residing in the same directory with the macro collection.
562There is no way of automatically including this information in the global
563documents yet, so it will need to be added manually somewhere in the
564documentation tree (at least in the global ``index.rst`` file or some other
565file that is included from the global scope).
566
Note: See TracBrowser for help on using the repository browser.