dev_style.txt 33 KB

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