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

Last change on this file since 1091 was 1091, checked in by cschlep, 10 years ago

Minor work on the style guide

  • 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 1091 2012-09-05 14:29:02Z cschlep $
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 style guides documents the conventions set forth
28to 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 leightweight
181  layout, and prevents cluttering the tables of content with too many
182  subsections.
183 
184  The following items should be included, preferrably 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 below example 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       
281                All Rights Reserved
282       
283                APS SPEC macros
284       
285                APS SPEC development team,
286                X-ray Science Division and APS Engineering Support Division,
287                Argonne National Laboratory
288       
289        LICENSE::
290       
291                OPEN SOURCE LICENSE
292       
293                Redistribution and use in source and binary forms, with or without
294                modification, are permitted provided that the following conditions are met:
295       
296                1. Redistributions of source code must retain the above copyright notice,
297                         this list of conditions and the following disclaimer.  Software changes,
298                         modifications, or derivative works, should be noted with comments and
299                         the author and organization's name.
300       
301                2. Redistributions in binary form must reproduce the above copyright notice,
302                         this list of conditions and the following disclaimer in the documentation
303                         and/or other materials provided with the distribution.
304       
305                3. Neither the names of UChicago Argonne, LLC or the Department of Energy
306                         nor the names of its contributors may be used to endorse or promote
307                         products derived from this software without specific prior written
308                         permission.
309       
310                4. The software and the end-user documentation included with the
311                         redistribution, if any, must include the following acknowledgment:
312       
313                         "This product includes software produced by UChicago Argonne, LLC
314                         under Contract No. DE-AC02-06CH11357 with the Department of Energy."
315       
316                *****************************************************************************
317       
318                DISCLAIMER
319       
320                THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND.
321       
322                Neither the United States GOVERNMENT, nor the United States Department
323                of Energy, NOR uchicago argonne, LLC, nor any of their employees, makes
324                any warranty, express or implied, or assumes any legal liability or
325                responsibility for the accuracy, completeness, or usefulness of any
326                information, data, apparatus, product, or process disclosed, or
327                represents that its use would not infringe privately owned rights.
328       
329                *****************************************************************************
330       
331        VERSION::
332       
333                $Revision: 1091 $
334                $Date: 2012-09-05 14:29:02 +0000 (Wed, 05 Sep 2012) $
335                $Author: cschlep $
336                $URL: specdomain/trunk/src/specdomain/doc/style_guide.rst $
337       
338        CHANGE LOG:
339       
340                YYYY/MM/DD (AS):
341       
342                - created first version of this macro.
343                - tested on a dummy SPEC version not connected to a diffractometer.
344       
345                YYYY/MM/DD (AS):
346       
347                - added a new macro definition: :spec:def:`new_macro` to display the status.
348       
349        TO DO:
350       
351                - List all the TODO items
352       
353        KNOWN BUGS:
354       
355                - List all the known bugs and limitations
356       
357        """
358
359Macro definition docstrings
360---------------------------
361
362The docstring for a macro or macro function definition should summarize its
363behavior and document its arguments, return value(s), side effects, and
364restrictions on when it can be called (all if applicable). A docstring should
365give enough information to write a call to the function without reading the
366function's code. A docstring should describe the function's calling syntax and
367its semantics, not its implementation.
368
369Certain aspects of a macro definition should be documented in special sections,
370listed below. Since Sphinx does not generally allow for the presence of any
371types of formal headings inside the code object docstrings, the docstring
372should be build up as a ReST definition list (see example below). The section
373titles are all CAPITALIZED for improved visibility and end with a colon. The
374contents for each section are indented by two spaces with respect to the
375section title.
376
377Sections
378~~~~~~~~
379
380The following sections should be included in the macro docstring after the
381summary line, in the below order, if applicable:
382
383DESCRIPTION:
384  A more elaborate description of the macro's functionality.
385 
386USAGE:
387  The syntax for calling the macro. This should contain all possible variants
388  of the macro call. Argument names are enclosed in angle brackets (``<>``) to
389  indicate that they should be replaced by actual values in the macro call.
390  Optional arguments are additionally enclosed in square brackets (``[]``).
391  The actual USAGE syntax should appear as preformatted text, and each input
392  line should start with a "``>``"-symbol to represent the SPEC command line
393  prompt::
394 
395    USAGE::
396   
397      > my_macro <pos1> [<pos2>]
398      > <return_value> = my_function(<input_value>)
399
400ARGUMENTS:
401  All the arguments to a function or macro call should be listed in the form of
402  a ReST field list. The argument name is enclosed between colons (``:``),
403  followed by the description, which can span several (indented) lines. It is
404  useful to specify also the type of the argument in square brackets (``[]``).
405 
406  If a macro call has both mandatory and optional arguments, list them in
407  separate lists::
408 
409    Required arguments:
410      :pos1:    Target position for motor [float].
411 
412    Optional arguments:
413      :timeout: The wait-time before giving up on serial port communication in
414        seconds [float].
415 
416  Note that a number of python projects use a special kind of argument
417  definition list which is processed by Sphinx to include more information,
418  for example, the type of an argument. Other projects, however, actively
419  discourage its use or prefer the above style for simplicity.
420  The syntax is as follows::
421 
422    :param str motor_name: name of motor to use.
423 
424  This syntax is perfectly acceptable also for SPEC documentation, however it
425  arguably results in harder to read in-line documentation and is often not
426  rendered very neatly in the final Sphinx output. Use this at your own
427  discretion.
428
429EXAMPLE:
430  A short example, illustrating the usage of the macro. As in the case of the
431  USAGE section, the syntax should appear as pre-formatted text, and each input
432  line should start with the "``>``"-symbol to represent the SPEC command line
433  prompt. Short explanation lines can be inserted as indented comment lines::
434 
435    EXAMPLE::
436   
437      > set_temperatures 23.5 50.0
438          # sets the two container temperatures to 23.5 and 50.0 degrees.
439
440NOTE(S):
441  Additional notes on the macro usage.
442
443SEE ALSO:
444  A list of other macros or documentation items to refer to for further
445  information. If possible, these should be dynamically linked using the
446  corresponding Sphinx specdomain roles::
447 
448    SEE ALSO:
449      * :spec:def:`my_other_macro`
450      * http://spec.examples.com/example3.html
451     
452Using the definition list syntax, other sections may be included, as necessary
453or appropriate for the particular macro.
454
455Example of a macro definition docstring
456~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457
458::
459
460        """
461        Concise summary line.
462       
463        USAGE::
464               
465                > my_move <motor> <position> [<sleep_time>]
466               
467        ARGUMENTS:
468               
469                Required arguments:
470                        :motor:    The motor to be moved [str].
471                        :position: The position to move the motor to [float].
472               
473                Optional arguments:
474                        :sleep_time: Settling time after the move has finished [float].
475               
476        EXAMPLE::
477       
478                > my_move del 23.2346 0.3
479                                # move del to 23.2346 and wait for 0.3 seconds after move finishes.
480                               
481        NOTE:
482                Indicate any side effects, restrictions or other usage notes here.
483               
484        SEE ALSO:
485                * :spec:def:`my_move2`
486                * :spec:global:`MOVE_FLAG`
487                * http://www.certif.com/spec_help/prdef.html
488               
489        """
490
491This results in the following:
492
493        Concise summary line.
494               
495        USAGE::
496               
497                > my_move <motor> <position> [<sleep_time>]
498               
499        ARGUMENTS:
500               
501                Required arguments:
502                  :motor:    The motor to be moved [str].
503                  :position: The position to move the motor to [float].
504               
505                Optional arguments:
506                  :sleep_time: Settling time after the move has finished [float].
507               
508        EXAMPLE::
509       
510                > my_move del 23.2346 0.3
511                                # move del to 23.2346 and wait for 0.3 seconds after move finishes.
512                               
513        NOTE:
514                Indicate any side effects, restrictions or other usage notes here.
515               
516        SEE ALSO:
517                * :spec:def:`my_move2`
518                * :spec:global:`MOVE_FLAG`
519                * http://www.certif.com/spec_help/prdef.html
520   
521
522One-line docstrings
523-------------------
524
525As mentioned previously, one-line docstrings (also called *descriptive
526comments*) can be used to document code objects that cannot contain extended
527docstrings.
528
529One-line docstrings begin with a capital letter and end with a period.
530
531Variables
532~~~~~~~~~
533Docstrings for variables provide a short description of the variable. It is
534also recommended to specify the type of the variable in square brackets
535(``[]``). For example::
536
537  global TTH     #: The scattering angle two-theta [float].
538  local _ind     #: List index of the active reflection [int].
539 
540  #: Associate array with orientation reflection HKL-indices & angles [float].
541  global ORIENTATION_REFLECTIONS
542
543
544Macro definitions
545~~~~~~~~~~~~~~~~~
546
547One-line docstrings for macro definitions contain a short description of the
548purpose for the (re-)definition. For example::
549
550  #: Define the ccd shutter handler
551  rdef ccdset_shutter '_ccdset_shutter'
552
553  #: remove ccd_getcounts from user_getcounts
554  cdef("user_getcounts", "", "ccd_key", "delete")
555
556
557Macro collection docstrings
558----------------------------
559
560As of now, there is no standard yet for documenting entire collections of
561macros, as, for example, those collected in particular directories of the SVN
562source code repository.
563
564The documentation for such a collection should be in the form of normal ReST
565files (*.rst), residing in the same directory with the macro collection. There
566is no way of automatically including this information in the global documents
567yet, so it will need to be added manually somewhere in the documentation tree
568(at least in the global ``index.rst`` file or some other file that is included
569from the global scope).
570
Note: See TracBrowser for help on using the repository browser.