You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

866 lines
31 KiB

  1. # KiCad C++ Source Code Style Guide #
  2. Latest Publishing: February 2017
  3. First Published: September 2010
  4. written by
  5. Wayne Stambaugh \<<stambaughw@gmail.com>\>
  6. and
  7. Dick Hollenbeck \<<dick@softplc.com>\>
  8. [TOC]
  9. # 1. Introduction # {#csp_intro}
  10. The purpose of this document is to provide a reference guide for KiCad
  11. developers about how source code should be styled and formatted in
  12. KiCad. It is not a comprehensive programming guide because it does not
  13. discuss many things such as software engineering strategies, source
  14. directories, existing classes, or how to internationalize text. The goal
  15. is to make all of the KiCad source conform to this guide.
  16. ## 1.1 Why Coding Style Matters ## {#why}
  17. You may be thinking to yourself that using the style defined in this
  18. document will not make you a good programmer and you would be correct.
  19. Any given coding style is no substitute for experience. However, any
  20. experienced coder will tell that the only thing worse than looking at
  21. code that is not in your preferred coding style, is looking at twenty
  22. different coding styles that are not your preferred coding style.
  23. Consistency makes a) problems easier to spot, and b) looking at code for
  24. long periods of time more tolerable.
  25. ## 1.2 Enforcement ## {#enforcement}
  26. The KiCad coding police are not going to break down your door and beat
  27. you with your keyboard if you don't follow these guidelines (although
  28. there are those who would argue that they should). However, there are
  29. some very sound reasons why you should follow them. If you are
  30. contributing patches, you are much more likely to be taken seriously by
  31. the primary developers if your patches are formatted correctly. Busy
  32. developers don't have the time to go back and reformat your code. If you
  33. have a desire to become a regular KiCad developer with commit access to
  34. the development branch, you're not likely to get a glowing
  35. recommendation by the lead developers if you will not follow these
  36. guidelines. It is just good programming courtesy to follow this policy
  37. because it is respectful of the investment already made by the existing
  38. developers. The other KiCad developers will appreciate your effort.
  39. **Warning**
  40. **Do not modify this document without the consent of the project
  41. leader. All changes to this document require approval.**
  42. ## 1.3 Tools ## {#tools}
  43. There are some tools that can help you format your code easily.
  44. [`clang-format`][clang-format] is a formatting tool that can both be used to
  45. provide code-style automation to your editor of choice, as well as allow git to
  46. check formatting when committing (using a "Git hook"). You should install this
  47. program to be able to use the Git hooks.
  48. The style config file is `_clang-format`, and should be picked up automatically
  49. by `clang-format` when the `--style=file` option is set.
  50. To enable the Git hooks (only needs to be done once per Git repo):
  51. git config core.hooksPath .githooks
  52. Set the `git clang-format` tool to use the provided `_clang-format` file:
  53. git config clangFormat.style file
  54. Then, to enable the format checker, set the `kicad.check-format` Git config
  55. to "true" for the KiCad repo:
  56. git config kicad.check-format true
  57. Without this config, the format checker will not run on commit, but you can
  58. still check files staged for commit manually (see below).
  59. If the hook is enabled, when you commit a change, you will be told if you
  60. have caused any style violations (only in your changed code). You can then fix
  61. the errors, either manually, or with the tools below.
  62. If you are warned about formatting errors, but you are sure your style is correct,
  63. you can still commit:
  64. git commit --no-verify
  65. ### Correcting Formatting Errors ## {#correcting-formatting-errors}
  66. There is a Git aliases file that provides the right commands to show and correct
  67. formatting errors. Add to your repository config by running this command from
  68. the source directory:
  69. git config --add include.path $(pwd)/helpers/git/format_alias
  70. Then you can use the following aliases:
  71. * `git check-format`: show any formatting warnings (but make no changes)
  72. * `git fix-format`: correct formatting (you will need to `git add` afterwards)
  73. These aliases use a script, `tools/check-coding.sh`, which takes care of only
  74. checking the formatting for files that should be formatted. This script has
  75. other uses:
  76. * Make (or see only) violations in files modified in the previous commit (useful
  77. when interactive-rebasing):
  78. * `check_coding.sh --amend [--diff]`
  79. # 2. Naming Conventions # {#naming_conventions}
  80. Before delving into anything as esoteric as indentation and formatting,
  81. naming conventions need to be addressed. This section does not attempt
  82. to define what names you use for your code. Rather, it defines the style
  83. for naming. See the references section for links to some excellent
  84. coding references. When defining multiple word names use the following
  85. conventions for improved readability:
  86. - Use underscores for all upper and all lower case variables to make
  87. multiple word names more readable.
  88. - Use camel case for mixed case variable names.
  89. Avoid mixing camel case and underscores.
  90. **Examples**
  91. ~~~~~~~~~~~~~{.cpp}
  92. CamelCaseName // if camelcase, then no underscores
  93. all_lower_case_name
  94. ALL_UPPER_CASE_NAME
  95. ~~~~~~~~~~~~~
  96. ## 2.1 Class, Type Definitions, Name Space, and Macro Names ## {#definitions}
  97. Class, typedef, enum, name space, and macro names should be comprised of
  98. all capital letters.
  99. **Examples**
  100. ~~~~~~~~~~~~~{.cpp}
  101. class SIMPLE
  102. #define LONG_MACRO_WITH_UNDERSCORES
  103. typedef boost::ptr_vector<PIN> PIN_LIST;
  104. enum KICAD_T {...};
  105. ~~~~~~~~~~~~~
  106. ## 2.2 Local, Private and Automatic Variables ## {#local_variables}
  107. The first character of automatic, static local, and private variable
  108. names should be lower case. This indicates that the variable will not be
  109. “visible” outside of the function, file, or class where they are
  110. defined, respectively. The limited visibility is being acknowledged with
  111. the lowercase starting letter, where lowercase is considered to be less
  112. boisterous than uppercase.
  113. **Examples**
  114. ~~~~~~~~~~~~~{.cpp}
  115. int i;
  116. double aPrivateVariable;
  117. static char* static_variable = NULL;
  118. ~~~~~~~~~~~~~
  119. ## 2.3 Public and Global Variables ## {#global_variables}
  120. The first character of public and global variable names are to be
  121. uppercase. This indicates that the variable is visible outside the class
  122. or file in which it was defined. (An exception is the use of prefix `g_`
  123. which is also sometimes used to indicate a global variable.)
  124. **Example**
  125. ~~~~~~~~~~~~~{.cpp}
  126. char* GlobalVariable;
  127. ~~~~~~~~~~~~~
  128. ## 2.4 Local, Private and Static Functions ## {#functions}
  129. The first character of local, private, and static functions should be
  130. lower case. This indicates that the function is not visible outside the
  131. class or file where it is defined.
  132. **Example**
  133. ~~~~~~~~~~~~~{.cpp}
  134. bool isModified();
  135. static int buildList( int* list );
  136. ~~~~~~~~~~~~~
  137. ## 2.5 Function Arguments ## {#function_arguments}
  138. Function arguments are prefixed with an 'a' to indicate these are
  139. arguments to a function. The 'a' stands for “argument”, and it also
  140. enables clever and concise Doxygen comments.
  141. **Example**
  142. ~~~~~~~~~~~~~{.cpp}
  143. /*/** */*
  144. * Copy aFoo into this instance.
  145. */
  146. void SetFoo( int aFoo );
  147. ~~~~~~~~~~~~~
  148. Notice how the reader can say “a Foo” to himself when reading this.
  149. ## 2.6 Pointers ## {#pointers}
  150. It is not desired to identify a pointer by building a 'p' into the
  151. variable name. The pointer aspect of the variable pertains to type, not
  152. purpose.
  153. **Example**
  154. ~~~~~~~~~~~~~{.cpp}
  155. MODULE* module;
  156. ~~~~~~~~~~~~~
  157. The purpose of the variable is that it represents a MODULE. Something
  158. like `p_module` would only make that harder to discern.
  159. ## 2.7 Accessing Member Variables and Member Functions ## {#accessing_members}
  160. We do not use “`this->`” to access either member variables or member
  161. functions from within the containing class. We let C++ perform this for
  162. us.
  163. # 3. Commenting # {#commenting}
  164. Comments in KiCad typically fall into two categories: in line code
  165. comments and Doxygen comments. In line comments have no set formatting
  166. rules other than they should have the same indent level as the code if
  167. they do not follow a statement. In line comments that follow statements
  168. should not exceed 99 columns unless absolutely necessary. The prevents
  169. word wrapping in an editor when the viewable columns is set to 100. In
  170. line comments can use either the C++ or the C commenting style, but C++
  171. comments are preferred for single line comments or comments consisting
  172. of only a few lines.
  173. ## 3.1 Blank Lines Above Comments ## {#blank_lines_above_comments}
  174. If a comment is the first thing on a line, then that comment should have
  175. one or more blank lines above them. One blank line is preferred.
  176. ## 3.2 Doxygen ## {#doxygen}
  177. Doxygen is a C++ source code documenting tool used by the project. Descriptive
  178. *.html files can be generated from the source code by installing Doxygen and
  179. building the target named **doxygen-docs** and **dev-docs** that include this
  180. document.
  181. $ cd <kicad_build_base>
  182. $ make doxygen-docs
  183. The generated source \*.html files will be placed into
  184. \<kicad\_project\_base\>/Documentation/doxygen/html/ and the developer's
  185. \*.html files will be placed into
  186. \<kicad\_project\_base\>/Documentation/development/doxygen/html/
  187. Doxygen comments are used to build developer documentation from the
  188. source code. They should normally be only placed in header files and not
  189. in \*.cpp files. This eliminates the obligation to keep two comments in
  190. agreement with each other. If the class, function, or enum, etc. is
  191. only defined in a \*.cpp source file and not present in any header file,
  192. in which case the Doxygen comments should go into the \*.cpp source file.
  193. Again, avoid duplicating the Doxygen comments in both the header and
  194. \*.cpp source files.
  195. KiCad uses the JAVADOC comment style defined in the [“Documenting the
  196. code”][doccode] section of the Doxygen [manual][manual]. Don't forget
  197. to use the special Doxygen tags: bug, todo, deprecated, etc., so other
  198. developers can quickly get useful information about your code. It is
  199. good practice to actually generate the Doxygen \*.html files by
  200. building target doxygen-docs, and then to review the quality of your
  201. Doxygen comments with a web browser before submitting a patch.
  202. [doccode]: http://www.doxygen.nl/manual/docblocks.html
  203. [manual]: http://www.doxygen.nl/manual
  204. ### 3.2.1 Function Comments ### {#function_comments}
  205. These go into a header file, unless the function is a private (i.e.
  206. static) function known only to a \*.cpp file. The format of a function
  207. comment is chosen to serve a dual purpose role: delineation of the
  208. function declaration within the source code and to create a consistent
  209. leading sentence in the doxygen html output. The chosen format is
  210. to use a descriptive single line sentence, followed by a blank line,
  211. followed by an optional detailed description as the shown in the example
  212. below.
  213. **Example**
  214. ~~~~~~~~~~~~~{.cpp}
  215. /*/** */*
  216. * Format and write text to an output stream.
  217. *
  218. * A really detailed description goes here if it's needed.
  219. *
  220. * @param aMestLevel is the multiple of spaces to precede the output with.
  221. * @param aFmt is a printf() style format string.
  222. * @param ... is a variable list of parameters that will get blended into
  223. * the output under control of the format string.
  224. * @return the number of characters output.
  225. * @throw IO_ERROR, if there is a problem outputting.
  226. */
  227. int PRINTF_FUNC Print( int aNestLevel, const char* aFmt, ... );
  228. ~~~~~~~~~~~~~
  229. The single line description goes on the 2nd line of the comment. The
  230. \@return keyword if present, should describe the return value followed
  231. by a hyphen. The \@param keyword names a function parameter and the text
  232. following should flow like a normal English sentence.
  233. ### 3.2.2 Class Comments ### {#class_comments}
  234. A class comment describes a class declaration by giving the purpose and
  235. use of the class. Its format is similar to a function comment. Doxygen
  236. can use the html \<p\> (paragraph designation) to begin a new paragraph
  237. in its output. So if the text of the comment is large, break it put into
  238. multiple paragraphs.
  239. **Example**
  240. ~~~~~~~~~~~~~{.cpp}
  241. /*/** */*
  242. * An interface (abstract) class used to output UTF8 text in a
  243. * convenient way.
  244. *
  245. * The primary interface is "printf() like" but with support for
  246. * indentation control. The destination of the 8 bit wide text is
  247. * up to the implementer.
  248. * <p>
  249. * The implementer only has to implement the write() function, but
  250. * can also optionally re-implement GetQuoteChar().
  251. * <p>
  252. * If you want to output a wxString, then use CONV_TO_UTF8() on it
  253. * before passing it as an argument to Print().
  254. * <p>
  255. * Since this is an abstract interface, only classes derived from
  256. * this one may actually be used.
  257. */
  258. class OUTPUTFORMATTER
  259. {
  260. ~~~~~~~~~~~~~
  261. # 4. Formatting # {#formatting}
  262. This section defines the formatting style used in the KiCad source.
  263. ## 4.1 Indentation ## {#indentation}
  264. The indentation level for the KiCad source code is defined as four
  265. spaces. Please do not use tabs.
  266. ### 4.1.1 Defines ### {#defines}
  267. There should be only one space after a \#define statement.
  268. ### 4.1.2 Column Alignment ### {#column_alignment}
  269. Please try to align multiple consecutive similar lines into consistent
  270. columns when possible, such as \#define lines which can be thought of as
  271. containing 4 columns: \#define, symbol, value, and comment. Notice how
  272. all 4 columns are aligned in the example below.
  273. **Example**
  274. ~~~~~~~~~~~~~{.cpp}
  275. #define LN_RED 12 // my favorite
  276. #define LN_GREEN 13 // eco friendly
  277. ~~~~~~~~~~~~~
  278. Another common case is the declaration of automatic variables. These are
  279. preferably shown in columns of type and variable name.
  280. ## 4.2 Blank Lines ## {#blank_lines}
  281. ### 4.2.1 Function Declarations ### {#function_declarations}
  282. There should be 1 blank line above a function declaration in a class
  283. file if that function declaration is presented with a Javadoc comment.
  284. This is consist with the statement above about blank lines above
  285. comments.
  286. ### 4.2.2 Function Definitions ### {#function_definitions}
  287. Function definitions in *.cpp files will not typically be accompanied by
  288. any comment, since those are normally only in the header file. It is
  289. desirable to set off the function definition within the *.cpp file by
  290. leaving two blank lines above the function definition.
  291. ### 4.2.3 If Statements ### {#if_statements}
  292. There should be one blank line above if statements.
  293. ## 4.3 Line Length ### {#line_length}
  294. The maximum line width is 99 columns. An exception to this is a long
  295. quoted string such as the internationalized text required to satisfy
  296. MSVC++, described below.
  297. ## 4.4 Strings ## {#strings}
  298. The KiCad project team no longer supports compiling with Microsoft
  299. Visual C++. When you need to break long strings into smaller substrings,
  300. please use the C99 compliant method for improved readability. Using
  301. any of previously accepted methods defined below for breaking
  302. long internationalized strings will no longer be accepted.
  303. **Examples**
  304. ~~~~~~~~~~~~~{.cpp}
  305. // This works with C99 compliant compilers is the **only** accepted method:
  306. wxChar* foo = _( “this is a long string broken ”
  307. “into pieces for readability.” );
  308. // This works with MSVC, breaks POEdit, and is **not** acceptable:
  309. wxChar* foo = _( “this is a long string broken ”
  310. L“into pieces for readability” );
  311. // This works with MSVC, is ugly, and is **not** accepted:
  312. wxChar* foo = _( “this is a long string \
  313. broken into pieces for readability” );
  314. ~~~~~~~~~~~~~
  315. A second acceptable solution is to simply put the text all on one
  316. line, even if it exceeds the 99 character line length limit. However,
  317. the preferred method is to break strings within the 99 character limit
  318. whenever possible to prevent wrapping.
  319. ## 4.5 Trailing Whitespace ## {#trailing_whitespace}
  320. Many programming editors conveniently indent your code for you. Some of
  321. them do it rather poorly and leave trailing whitespace. Thankfully, most
  322. editors come with a remove trailing whitespace macro or at least a
  323. setting to make trailing whitespace visible so you can see it and
  324. manually remove it. Trailing whitespace is known to break some text
  325. parsing tools. It also leads to unnecessary diffs in the version control
  326. system. Please remove trailing whitespace.
  327. ## 4.6 Multiple Statements per Line ## {#multiple_statements_per_line}
  328. It is generally preferred that each statement be placed on its own line.
  329. This is especially true for statements without keywords.
  330. **Example**
  331. ~~~~~~~~~~~~~{.cpp}
  332. x=1; y=2; z=3; // Bad, should be on separate lines.
  333. ~~~~~~~~~~~~~
  334. ## 4.7 Braces ## {#braces}
  335. Braces should be placed on the line proceeding the keyword and indented
  336. to the same level. It is not necessary to use braces if there is only a
  337. single line statement after the keyword. In the case of if..else
  338. if..else, indent all to the same level.
  339. **Example**
  340. ~~~~~~~~~~~~~{.cpp}
  341. void function()
  342. {
  343. if( foo )
  344. {
  345. statement1;
  346. statement2;
  347. }
  348. else if( bar )
  349. {
  350. statement3;
  351. statement4;
  352. }
  353. else
  354. statement5;
  355. }
  356. ~~~~~~~~~~~~~
  357. ## 4.8 Parenthesis ## {#parenthesis}
  358. Parenthesis should be placed immediately after function names and
  359. keywords. Spaces should be placed after the opening parenthesis, before
  360. the closing parenthesis, and between the comma and the next argument in
  361. functions. No space is needed if a function has no arguments.
  362. **Example**
  363. ~~~~~~~~~~~~~{.cpp}
  364. void Function( int aArg1, int aArg2 )
  365. {
  366. while( busy )
  367. {
  368. if( a || b || c )
  369. doSomething();
  370. else
  371. doSomethingElse();
  372. }
  373. }
  374. ~~~~~~~~~~~~~
  375. ## 4.9 Switch Formatting ## {#switch}
  376. The case statement is to be indented to the same level as the switch.
  377. **Example**
  378. ~~~~~~~~~~~~~{.cpp}
  379. switch( foo )
  380. {
  381. case 1:
  382. doOne();
  383. break;
  384. case 2:
  385. doTwo();
  386. // Fall through.
  387. default:
  388. doDefault();
  389. }
  390. ~~~~~~~~~~~~~
  391. It is permitted to place all cases on a single line each, if that makes the
  392. code more readable. This is often done for look-ups or translation functions. In
  393. this case, you will have to manually align for readability as appropriate and
  394. reject clang-format's suggested changes, if you use it:
  395. ~~~~~~~~~~~~~{.cpp}
  396. switch( m_orientation )
  397. {
  398. case PIN_RIGHT: m_orientation = PIN_UP; break;
  399. case PIN_UP: m_orientation = PIN_LEFT; break;
  400. case PIN_LEFT: m_orientation = PIN_DOWN; break;
  401. case PIN_DOWN: m_orientation = PIN_RIGHT; break;
  402. }
  403. ~~~~~~~~~~~~~
  404. # 5. License Statement # {#license_statement}
  405. There is a the file copyright.h which you can copy into the top of
  406. your new source files and edit the \<author\> field. KiCad depends on
  407. the copyright enforcement capabilities of copyright law, and this
  408. means that source files must be copyrighted and not be released into
  409. the public domain. Each source file has one or more owners.
  410. # 6. Header Files # {#header_files}
  411. Project \*.h source files should:
  412. - contain a license statement
  413. - contain a nested include \#ifndef
  414. - be fully self standing and not depend on other headers that are not
  415. included within it.
  416. The license statement was described above.
  417. ## 6.1 Nested Include #ifndef ## {#nested_include}
  418. Each header file should include an \#ifndef which is commonly used to
  419. prevent compiler errors in the case where the header file is seen
  420. multiple times in the code stream presented to the compiler. Just
  421. after the license statement, at the top of the file there should be
  422. lines similar to these (but with a file name specific token other than
  423. `RICHIO_H_`):
  424. ~~~~~~~~~~~~~{.cpp}
  425. #ifndef RICHIO_H_
  426. #define RICHIO_H_
  427. ~~~~~~~~~~~~~
  428. And at the very bottom of the header file, use a line like this one:
  429. ~~~~~~~~~~~~~{.cpp}
  430. #endif // RICHIO_H_
  431. ~~~~~~~~~~~~~
  432. The \#ifndef wrapper begins after the license statement, and ends at
  433. the very bottom of the file. It is important that it wrap any nested
  434. \#include statements, so that the compiler can skip them if the
  435. \#ifndef evaluates to false, which will reduce compilation time.
  436. ## 6.2 Headers Without Unsatisfied Dependencies ## {#header_depends}
  437. Any header file should include other headers that it depends on. (Note:
  438. KiCad is not at this point now, but this section is a goal of the
  439. project.)
  440. It should be possible to run the compiler on any header file within the
  441. project, and with proper include paths being passed to the compiler, the
  442. header file should compile without error.
  443. **Example**
  444. $ cd /svn/kicad/testing.checkout/include
  445. $ g++ wx-config --cxxflags -I . xnode.h -o /tmp/junk
  446. Such structuring of the header files removes the need within a client
  447. \*.cpp file to include some project header file before some other project
  448. header file. (A client \*.cpp file is one that intends to **use, not
  449. implement,** the public API exposed within the header file.)
  450. Client code should not have to piece together things that a header file
  451. wishes to expose. The exposing header file should be viewed as a fully
  452. sufficient **ticket to use** the public API of that header file.
  453. This is not saying anything about how much to expose, only that that
  454. which is exposed needs to be fully usable merely by including the header
  455. file that exposes it, with no additional includes.
  456. For situations where there is a class header file and an
  457. implementation \*.cpp file, it is desirable to hide as much of the
  458. private implementation as is practical and any header file that is not
  459. needed as part of the public API can and should be included only in
  460. the implementation \*.cpp file. However, the number one concern of
  461. this section is that client (using) code can use the public API which
  462. is exposed in the header file, merely by including that one header
  463. file.
  464. # 7. I Wrote X Lines of Code Before I Read This Document # {#x_lines}
  465. It's OK. We all make mistakes. Fortunately, KiCad provides a
  466. configuration file for the code beautifier uncrustify. Uncrustify won't
  467. fix your naming problems but it does a pretty decent job of formatting
  468. your source code. There are a few places where uncrustify makes some
  469. less than ideal indentation choices. It struggles with the string
  470. declaration macros wxT(“”) and \_(“”) and functions used as arguments to
  471. other functions. After you uncrustify your source code, please review the
  472. indentation for any glaring errors and manually fix them. See the
  473. uncrustify [website][uncrustify] for more information.
  474. [uncrustify]: http://uncrustify.sourceforge.net/
  475. # 8. Show Me an Example # {#show_me_an_example}
  476. Nothing drives the point home like an example. The source file richio.h
  477. below was taken directly from the KiCad source.
  478. ~~~~~~~~~~~~~{.cpp}
  479. /*
  480. * This program source code file is part of KICAD, a free EDA CAD application.
  481. *
  482. * Copyright (C) 2007-2010 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  483. * Copyright (C) 2007 KiCad Developers, see change_log.txt for contributors.
  484. *
  485. * This program is free software; you can redistribute it and/or
  486. * modify it under the terms of the GNU General Public License
  487. * as published by the Free Software Foundation; either version 2
  488. * of the License, or (at your option) any later version.
  489. *
  490. * This program is distributed in the hope that it will be useful,
  491. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  492. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  493. * GNU General Public License for more details.
  494. *
  495. * You should have received a copy of the GNU General Public License
  496. * along with this program; if not, you may find one here:
  497. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  498. * or you may search the http://www.gnu.org website for the version 2 license,
  499. * or you may write to the Free Software Foundation, Inc.,
  500. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  501. */
  502. #ifndef RICHIO_H_
  503. #define RICHIO_H_
  504. // This file defines 3 classes useful for working with DSN text files and is named
  505. // "richio" after its author, Richard Hollenbeck, aka Dick Hollenbeck.
  506. #include <string>
  507. #include <vector>
  508. // I really did not want to be dependent on wxWidgets in richio
  509. // but the errorText needs to be wide char so wxString rules.
  510. #include <wx/wx.h>
  511. #include <cstdio> // FILE
  512. /*/** */*
  513. * A class used to hold an error message and may be used to throw exceptions
  514. * containing meaningful error messages.
  515. */
  516. struct IOError
  517. {
  518. wxString errorText;
  519. IOError( const wxChar* aMsg ) :
  520. errorText( aMsg )
  521. {
  522. }
  523. IOError( const wxString& aMsg ) :
  524. errorText( aMsg )
  525. {
  526. }
  527. };
  528. /*/** */*
  529. * Read single lines of text into a buffer and increments a line number counter.
  530. */
  531. class LINE_READER
  532. {
  533. protected:
  534. FILE* fp;
  535. int lineNum;
  536. unsigned maxLineLength;
  537. unsigned length;
  538. char* line;
  539. unsigned capacity;
  540. public:
  541. /*/** */*
  542. * @param aFile is an open file in "ascii" mode, not binary mode.
  543. * @param aMaxLineLength is the number of bytes to use in the line buffer.
  544. */
  545. LINE_READER( FILE* aFile, unsigned aMaxLineLength );
  546. ~LINE_READER()
  547. {
  548. delete[] line;
  549. }
  550. /*
  551. int CharAt( int aNdx )
  552. {
  553. if( (unsigned) aNdx < capacity )
  554. return (char) (unsigned char) line[aNdx];
  555. return -1;
  556. }
  557. */
  558. /*/** */*
  559. * Read a line of text into the buffer and increments the line number
  560. * counter.
  561. *
  562. * @return is the number of bytes read, 0 at end of file.
  563. * @throw IO_ERROR when a line is too long.
  564. */
  565. int ReadLine();
  566. operator char* ()
  567. {
  568. return line;
  569. }
  570. int LineNumber()
  571. {
  572. return lineNum;
  573. }
  574. unsigned Length()
  575. {
  576. return length;
  577. }
  578. };
  579. /*/** */*
  580. * An interface (abstract class) used to output ASCII text in a convenient way.
  581. *
  582. * The primary interface is printf() like with support for indentation control.
  583. * The destination of the 8 bit wide text is up to the implementer. If you want
  584. * to output a wxString, then use CONV_TO_UTF8() on it before passing it as an
  585. * argument to Print().
  586. * <p>
  587. * Since this is an abstract interface, only classes derived from this one
  588. * will be the implementations.
  589. * </p>
  590. */
  591. class OUTPUTFORMATTER
  592. {
  593. #if defined(__GNUG__) // The GNU C++ compiler defines this
  594. // When used on a C++ function, we must account for the "this" pointer,
  595. // so increase the STRING-INDEX and FIRST-TO_CHECK by one.
  596. // See http://docs.freebsd.org/info/gcc/gcc.info.Function_Attributes.html
  597. // Then to get format checking during the compile, compile with -Wall or -Wformat
  598. #define PRINTF_FUNC __attribute__ ((format (printf, 3, 4)))
  599. #else
  600. #define PRINTF_FUNC // nothing
  601. #endif
  602. public:
  603. /*/** */*
  604. * Format and write text to the output stream.
  605. *
  606. * @param nestLevel is the multiple of spaces to preceed the output with.
  607. * @param fmt is a printf() style format string.
  608. * @param ... is a variable list of parameters that will get blended into
  609. * the output under control of the format string.
  610. * @return the number of characters output.
  611. * @throw IO_ERROR if there is a problem outputting, such as a full disk.
  612. */
  613. virtual int PRINTF_FUNC Print( int nestLevel, const char* fmt, ... ) = 0;
  614. /*/** */*
  615. * Return the quoting character required for aWrapee.
  616. *
  617. * Return the quote character as a single character string for a given
  618. * input wrapee string. If the wrappee does not need to be quoted,
  619. * the return value is "" (the null string), such as when there are no
  620. * delimiters in the input wrapee string. If you want the quote character
  621. * to be assuredly not "", then pass in "(" as the wrappee.
  622. * <p>
  623. * Implementations are free to override the default behavior, which is to
  624. * call the static function of the same name.
  625. * </p>
  626. *
  627. * @param aWrapee is a string that might need wrapping on each end.
  628. * @return the quote character as a single character string, or ""
  629. * if the wrapee does not need to be wrapped.
  630. */
  631. virtual const char* GetQuoteChar( const char* aWrapee ) = 0;
  632. virtual ~OUTPUTFORMATTER() {}
  633. /*/** */*
  634. * Get the quote character according to the Specctra DSN specification.
  635. *
  636. * @param aWrapee is a string that might need wrapping on each end.
  637. * @param aQuoteChar is a single character C string which provides the current
  638. * quote character, should it be needed by the wrapee.
  639. *
  640. * @return the quote_character as a single character string, or ""
  641. * if the wrapee does not need to be wrapped.
  642. */
  643. static const char* GetQuoteChar( const char* aWrapee, const char* aQuoteChar );
  644. };
  645. /*/** */*
  646. * Implement an OUTPUTFORMATTER to a memory buffer.
  647. */
  648. class STRINGFORMATTER : public OUTPUTFORMATTER
  649. {
  650. std::vector<char> buffer;
  651. std::string mystring;
  652. int sprint( const char* fmt, ... );
  653. int vprint( const char* fmt, va_list ap );
  654. public:
  655. /*/** */*
  656. * Reserve space in the buffer
  657. */
  658. STRINGFORMATTER( int aReserve = 300 ) :
  659. buffer( aReserve, '\0' )
  660. {
  661. }
  662. /*/** */*
  663. * Clears the buffer and empties the internal string.
  664. */
  665. void Clear()
  666. {
  667. mystring.clear();
  668. }
  669. /*/** */*
  670. * Remove whitespace, '(', and ')' from the internal string.
  671. */
  672. void StripUseless();
  673. std::string GetString()
  674. {
  675. return mystring;
  676. }
  677. //-----<OUTPUTFORMATTER>------------------------------------------------
  678. int PRINTF_FUNC Print( int nestLevel, const char* fmt, ... );
  679. const char* GetQuoteChar( const char* wrapee );
  680. //-----</OUTPUTFORMATTER>-----------------------------------------------
  681. };
  682. #endif // RICHIO_H_
  683. ~~~~~~~~~~~~~
  684. # 9. Resources # {#resources}
  685. There are plenty of excellent resources on the Internet on C++ coding
  686. styles and coding do's and don'ts. Here are a few useful ones. In most
  687. cases, the coding styles do not follow the KiCad coding style but there
  688. is plenty of other good information here. Besides, most of them have
  689. some great humor in them enjoyable to read. Who knows, you might even
  690. learn something new.
  691. - [C++ Coding Standard][cppstandard]
  692. - [Linux Kernel Coding Style][kernel]
  693. - [C++ Operator Overloading Guidelines][overloading]
  694. - [Wikipedia's Programming Style Page][style]
  695. [clang-format]: https://clang.llvm.org/docs/ClangFormat.html
  696. [cppstandard]:http://www.possibility.com/Cpp/CppCodingStandard.html
  697. [kernel]:https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/coding-style.rst
  698. [overloading]:http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
  699. [style]:http://en.wikipedia.org/wiki/Programming_style