dev_style.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. *dev_style.txt* Nvim
  2. NVIM REFERENCE MANUAL
  3. Nvim style guide *dev-style*
  4. Style guidelines for developers working Nvim's source code.
  5. License: CC-By 3.0 https://creativecommons.org/licenses/by/3.0/
  6. Type |gO| to see the table of contents.
  7. ==============================================================================
  8. Background
  9. One way in which we keep the code base manageable is by enforcing consistency.
  10. It is very important that any programmer be able to look at another's code and
  11. quickly understand it.
  12. Maintaining a uniform style and following conventions means that we can more
  13. easily use "pattern-matching" to infer what various symbols are and what
  14. invariants are true about them. Creating common, required idioms and patterns
  15. makes code much easier to understand.
  16. In some cases there might be good arguments for changing certain style rules,
  17. but we nonetheless keep things as they are in order to preserve consistency.
  18. ==============================================================================
  19. Header Files *dev-style-header*
  20. Header guard ~
  21. All header files should start with `#pragma once` to prevent multiple inclusion.
  22. In foo/bar.h:
  23. >c
  24. #pragma once
  25. <
  26. Headers system ~
  27. Nvim uses two types of headers. There are "normal" headers and "defs" headers.
  28. Typically, each normal header will have a corresponding defs header, e.g.
  29. `fileio.h` and `fileio_defs.h`. This distinction is done to minimize
  30. recompilation on change. The reason for this is because adding a function or
  31. modifying a function's signature happens more frequently than changing a type
  32. The goal is to achieve the following:
  33. - All headers (defs and normal) must include only defs headers, system
  34. headers, and generated declarations. In other words, headers must not
  35. include normal headers.
  36. - Source (.c) files may include all headers, but should only include normal
  37. headers if they need symbols and not types.
  38. Use the following guideline to determine what to put where:
  39. Symbols:
  40. - regular function declarations
  41. - `extern` variables (including the `EXTERN` macro)
  42. Non-symbols:
  43. - macros, i.e. `#define`
  44. - static inline functions with the `FUNC_ATTR_ALWAYS_INLINE` attribute
  45. - typedefs
  46. - structs
  47. - enums
  48. - All symbols must be moved to normal headers.
  49. - Non-symbols used by multiple headers should be moved to defs headers. This
  50. is to ensure headers only include defs headers. Conversely, non-symbols used
  51. by only a single header should be moved to that header.
  52. - EXCEPTION: if the macro calls a function, then it must be moved to a normal
  53. header.
  54. ==============================================================================
  55. Scoping *dev-style-scope*
  56. Local Variables ~
  57. Place a function's variables in the narrowest scope possible, and initialize
  58. variables in the declaration.
  59. C99 allows you to declare variables anywhere in a function. Declare them in as
  60. local a scope as possible, and as close to the first use as possible. This
  61. makes it easier for the reader to find the declaration and see what type the
  62. variable is and what it was initialized to. In particular, initialization
  63. should be used instead of declaration and assignment, e.g. >c
  64. int i;
  65. i = f(); // ❌: initialization separate from declaration.
  66. int j = g(); // ✅: declaration has initialization.
  67. Initialization ~
  68. Multiple declarations can be defined in one line if they aren't initialized,
  69. but each initialization should be done on a separate line.
  70. >c
  71. int i;
  72. int j; // ✅
  73. int i, j; // ✅: multiple declarations, no initialization.
  74. int i = 0;
  75. int j = 0; // ✅: one initialization per line.
  76. int i = 0, j; // ❌: multiple declarations with initialization.
  77. int i = 0, j = 0; // ❌: multiple declarations with initialization.
  78. ==============================================================================
  79. Nvim-Specific Magic
  80. clint ~
  81. Use `clint.py` to detect style errors.
  82. `src/clint.py` is a Python script that reads a source file and identifies
  83. style errors. It is not perfect, and has both false positives and false
  84. negatives, but it is still a valuable tool. False positives can be ignored by
  85. putting `// NOLINT` at the end of the line.
  86. uncrustify ~
  87. src/uncrustify.cfg is the authority for expected code formatting, for cases
  88. not covered by clint.py. We remove checks in clint.py if they are covered by
  89. uncrustify rules.
  90. ==============================================================================
  91. Other C Features *dev-style-features*
  92. Variable-Length Arrays and alloca() ~
  93. We do not allow variable-length arrays or `alloca()`.
  94. Variable-length arrays can cause hard to detect stack overflows.
  95. Postincrement and Postdecrement ~
  96. Use postfix form (`i++`) in statements. >c
  97. for (int i = 0; i < 3; i++) { }
  98. int j = ++i; // ✅: ++i is used as an expression.
  99. for (int i = 0; i < 3; ++i) { }
  100. ++i; // ❌: ++i is used as a statement.
  101. Use of const ~
  102. Use `const` pointers whenever possible. Avoid `const` on non-pointer parameter definitions.
  103. Where to put the const ~
  104. Some people favor the form `int const *foo` to `const int *foo` . They
  105. argue that this is more readable because it's more consistent: it keeps
  106. the rule that `const` always follows the object it's describing. However,
  107. this consistency argument doesn't apply in codebases with few
  108. deeply-nested pointer expressions since most `const` expressions have only
  109. one `const`, and it applies to the underlying value. In such cases, there's
  110. no consistency to maintain. Putting the `const` first is arguably more
  111. readable, since it follows English in putting the "adjective" (`const`)
  112. before the "noun" (`int`).
  113. That said, while we encourage putting `const` first, we do not require it.
  114. But be consistent with the code around you! >c
  115. void foo(const char *p, int i);
  116. }
  117. int foo(const int a, const bool b) {
  118. }
  119. int foo(int *const p) {
  120. }
  121. Integer Types ~
  122. Of the built-in integer types only use `char`, `int`, `uint8_t`, `int8_t`,
  123. `uint16_t`, `int16_t`, `uint32_t`, `int32_t`, `uint64_t`, `int64_t`,
  124. `uintmax_t`, `intmax_t`, `size_t`, `ssize_t`, `uintptr_t`, `intptr_t`, and
  125. `ptrdiff_t`.
  126. Use `int` for error codes and local, trivial variables only.
  127. Use care when converting integer types. Integer conversions and promotions can
  128. cause non-intuitive behavior. Note that the signedness of `char` is
  129. implementation defined.
  130. Public facing types must have fixed width (`uint8_t`, etc.)
  131. There are no convenient `printf` format placeholders for fixed width types.
  132. Cast to `uintmax_t` or `intmax_t` if you have to format fixed width integers.
  133. Type unsigned signed
  134. `char` `%hhu` `%hhd`
  135. `int` n/a `%d`
  136. `(u)intmax_t` `%ju` `%jd`
  137. `(s)size_t` `%zu` `%zd`
  138. `ptrdiff_t` `%tu` `%td`
  139. Booleans ~
  140. Use `bool` to represent boolean values. >c
  141. int loaded = 1; // ❌: loaded should have type bool.
  142. Conditions ~
  143. Don't use "yoda-conditions". Use at most one assignment per condition. >c
  144. if (1 == x) {
  145. if (x == 1) { //use this order
  146. if ((x = f()) && (y = g())) {
  147. Function declarations ~
  148. Every function must not have a separate declaration.
  149. Function declarations are created by the gen_declarations.lua script. >c
  150. static void f(void);
  151. static void f(void)
  152. {
  153. ...
  154. }
  155. General translation unit layout ~
  156. The definitions of public functions precede the definitions of static
  157. functions. >c
  158. <HEADER>
  159. <PUBLIC FUNCTION DEFINITIONS>
  160. <STATIC FUNCTION DEFINITIONS>
  161. Integration with declarations generator ~
  162. Every C file must contain #include of the generated header file, guarded by
  163. #ifdef INCLUDE_GENERATED_DECLARATIONS.
  164. Include must go after other #includes and typedefs in .c files and after
  165. everything else in header files. It is allowed to omit #include in a .c file
  166. if .c file does not contain any static functions.
  167. Included file name consists of the .c file name without extension, preceded by
  168. the directory name relative to src/nvim. Name of the file containing static
  169. functions declarations ends with `.c.generated.h`, `*.h.generated.h` files
  170. contain only non-static function declarations. >c
  171. // src/nvim/foo.c file
  172. #include <stddef.h>
  173. typedef int FooType;
  174. #ifdef INCLUDE_GENERATED_DECLARATIONS
  175. # include "foo.c.generated.h"
  176. #endif
  177. // src/nvim/foo.h file
  178. #pragma once
  179. #ifdef INCLUDE_GENERATED_DECLARATIONS
  180. # include "foo.h.generated.h"
  181. #endif
  182. 64-bit Portability ~
  183. Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing,
  184. comparisons, and structure alignment.
  185. - Remember that `sizeof(void *)` != `sizeof(int)`. Use `intptr_t` if you want
  186. a pointer-sized integer.
  187. - You may need to be careful with structure alignments, particularly for
  188. structures being stored on disk. Any class/structure with a
  189. `int64_t`/`uint64_t` member will by default end up being 8-byte aligned on a
  190. 64-bit system. If you have such structures being shared on disk between
  191. 32-bit and 64-bit code, you will need to ensure that they are packed the
  192. same on both architectures. Most compilers offer a way to alter structure
  193. alignment. For gcc, you can use `__attribute__((packed))`. MSVC offers
  194. `#pragma pack()` and `__declspec(align())`.
  195. - Use the `LL` or `ULL` suffixes as needed to create 64-bit constants. For
  196. example: >c
  197. int64_t my_value = 0x123456789LL;
  198. uint64_t my_mask = 3ULL << 48;
  199. sizeof ~
  200. Prefer `sizeof(varname)` to `sizeof(type)`.
  201. Use `sizeof(varname)` when you take the size of a particular variable.
  202. `sizeof(varname)` will update appropriately if someone changes the variable
  203. type either now or later. You may use `sizeof(type)` for code unrelated to any
  204. particular variable, such as code that manages an external or internal data
  205. format where a variable of an appropriate C type is not convenient. >c
  206. Struct data;
  207. memset(&data, 0, sizeof(data));
  208. memset(&data, 0, sizeof(Struct));
  209. if (raw_size < sizeof(int)) {
  210. fprintf(stderr, "compressed record not big enough for count: %ju", raw_size);
  211. return false;
  212. }
  213. ==============================================================================
  214. Naming *dev-style-naming*
  215. The most important consistency rules are those that govern naming. The style
  216. of a name immediately informs us what sort of thing the named entity is: a
  217. type, a variable, a function, a constant, a macro, etc., without requiring us
  218. to search for the declaration of that entity. The pattern-matching engine in
  219. our brains relies a great deal on these naming rules.
  220. Naming rules are pretty arbitrary, but we feel that consistency is more
  221. important than individual preferences in this area, so regardless of whether
  222. you find them sensible or not, the rules are the rules.
  223. General Naming Rules ~
  224. Function names, variable names, and filenames should be descriptive; eschew
  225. abbreviation.
  226. Give as descriptive a name as possible, within reason. Do not worry about
  227. saving horizontal space as it is far more important to make your code
  228. immediately understandable by a new reader. Do not use abbreviations that are
  229. ambiguous or unfamiliar to readers outside your project, and do not abbreviate
  230. by deleting letters within a word. >c
  231. int price_count_reader; // No abbreviation.
  232. int num_errors; // "num" is a widespread convention.
  233. int num_dns_connections; // Most people know what "DNS" stands for.
  234. int n; // Meaningless.
  235. int nerr; // Ambiguous abbreviation.
  236. int n_comp_conns; // Ambiguous abbreviation.
  237. int wgc_connections; // Only your group knows what this stands for.
  238. int pc_reader; // Lots of things can be abbreviated "pc".
  239. int cstmr_id; // Deletes internal letters.
  240. File Names ~
  241. Filenames should be all lowercase and can include underscores (`_`).
  242. Use underscores to separate words. Examples of acceptable file names: >
  243. my_useful_file.c
  244. getline_fix.c // ✅: getline refers to the glibc function.
  245. C files should end in `.c` and header files should end in `.h`.
  246. Do not use filenames that already exist in `/usr/include`, such as `db.h`.
  247. In general, make your filenames very specific. For example, use
  248. `http_server_logs.h` rather than `logs.h`.
  249. Type Names ~
  250. Typedef-ed structs and enums start with a capital letter and have a capital
  251. letter for each new word, with no underscores: `MyExcitingStruct`.
  252. Non-Typedef-ed structs and enums are all lowercase with underscores between
  253. words: `struct my_exciting_struct` . >c
  254. struct my_struct {
  255. ...
  256. };
  257. typedef struct my_struct MyAwesomeStruct;
  258. Variable Names ~
  259. Variable names are all lowercase, with underscores between words. For
  260. instance: `my_exciting_local_variable`.
  261. Common Variable names ~
  262. For example: >c
  263. string table_name; // ✅: uses underscore.
  264. string tablename; // ✅: all lowercase.
  265. string tableName; // ❌: mixed case.
  266. <
  267. Struct Variables ~
  268. Data members in structs should be named like regular variables. >c
  269. struct url_table_properties {
  270. string name;
  271. int num_entries;
  272. }
  273. <
  274. Global Variables ~
  275. Don't use global variables unless absolutely necessary. Prefix global
  276. variables with `g_`.
  277. Constant Names ~
  278. Use a `k` followed by mixed case: `kDaysInAWeek`.
  279. All compile-time constants, whether they are declared locally or globally,
  280. follow a slightly different naming convention from other variables. Use a `k`
  281. followed by words with uppercase first letters: >c
  282. const int kDaysInAWeek = 7;
  283. Function Names ~
  284. Function names are all lowercase, with underscores between words. For
  285. instance: `my_exceptional_function()`. All functions in the same header file
  286. should have a common prefix.
  287. In `os_unix.h`: >c
  288. void unix_open(const char *path);
  289. void unix_user_id(void);
  290. If your function crashes upon an error, you should append `or_die` to the
  291. function name. This only applies to functions which could be used by
  292. production code and to errors that are reasonably likely to occur during
  293. normal operation.
  294. Enumerator Names ~
  295. Enumerators should be named like constants: `kEnumName`. >c
  296. enum url_table_errors {
  297. kOK = 0,
  298. kErrorOutOfMemory,
  299. kErrorMalformedInput,
  300. };
  301. Macro Names ~
  302. They're like this: `MY_MACRO_THAT_SCARES_CPP_DEVELOPERS`. >c
  303. #define ROUND(x) ...
  304. #define PI_ROUNDED 5.0
  305. ==============================================================================
  306. Comments *dev-style-comments*
  307. Comments are vital to keeping our code readable. The following rules describe
  308. what you should comment and where. But remember: while comments are very
  309. important, the best code is self-documenting.
  310. When writing your comments, write for your audience: the next contributor who
  311. will need to understand your code. Be generous — the next one may be you!
  312. Nvim uses Doxygen comments.
  313. Comment Style ~
  314. Use the `//`-style syntax only. >c
  315. // This is a comment spanning
  316. // multiple lines
  317. f();
  318. File Comments ~
  319. Start each file with a description of its contents.
  320. Legal Notice ~
  321. We have no such thing. These things are in LICENSE and only there.
  322. File Contents ~
  323. Every file should have a comment at the top describing its contents.
  324. Generally a `.h` file will describe the variables and functions that are
  325. declared in the file with an overview of what they are for and how they
  326. are used. A `.c` file should contain more information about implementation
  327. details or discussions of tricky algorithms. If you feel the
  328. implementation details or a discussion of the algorithms would be useful
  329. for someone reading the `.h`, feel free to put it there instead, but
  330. mention in the `.c` that the documentation is in the `.h` file.
  331. Do not duplicate comments in both the `.h` and the `.c`. Duplicated
  332. comments diverge. >c
  333. /// A brief description of this file.
  334. ///
  335. /// A longer description of this file.
  336. /// Be very generous here.
  337. Struct Comments ~
  338. Every struct definition should have accompanying comments that describes what
  339. it is for and how it should be used. >c
  340. /// Window info stored with a buffer.
  341. ///
  342. /// Two types of info are kept for a buffer which are associated with a
  343. /// specific window:
  344. /// 1. Each window can have a different line number associated with a
  345. /// buffer.
  346. /// 2. The window-local options for a buffer work in a similar way.
  347. /// The window-info is kept in a list at g_wininfo. It is kept in
  348. /// most-recently-used order.
  349. struct win_info {
  350. /// Next entry or NULL for last entry.
  351. WinInfo *wi_next;
  352. /// Previous entry or NULL for first entry.
  353. WinInfo *wi_prev;
  354. /// Pointer to window that did the wi_fpos.
  355. Win *wi_win;
  356. ...
  357. };
  358. If the field comments are short, you can also put them next to the field. But
  359. be consistent within one struct, and follow the necessary doxygen style. >c
  360. struct wininfo_S {
  361. WinInfo *wi_next; ///< Next entry or NULL for last entry.
  362. WinInfo *wi_prev; ///< Previous entry or NULL for first entry.
  363. Win *wi_win; ///< Pointer to window that did the wi_fpos.
  364. ...
  365. };
  366. If you have already described a struct in detail in the comments at the top of
  367. your file feel free to simply state "See comment at top of file for a complete
  368. description", but be sure to have some sort of comment.
  369. Document the synchronization assumptions the struct makes, if any. If an
  370. instance of the struct can be accessed by multiple threads, take extra care to
  371. document the rules and invariants surrounding multithreaded use.
  372. Function Comments ~
  373. Declaration comments describe use of the function; comments at the definition
  374. of a function describe operation.
  375. Function Declarations ~
  376. Every function declaration should have comments immediately preceding it
  377. that describe what the function does and how to use it. These comments
  378. should be descriptive ("Opens the file") rather than imperative ("Open the
  379. file"); the comment describes the function, it does not tell the function
  380. what to do. In general, these comments do not describe how the function
  381. performs its task. Instead, that should be left to comments in the
  382. function definition.
  383. Types of things to mention in comments at the function declaration:
  384. - If the function allocates memory that the caller must free.
  385. - Whether any of the arguments can be a null pointer.
  386. - If there are any performance implications of how a function is used.
  387. - If the function is re-entrant. What are its synchronization assumptions? >c
  388. /// Brief description of the function.
  389. ///
  390. /// Detailed description.
  391. /// May span multiple paragraphs.
  392. ///
  393. /// @param arg1 Description of arg1
  394. /// @param arg2 Description of arg2. May span
  395. /// multiple lines.
  396. ///
  397. /// @return Description of the return value.
  398. Iterator *get_iterator(void *arg1, void *arg2);
  399. <
  400. Function Definitions ~
  401. If there is anything tricky about how a function does its job, the
  402. function definition should have an explanatory comment. For example, in
  403. the definition comment you might describe any coding tricks you use, give
  404. an overview of the steps you go through, or explain why you chose to
  405. implement the function in the way you did rather than using a viable
  406. alternative. For instance, you might mention why it must acquire a lock
  407. for the first half of the function but why it is not needed for the second
  408. half.
  409. Note you should not just repeat the comments given with the function
  410. declaration, in the `.h` file or wherever. It's okay to recapitulate
  411. briefly what the function does, but the focus of the comments should be on
  412. how it does it. >c
  413. // Note that we don't use Doxygen comments here.
  414. Iterator *get_iterator(void *arg1, void *arg2)
  415. {
  416. ...
  417. }
  418. Variable Comments ~
  419. In general the actual name of the variable should be descriptive enough to
  420. give a good idea of what the variable is used for. In certain cases, more
  421. comments are required.
  422. Global Variables ~
  423. All global variables should have a comment describing what they are and
  424. what they are used for. For example: >c
  425. /// The total number of tests cases that we run
  426. /// through in this regression test.
  427. const int kNumTestCases = 6;
  428. Implementation Comments ~
  429. In your implementation you should have comments in tricky, non-obvious,
  430. interesting, or important parts of your code.
  431. Line Comments ~
  432. Also, lines that are non-obvious should get a comment at the end of the
  433. line. These end-of-line comments should be separated from the code by 2
  434. spaces. Example: >c
  435. // If we have enough memory, mmap the data portion too.
  436. mmap_budget = max<int64>(0, mmap_budget - index_->length());
  437. if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) {
  438. return; // Error already logged.
  439. }
  440. <
  441. Note that there are both comments that describe what the code is doing,
  442. and comments that mention that an error has already been logged when the
  443. function returns.
  444. If you have several comments on subsequent lines, it can often be more
  445. readable to line them up: >c
  446. do_something(); // Comment here so the comments line up.
  447. do_something_else_that_is_longer(); // Comment here so there are two spaces between
  448. // the code and the comment.
  449. { // One space before comment when opening a new scope is allowed,
  450. // thus the comment lines up with the following comments and code.
  451. do_something_else(); // Two spaces before line comments normally.
  452. }
  453. <
  454. NULL, true/false, 1, 2, 3... ~
  455. When you pass in a null pointer, boolean, or literal integer values to
  456. functions, you should consider adding a comment about what they are, or
  457. make your code self-documenting by using constants. For example, compare:
  458. >c
  459. bool success = calculate_something(interesting_value,
  460. 10,
  461. false,
  462. NULL); // What are these arguments??
  463. <
  464. versus: >c
  465. bool success = calculate_something(interesting_value,
  466. 10, // Default base value.
  467. false, // Not the first time we're calling this.
  468. NULL); // No callback.
  469. <
  470. Or alternatively, constants or self-describing variables: >c
  471. const int kDefaultBaseValue = 10;
  472. const bool kFirstTimeCalling = false;
  473. Callback *null_callback = NULL;
  474. bool success = calculate_something(interesting_value,
  475. kDefaultBaseValue,
  476. kFirstTimeCalling,
  477. null_callback);
  478. <
  479. Don'ts ~
  480. Note that you should never describe the code itself. Assume that the
  481. person reading the code knows C better than you do, even though he or she
  482. does not know what you are trying to do: >c
  483. // Now go through the b array and make sure that if i occurs,
  484. // the next element is i+1.
  485. ... // Geez. What a useless comment.
  486. Punctuation, Spelling and Grammar ~
  487. Pay attention to punctuation, spelling, and grammar; it is easier to read
  488. well-written comments than badly written ones.
  489. Comments should be as readable as narrative text, with proper capitalization
  490. and punctuation. In many cases, complete sentences are more readable than
  491. sentence fragments. Shorter comments, such as comments at the end of a line of
  492. code, can sometimes be less formal, but you should be consistent with your
  493. style.
  494. Although it can be frustrating to have a code reviewer point out that you are
  495. using a comma when you should be using a semicolon, it is very important that
  496. source code maintain a high level of clarity and readability. Proper
  497. punctuation, spelling, and grammar help with that goal.
  498. TODO Comments ~
  499. Use `TODO` comments for code that is temporary, a short-term solution, or
  500. good-enough but not perfect.
  501. `TODO`s should include the string `TODO` in all caps, followed by the name,
  502. email address, or other identifier of the person who can best provide context
  503. about the problem referenced by the `TODO`. The main purpose is to have a
  504. consistent `TODO` format that can be searched to find the person who can
  505. provide more details upon request. A `TODO` is not a commitment that the
  506. person referenced will fix the problem. Thus when you create a `TODO`, it is
  507. almost always your name that is given. >c
  508. // TODO(kl@gmail.com): Use a "*" here for concatenation operator.
  509. // TODO(Zeke): change this to use relations.
  510. If your `TODO` is of the form "At a future date do something" make sure that
  511. you either include a very specific date ("Fix by November 2005") or a very
  512. specific event ("Remove this code when all clients can handle XML
  513. responses.").
  514. Deprecation Comments ~
  515. Mark deprecated interface points with `@deprecated` docstring token.
  516. You can mark an interface as deprecated by writing a comment containing the
  517. word `@deprecated` in all caps. The comment goes either before the declaration
  518. of the interface or on the same line as the declaration.
  519. After `@deprecated`, write your name, email, or other identifier in
  520. parentheses.
  521. A deprecation comment must include simple, clear directions for people to fix
  522. their callsites. In C, you can implement a deprecated function as an inline
  523. function that calls the new interface point.
  524. Marking an interface point `DEPRECATED` will not magically cause any callsites
  525. to change. If you want people to actually stop using the deprecated facility,
  526. you will have to fix the callsites yourself or recruit a crew to help you.
  527. New code should not contain calls to deprecated interface points. Use the new
  528. interface point instead. If you cannot understand the directions, find the
  529. person who created the deprecation and ask them for help using the new
  530. interface point.
  531. ==============================================================================
  532. Formatting *dev-style-format*
  533. Coding style and formatting are pretty arbitrary, but a project is much easier
  534. to follow if everyone uses the same style. Individuals may not agree with
  535. every aspect of the formatting rules, and some of the rules may take some
  536. getting used to, but it is important that all project contributors follow the
  537. style rules so that they can all read and understand everyone's code easily.
  538. Non-ASCII Characters ~
  539. Non-ASCII characters should be rare, and must use UTF-8 formatting.
  540. You shouldn't hard-code user-facing text in source (OR SHOULD YOU?), even
  541. English, so use of non-ASCII characters should be rare. However, in certain
  542. cases it is appropriate to include such words in your code. For example, if
  543. your code parses data files from foreign sources, it may be appropriate to
  544. hard-code the non-ASCII string(s) used in those data files as delimiters. More
  545. commonly, unittest code (which does not need to be localized) might contain
  546. non-ASCII strings. In such cases, you should use UTF-8, since that is an
  547. encoding understood by most tools able to handle more than just ASCII.
  548. Hex encoding is also OK, and encouraged where it enhances readability — for
  549. example, `"\uFEFF"`, is the Unicode zero-width no-break space character, which
  550. would be invisible if included in the source as straight UTF-8.
  551. Braced Initializer Lists ~
  552. Format a braced list exactly like you would format a function call in its
  553. place but with one space after the `{` and one space before the `}`
  554. If the braced list follows a name (e.g. a type or variable name), format as if
  555. the `{}` were the parentheses of a function call with that name. If there is
  556. no name, assume a zero-length name. >c
  557. struct my_struct m = { // Here, you could also break before {.
  558. superlongvariablename1,
  559. superlongvariablename2,
  560. { short, interior, list },
  561. { interiorwrappinglist,
  562. interiorwrappinglist2 } };
  563. Loops and Switch Statements ~
  564. Annotate non-trivial fall-through between cases.
  565. If not conditional on an enumerated value, switch statements should always
  566. have a `default` case (in the case of an enumerated value, the compiler will
  567. warn you if any values are not handled). If the default case should never
  568. execute, simply use `abort()`: >c
  569. switch (var) {
  570. case 0:
  571. ...
  572. break;
  573. case 1:
  574. ...
  575. break;
  576. default:
  577. abort();
  578. }
  579. Switch statements that are conditional on an enumerated value should not have
  580. a `default` case if it is exhaustive. Explicit case labels are preferred over
  581. `default`, even if it leads to multiple case labels for the same code. For
  582. example, instead of: >c
  583. case A:
  584. ...
  585. case B:
  586. ...
  587. case C:
  588. ...
  589. default:
  590. ...
  591. You should use: >c
  592. case A:
  593. ...
  594. case B:
  595. ...
  596. case C:
  597. ...
  598. case D:
  599. case E:
  600. case F:
  601. ...
  602. Certain compilers do not recognize an exhaustive enum switch statement as
  603. exhaustive, which causes compiler warnings when there is a return statement in
  604. every case of a switch statement, but no catch-all return statement. To fix
  605. these spurious errors, you are advised to use `UNREACHABLE` after the switch
  606. statement to explicitly tell the compiler that the switch statement always
  607. returns and any code after it is unreachable. For example: >c
  608. enum { A, B, C } var;
  609. ...
  610. switch (var) {
  611. case A:
  612. return 1;
  613. case B:
  614. return 2;
  615. case C:
  616. return 3;
  617. }
  618. UNREACHABLE;
  619. Return Values ~
  620. Do not needlessly surround the `return` expression with parentheses.
  621. Use parentheses in `return expr`; only where you would use them in `x =
  622. expr;`. >c
  623. return result;
  624. return (some_long_condition && another_condition);
  625. return (value); // You wouldn't write var = (value);
  626. return(result); // return is not a function!
  627. Horizontal Whitespace ~
  628. Use of horizontal whitespace depends on location.
  629. Variables ~
  630. >c
  631. int long_variable = 0; // Don't align assignments.
  632. int i = 1;
  633. struct my_struct { // Exception: struct arrays.
  634. const char *boy;
  635. const char *girl;
  636. int pos;
  637. } my_variable[] = {
  638. { "Mia", "Michael", 8 },
  639. { "Elizabeth", "Aiden", 10 },
  640. { "Emma", "Mason", 2 },
  641. };
  642. <
  643. ==============================================================================
  644. Parting Words
  645. The style guide is intended to make the code more readable. If you think you
  646. must violate its rules for the sake of clarity, do it! But please add a note
  647. to your pull request explaining your reasoning.
  648. vim:tw=78:ts=8:et:ft=help:norl: