====== microHAL coding guide. ======
(Beware that this is still work-in-progress)
===== Purpose and scope. =====
This coding guide is a set of rules and regulations concerning how the actual source code should look like. To ensure consistency, all the source code of the HALFRED project shall conform to this guide. At this point any exceptions that are somehow needed should be reported, in order to enable early improvements to the rules.

===== Project deliverables, versioning and development process. =====
It is assumed that this project delivers software in the form of a source code. The code is prepared in a version control repository. The development process is aimed at releasing a consistent distribution of the project contents called "release", every one and a while. The official releases should have unique version numbers in a form of:

   xx.yy.zz

where:
  * xx denotes the major version number - changes in this number reflect only big steps in the project development (like big architecture change, major source code reorganization etc.)
  * yy denotes the minor version number - changes in this number reflect API changes in the project modules
  * zz denotes the maintenance number - changes in this number reflect corrections and bug fixes made to the release after it was done (service packs)
The unofficial releases (snapshots, nightly builds, bleeding edge releases) should have a form of

   xx.yy.zz.revision

where:
  * revision adds the information about version control revision that was used to prepare the release

The structure of the **version control repository (SVN)** should reflect the development process. Each major project version should have it's own repository. Inside the repository the main directory structure should reflect the major and minor version number and inside each of the major folders the the standard SVN pattern should follow. Example:

   root
      0.1
         trunk
         branches
         tags
            0.1.0
            0.1.1
      0.2
         trunk
         branches
         tags
            0.2.0
            0.2.1
         
===== Folder structure. =====
The trunk folder in each of the main development branches should hold the current version of the distribution. The folder structure should look like this:
   TODO
   
===== File and folder names. =====

All the file names and folder names should be spelled with lowercase letters. No spaces allowed. Instead of a space use underscore ("_"). Don't use other special characters like ~ ` ! @ # $ % ^ & * ( ) + = etc.

===== Coding rules =====

==== Source file layout ====

=== Language and character encoding ===

All the code and comments must be written in English. All the files should be encoded using [[http://en.wikipedia.org/wiki/UTF-8|UTF-8]]. There shall be no non-ASCII characters in the code. This rule is also strongly advised for comments. One exception is when spelling person or organization names, however even then conversion to ASCII characters is preferred. 

=== Line length ===

Single line length should be limited to 100 characters. In special cases the line can be extended to 130 characters. More is strongly discouraged. 

=== Indentation, tabs and spaces ===

Don't use tabs! Configure your editor to insert 4 spaces instead of the tab character. Nearly every editor has this option. You can also use the [[http://astyle.sourceforge.net/|AStyle]] program to convert tabs to spaces. 

A single indentation should have 4 spaces - no more, no less.

=== File information ===

Each and every source file should start with a standard file information section. The format of this section should look like this:

<code cpp>
/* =========================================================================================== *//**
 @file        serial_port.cpp
 @authors     Albert Einstein, Niels Bohr
 @version     $Id$
 @package     HALFRED port
 @brief       Serial port driver
 @hardware    STM32F4xx
 @copyright   $Copyright$
 @details     Implementation of the serial port driver (USART) for STM32F4xx microcontroller using
              interrupts and data buffering.

*//* ============================================================================================ */
</code>

++++See more details |
The format of this section is parsable by Doxygen. 

  * The $Id$ and $Copyright$ fields are meant to be replaced automatically during release to add revision and license information respectfully. 
  * The package field should contain strings like:
    * HALFRED if the file is a core file and is hardware independendent
    * HALFRED port for <MICROCONTROLLER_FAMILY_NAME> if the file belongs to the port
  * The author field should list the initial author of the file and all significant contributors. If you make a change to the file created by somebody else, decide if the change is significant (added functionality, API change) and if is, add yourself to the list of authors at the end.
  * The brief field should describe in one sentence the purpose of the file
  * The hardware field should say "Independent" if the file is general and not dependent on hardware, or list the compatible/supported hardware
  * The details field should describe in more detail the contents of the file. This place is also used for notes, remarks and warnings.
++++

==== Style of coding ====

=== K&R Indent style ===

We're using the [[http://en.wikipedia.org/wiki/1_true_brace_style#K.26R_style|K&R style]] of code formatting in the 1TBS variant. 
++++See precise explanation |
Each function has its opening brace at the next line on the same indentation level as its header, the statements within the braces are indented, and the closing brace at the end is on the same indentation level as the header of the function at a line of its own. The blocks inside a function, however, have their opening braces at the same line as their respective control statements; closing braces remain in a line of their own, unless followed by an else or while keyword.  The constructs that allow insertions of new code lines are on separate lines, and constructs that prohibit insertions are on a single line. This principle is amplified by bracing every if, else, while, etc.—including single-line conditionals—so that insertion of a new line of code anywhere is always "safe" (i.e., such an insertion will not make the flow of execution disagree with the source code indentation).
++++
++++See example |
<code cpp>
int main(int argc, char *argv[])
{
    ...
    while (x == y) {
        something();
        somethingelse();
 
        if (some_error) {
            do_correct();
        } else {
            // must surround each statement with curly braces
            continue_as_usual();
        }
    }
    
    // "empty" statements shall be clearly stated using ';'
    while (pollSomething()) {
        ;
    }
     
    finalthing();
    ...
}
</code>
++++

=== Symbol names ===

We generally follow the camelCase notation with lower-case letter first for instances and upper-case letter for types. The following naming convention shall be used:

All the variables (local and global) and all class properties shall be spelled with lower-case letter first. Each sequential word in the name shall be spelled with capital letter.
Example: 
<code cpp>
int myLocalVariable;
</code>

All method and function names shall be named using the same convention as variables.
Example:
<code cpp>
void doSomething();
int MyClass::getSomeValue();
</code>

Accessors and mutators (get and set functions) should match the name of the variable they are getting and setting.
Example:
<code cpp>
class MyClass {
private:
    int myValue;    
public:
    void setMyValue(int newValue);
    int getMyValue();
};
</code>

All compile time constants shall be named starting with a "k" letter. Each sequential word in the name shall be spelled with capital letter.
Example:
<code cpp>
const int kDaysInWeek = 7;
</code>

All types and class names shall be spelled with capital letter. Each sequential word in the name shall also be spelled with capital letter.
Example: <code cpp>
class MyClass;
enum SerialPortMode {
  ...
};
struct USBEndpointDescriptor;
</code>

Namespaces shall be spelled with lower-case letters only. It's thus best to keep them one-word.
Example: 
<code cpp>
namespace microhal {
   ...
} // namespace microhal
</code>

Preprocessor symbols shall be spelled with capital letters only. Each word shall be separated by an underscore. Macros representing behavior shall indicate this by including () braces. 
Example: 
<code cpp>
#define MY_MACRO()               do { .. } while (0)
#define NUMBER_OF_ELEMENTS       12
</code>

Enumerated values shall be named like preprocessor symbols. The names of enumerated symbols shall be more than less explicit.
Example:
<code cpp>
enum SerialPortParity {
    NO_PARITY
    EVEN_PARITY,
    ODD_PARITY,
};
</code>

Finally: whatever you do - be consistent!

=== Preprocessor ===

Avoid using preprocessor whenever usage of a substitute %%C++%% feature is possible (constants, constexpr, inlining, templates). However if that's absolutely necessary, the preprocessor expressions should follow the following rules:

Control sequences in macros shall be surrounded by a do { .. } while (0) construct and shall indicate the control behavior by including () braces at the end of the macro name.
<code cpp>
#define DO_SOMETHING()     do { doSomething(); } while(0)
</code>

Value calculations shall be always enclosed in (..) braces. This also applies to macro arguments. Remember that preprocessor is a simple copy-paste tool.
<code cpp>
#define TO_RADIANS(degrees)          (((degrees)*PI) / 180)
</code>


=== Abbreviations ===

Avoid abbreviations, even if this results in a longer name (the IDEs have auto-completion feature these days).

Good example: 
<code cpp>
setThreadPriority();
setBaudrate();
</code>
Bad example: 
<code cpp>
setThreadPrio()
setBaud();
</code>

There may be some exceptions to this rule, including abbreviations that are almost never used in the full form, such as: max (maximum), min (minimum), ptr (pointer - ptr is used in this form across all %%C++%%, for example nullptr).

==== Header files ====

=== General ===
Every %%C++%% source file (*.cpp) should have it's own header file (*.h). The header file should provide all the means to use the contents of the associate source file. However the header file should reveal only what is necessary to use the provided functionality and hide the details. 

=== Protection against multiple inclusion ===
All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be: NAME_OF_THE_FILE_H

++++see additional example and explanation | 
In example, for a header file named my_class.h the define guard should look like this

<code cpp>
#ifndef MY_CLASS_H
#define MY_CLASS_H
// header contents follow here

#endif // MY_CLASS_H
</code>
++++

==== Documenting the source code ====
