Allow entries in arbitrary areas
[hiphop-php.git] / hphp / doc / coding-conventions.md
blobf8af97f259c86aa7a8466f2fe49d1112c19ead72
1 HHVM Coding Conventions
2 =======================
4 This document is meant to serve as a guide to writing C++ in the HHVM codebase,
5 covering when and how to use various language features as well as how code
6 should be formatted. Our goal is to ensure a consistently high-quality codebase
7 that is easy to read and contribute to, especially for newcomers.
9 The HHVM codebase contains a wide variety of code from many different authors.
10 It's been through a few different major stages in its life, including stints in
11 multiple different repositories. As a result, large (primarily older) parts of
12 the codebase do not fit this guide. When in doubt about how to write or format
13 something, always prefer the advice here over existing conventions in the
14 code. If you're already touching some older code as part of your work, please
15 do clean it up as you go along. But please do not spend hours applying the
16 formatting guidelines here to code you aren't otherwise modifying. While we'd
17 love for the entire codebase to follow this guide, we'd rather get there
18 gradually than lose lots of git history and developer time to purely cosmetic
19 changes. That said, if cosmetic changes that you're making as part of a larger
20 diff keep growing in scope, it may be worth pulling them out into a separate
21 diff.
23 There's no well-defined cutoff here - just try to minimize effort for your
24 reviewers. A good rule of thumb is that if your cosmetic changes require adding
25 significant new sections to the diff (such as a function rename that touches
26 all callsites), it should probably be pulled out into its own diff.
29 ## Headers ##
31 Every .cpp file in the HHVM repository should have a corresponding .h file with
32 the same name, and which declares its public interfaces. We tend to value API
33 documentation more heavily than inline implementation comments, so *all*
34 declarations in headers (classes, enums, functions, constants, etc.)  should be
35 documented. See Comments and Documentation for more details.
37 Build times are a frequent source of pain in many large C++ projects. Try not
38 to make large header files that mostly serve to include groups of other large
39 header files. This can discourage "include what you use," discussed in the
40 "What to include section".
42 ### Include guards ###
44 To prevent multiple inclusion, all headers should have the following directive
45 after their license header comment:
47 ```cpp
49  * ...see the 'File copyright' section for details on what goes here...
50  */
52 #pragma once
54 // File contents
55 ```
57 ### What to include ###
59 The golden rule for what to include is "include what you use" (IWYU). In brief,
60 this means you should not rely on any headers you include to transitively
61 include other headers which have definitions you require. You should also
62 prefer to forward declare structs and classes when the definition is not needed
63 (so, "don't include what you don't use"), which helps reduce HHVM's nontrivial
64 build time.
66 To make it easier to achieve IWYU, we have the following guidelines for
67 includes:
69 - Always include the corresponding .h for a .cpp first, before even system
70   headers.
71 - Separate includes into groups: C++ standard library headers, external projects
72   (such as Boost and Intel TBB), and finally headers within HHVM. Each group
73   should be separated by a newline, for readability. (Whether to separate HHVM
74   includes by subsystem (e.g., `jit`) is left up to the author.)
75 - Keep headers alphabetized within each group. This makes it easier to ensure
76   that all necessary includes are made, and no extraneous ones are left behind.
77 - Use double quotes for Folly and HHVM headers and angle brackets for all
78   others.
80 As an example, here is what the include section might look like for a file
81 named `bytecode.cpp`:
83 ```cpp
84 #include "hphp/runtime/vm/bytecode.h"
86 #include <cstdio>
87 #include <string>
89 #include <boost/program_options/options_description.hpp>
91 #include "hphp/runtime/vm/class.h"
92 #include "hphp/runtime/vm/func.h"
93 #include "hphp/runtime/vm/hhbc.h"
94 #include "hphp/util/string.h"
95 ```
97 ### Inline functions ###
99 Defining functions inline is encouraged for very short functions.
101 When defining inline member functions on structs or classes which have tight,
102 compact interfaces (e.g., a smart pointer class, or any wrapper class), prefer
103 to define the functions in the class definition, for concision.
105 However, for classes with more complex, malleable APIs where inline helpers
106 proliferate (e.g., Func, Class, IRInstruction, etc.), restrict the class
107 definition to member function prototypes *only*. This makes the API much
108 cleaner. For these classes, define all inline functions in a corresponding
109 `-inl.h` file.
111 ```cpp
112 // At the bottom of func.h.
114 #include "hphp/runtime/vm/func-inl.h"
117 ```cpp
118 // After the copyright in func-inl.h.
120 namespace HPHP {
122 // Definitions go here.
127 For API's large enough to warrant -inl.h files, move *all* definitions into the
128 -inl.h, even one-line accessors. This serves both to keep the API cleaner and
129 to avoid splitting implementations among three files (the header, the inline,
130 and the source).
132 Some files, with or without a corresponding -inl.h file, may need a -defs.h
133 file. This file also contains definitions of inline functions, but it is *not*
134 included by the main header. It is intended to be used when only a few callers
135 need access to the definitions, or when the definitions can't be in the main
136 header because it would create circular dependencies. It should be included
137 directly by the callers that do need access to the definitions it contains.
140 ## Structs and Classes ##
142 Classes are used extensively throughout the HHVM codebase, with a number of
143 coding conventions. See also Naming for conventions around class naming.
145 ### Using struct vs. class ###
147 In C++, `struct` and `class` have nearly identical meanings; the only
148 difference lies in the default accessibility (`struct` defaults to public, and
149 `class`, to private).
151 We do not assign further meaning to these keywords, so we use `struct`
152 everywhere.  Efforts to compile under MSVC also require that we use the same
153 keyword between a struct/class definition and its forward declarations due to
154 MSVC's failure to adhere to the C++ spec, and sticking to `struct` everywhere
155 makes this easier.
157 ### Access control ###
159 Try to avoid the `protected` keyword. It tends to give a false sense of
160 security about encapsulation: since anyone can inherit from your class, anyone
161 can access the `protected` member with a little extra effort.
163 ### Implicit and explicit constructors ###
165 By default, always use `explicit` for single-argument, non-initializer list
166 constructors.
168 ```cpp
169 struct MyStruct {
170   // We don't want to implicitly convert ints to MyStructs
171   explicit MyStruct(int foo);
173   // Two-argument constructor; no need for explicit
174   MyStruct(const std::string& name, int age);
178 ### Public data members vs. getters/setters ###
180 Prefer declaring public member variables to using getters and setters. Getters
181 and setters that don't manage object state in a nontrivial way serve to bloat
182 the API and introduce unnecessary boilerplate.
184 Getters are, of course, encouraged for private members. Avoid prefixing getters
185 with `get`:
187 ```cpp
188 struct Func {
189   const SVInfoVec& staticVars() const;
190   void setStaticVars(const SVInfoVec&);
192   ArFunction arFuncPtr() const;
194   static constexpr ptrdiff_t sharedBaseOff();
198 ### Declaration order ###
200 Adhere to the following order for declarations in a struct or class definition:
202 1. Friend classes.
203 2. Nested classes, enums, typedefs. (If possible, just declare the nested
204    class and define it following the enclosing class definition.)
205 3. Constructors, destructor.
206 4. Member functions, including static functions, documented and grouped
207    coherently.
208 5. Constants and static data members.
209 6. *All* instance data members, regardless of accessibility.
211 Private member functions can be interspersed with public functions, or
212 relegated to a single section before the data members. However, all instance
213 properties *must* occur contiguously at the end of the class definition.
216 ## Other C++ Language Features ##
218 Very few language features are unconditionally banned. However, if you want to
219 use one of the more controversial constructs such as `goto` or `operator,()`,
220 you'd better have a convincing argument as to why it's better than the
221 alternatives. C++ is a very large and complex language and we don't want to
222 artificially limit what developers can do, but that puts a lot of
223 responsibility on your shoulders.
225 Avoiding restrictions on useful language features (e.g., exceptions, templates,
226 C++11 lambdas) is a major motivating factor for maintaining our own style guide
227 rather than adopting an existing one.
229 ### Namespaces ###
231 All HHVM code should be scoped in `namespace HPHP { /* everything */ }`. Large
232 submodules such as `HPHP::jit` and `HPHP::rds` may be contained in their own
233 namespace within `HPHP`. We often use anonymous namespaces instead of the
234 `static` keyword to keep symbols internal to their translation unit. This is
235 mostly left up to the author; just keep in mind that classes and structs,
236 unlike functions and variables, *must* be in an anonymous namespace in order to
237 be properly hidden.
239 Avoid `using namespace` whenever possible, especially in headers. It is
240 acceptable in `.cpp` files in very limited scopes (function-level or deeper) if
241 it will significantly aid in readability of the code that follows. `using
242 namespace std;` at the top of a `.cpp` is explicitly disallowed.
244 ### Enums ###
246 Prefer `enum class` whenever possible. Old-style enums are generally only
247 acceptable if you expect that your type will be frequently used in an integer
248 context, such as array indexing.
251 ## Naming ##
253 HHVM code adheres to the some broad naming conventions.
255 When the convention is left open, in general, prefer the local conventions
256 used in the file you are working on---e.g., in a struct whose data members all
257 have `m_namesLikeThis`, prefer `m_anotherNameLikeThis` to `m_this_style`, even
258 though the latter is found in other parts of the codebase.
260 ### Variables ###
262 Use `lowerCamelCase` or `lower_case_with_underscores` for all local variables,
263 adhering to whichever is the discernable local convention if possible.  Static
264 variables (whether declared in an anonymous namespace or with the `static`
265 keyword) should additionally be prefixed by `s` (e.g., `s_funcVec`).  Globals,
266 likewise, should be prefixed by `g_` (e.g., `g_context`).
268 ### Constants ###
270 All constants should be prefixed with `k` and use `CamelCase`, e.g.,
271 `kInvalidHandle`. Prefer `constexpr` to `const` whenever possible.
273 ### Class data members ###
275 As with variables, use `lowerCamelCase` or `lower_case_with_underscores` for
276 all data members. Additionally, private instance members should be prefixed
277 with `m_` (e.g., `m_cls`, `m_baseCls`, `m_base_cls`), and all static members
278 should be prefixed with `s_` (e.g., `s_instance`).  Prefer to leave public
279 members unprefixed.
281 ### Functions ###
283 We generally prefer `lowerCamelCase` for header-exposed functions, including
284 member functions, although we use `lower_case_with_underscores` as well (e.g.,
285 `hphp_session_init`), more commonly in file-local scopes.  As usual, follow the
286 local naming conventions of the file you are working in.
288 If you are modeling a class after an existing pattern, such as an STL
289 container, prefer to follow the appropriate conventions (e.g.,
290 `my_list::push_back` is preferred over `my_list::pushBack`).
292 ### Classes ###
294 Classes use `UpperCamelCase`, except when modeling existing patterns like STL
295 containers or smart pointers.
297 ### Namespaces ###
299 New namespaces should use `lowercase`---and single-word namespaces are greatly
300 prefered for common usage.  For longer namespaces (e.g., `vasm_detail`), use
301 `lower_case_with_underscores`.
303 ### Other conventions ###
305 Prefer correctly capitalizing acronyms in new code (e.g., prefer `IRTranslator`
306 to `HhbcTranslator`). In this vein, prefer `ID` (e.g., `TransID`) to `Id`
307 (e.g., `FuncId`) in new code.
310 ## Formatting ##
312 While consistent code formatting doesn't directly affect correctness, it makes
313 it easier to read and maintain. For this reason, we've come up with a set of
314 guidelines about how code should be formatted. There's a good chance that some
315 of these will conflict with your own personal preferred style, but we believe
316 that having a consistently easy to read codebase is more important than letting
317 each developer write code that he or she thinks is uncompromisingly beautiful.
319 Anything not specified here is left up to the judgment of the developer.
320 However, this document is not set in stone, so if a particular formatting issue
321 keeps coming up in code review it probably deserves a few lines in here.
323 ### General rules ###
325 - All indentation is to be done using spaces.
326 - Each indentation level is 2 spaces wide.
327 - Lines may be no longer than 80 characters, unless absolutely required for
328   some syntactic reason.
329 - Lines should not have any trailing whitespace. This includes blank lines at
330   non-zero indentation levels; the only character on those lines should be a
331   newline.
333 ### Types and variables ###
335 - When declaring a variable or typedef, the `*` and `&` characters for pointer
336   and reference types should be adjacent to the type, not the name (e.g.,
337   `const Func*& func`).
338 - Limit variable declarations to one per line.
340 ### Function signatures ###
342 The following function signatures are formatted properly:
344 ```cpp
345 // If arguments would fit on 1 line:
346 inline void Func::appendParam(bool ref, const Func::ParamInfo& info) {
349 // If the arguments need to wrap, we have two accepted styles, both of which
350 // are OK even if the wrapping wasn't necessary:
351 SSATmp* HhbcTranslator::ldClsPropAddr(Block* catchBlock,
352                                       SSATmp* ssaCls,
353                                       SSATmp* ssaName,
354                                       bool raise) {
355   doSomeStuff();
358 // This style is helpful if any of the function, argument, or type names
359 // involved are particularly long.
360 SSATmp* HhbcTranslator::ldClsPropAddr(
361   Block* catchBlock,
362   SSATmp* ssaCls,
363   SSATmp* ssaName,
364   bool raise
365 ) {
366   doSomeStuff();
370 Always keep the type on the same line as the function name, unless it would
371 leave insufficient room for arguments. Do likewise with other modifying
372 keywords (`inline`, `static`, any attributes).
374 Wrapped arguments should always be aligned with the argument on the previous
375 line. The opening curly brace should be on the same line as the last argument,
376 with the exception of class constructors (see the Constructor initializer list
377 section). When writing function declarations in headers, include argument names
378 unless they add no value:
380 ```cpp
381 struct Person {
382   // The single string argument here is obviously the name.
383   void setName(const std::string&);
385   // Two string arguments, so it's not obvious what each one is without names.
386   void setFavorites(const std::string& color, const std::string& animal);
390 ### Statements ###
392 Conditional and loop statements should be formatted like so:
394 ```cpp
395 if (vmpc() == nullptr) {
396   fprintf(stderr, "whoops!\n");
397   std::abort();
401 Note that there is a single space after the `if` keyword, no spaces between
402 `condition` and the surrounding parentheses, and a single space between the `)`
403 and the `{`. As with all blocks, the body should be one indentation level
404 deeper than the `if`. If the *entire* statement (condition and body) fits on
405 one line, you may leave it on one line, omitting the curly braces. In all
406 other cases, the braces are required. For example, the following are OK:
408 ```cpp
409 if (obj->_count == 0) deleteObject(obj);
411 for (auto block : blocks) block->setParent(nullptr);
414 But these are not acceptable:
416 ```cpp
417 if (veryLongVariableName.hasVeryLongFieldName() &&
418     (rand() % 5) == 0) launchRocket();
420 if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
421   goto fail;
424 Avoid assignments in conditional expressions, unless the variable is declared
425 within the condition, e.g.,
427 ```cpp
428 if (auto const unit = getMyUnit(from, these, args)) {
429   // Do stuff with unit.
433 Prefer C++11 foreach syntax to explicit iterators:
435 ```cpp
436 for (auto const& thing : thingVec) {
437   // Do stuff with thing.
441 ### Expressions ###
443 - All binary operators should have one space on each side, except for `.`,
444   `->`, `.*`, and `->*` which should have zero.
445 - Do not include redundant parentheses unless you think the expression would be
446   confusing to read otherwise. A good rule of thumb is that if you and/or your
447   reviewers have to look at a chart of operator precedence to decide if the
448   expression parses as expected, you probably need some extra parentheses. GCC
449   or clang may suggest extra parens in certain situations; we compile with
450   `-Werror` so you must always follow those guidelines.
451 - If an expression does not fit on one line, attempt to wrap it after an
452   operator (rather than an identifier or keyword) and indent subsequent lines
453   with the beginning of the current parenthesis/brace nesting level. For
454   example, here are some long expressions, formatted appropriately:
455 ```cpp
456 if (RuntimeOption::EvalJitRegionSelector != "" &&
457     (RuntimeOption::EvalHHIRRefcountOpts ||
458      RuntimeOption::EvalHHITExtraOptPass) &&
459     Func::numLoadedFuncs() < 600) {
460   // ...
463 longFunctionName(argumentTheFirst,
464                  argumentTheSecond,
465                  argumentTheThird,
466                  argumentTheFourth);
469 - Function calls should be formatted primarily using the previous rule. If one
470   or more of the arguments to the function is very wide, it may be necessary to
471   shift all the arguments down one line and align them one level deeper than
472   the current scope. This is always acceptable, but is especially common when
473   passing lambdas:
474 ```cpp
475 m_irb->ifThen(
476   [&](Block* taken) {
477     gen(CheckType, Type::Int, taken, src);
478   },
479   [&] {
480     doSomeStuff();
481     lotsOfNonTrivialCode();
482     // etc...
483   }
487 ### Constructor initializer lists ###
489 If an initializer list can be kept on a single line, it is fine to do so:
491 ```cpp
492 MyClass::MyClass(uint64_t idx) : m_idx(idx) {}
494 MyClass::MyClass(const Func* func) : m_idx(-1) {
495   // Do stuff.
499 Otherwise, it is always correct to format lists thusly:
501 ```cpp
502 MyClass::MyClass(const Class* cls, const Func* func, const Class* ctx)
503   : m_cls(cls)
504   , m_func(func)
505   , m_ctx(ctx)
506   , m_isMyConditionMet(false)
509 MyClass::MyClass(const Class* cls, const Func* func)
510   : m_cls(cls)
511   , m_func(func)
512   , m_ctx(nullptr)
513   , m_isMyConditionMet(false)
515   // Do stuff.
519 ### Namespaces ###
521 We don't nest namespaces very deeply, so prefer to keep the scoping to a single
522 line:
524 ```cpp
525 namespace HPHP { namespace jit { namespace x64 {
526 ///////////////////////////////////////////////////////////////////////////////
529  * Some nice documentation.
530  */
531 struct SomeNiceThing {
532   // some nice properties
535 ///////////////////////////////////////////////////////////////////////////////
539 Do not increase the indentation level when entering namespace scope. Instead,
540 consider adding a line of forward slashes as a separator, to more clearly
541 delineate the namespace (this is especially useful for anonymous namespaces in
542 source files). This form of delineation is encouraged, but we have no strict
543 convention for its formatting (you'll see 70- or 79- or 80-character
544 separators, with or without an extra newline between it and the braces, etc.).
547 ## Comments ##
549 All public and private APIs in headers should be documented in detail. Names
550 and notions which are not obvious (e.g., "persistent" or "simple") should be
551 explained. Preconditions and postconditions should be noted.
553 Inline code comments are encouraged for complex logic, but their density is
554 left up to the author. Rather than summarizing/paraphrasing what your code is
555 doing, focus on explaining what overarching goal the code is achieving and/or
556 why that goal is necessary or desirable.
558 ### Comment style ###
560 Here are some comment styles we use or avoid:
562 ```cpp
563 // This style of comment is the most common for relatively short inline
564 // comments. It's fine if it's multi-line.
566 // It's also fine if it has line breaks. The extra newline aids readability in
567 // this case.
570  * This style of comment is the right one to use for struct/function
571  * documentation. Prefer one star on the opening line, as opposed to the
572  * doxygen standard of two.
574  * This is also sometimes used for inline code comments, although the // style
575  * makes it easier to comment out blocks of code.
576  */
578 struct ClassLikeThing {
579   std::vector<const Func*> methods; // This is fine for short annotations.
581   /* This is also ok, though try not to mix and match too much in a file. */
582   std::vector<const ClassLikeThing*> parents;
585 /* Don't write multiline comments where some lines are missing their prefix.
586    This is pretty weird. */
589 Try to use complete sentences in all but the shortest of comments. All comments
590 should be flowed to 79 characters in width.
592 ### Separators ###
594 Delineate sections of code with a line of forward slashes. There is no strict
595 convention, but prefer lines of slashes to other delineators (e.g., `/*****/`,
596 five newlines, ASCII-art cartoon characters).
598 ### File copyright ###
600 All files must begin with a copyright/license notice. For files created by
601 Facebook employees, the following should be used:
603 ```cpp
605    +----------------------------------------------------------------------+
606    | HipHop for PHP                                                       |
607    +----------------------------------------------------------------------+
608    | Copyright (c) 2010-201x Facebook, Inc. (http://www.facebook.com)     |
609    +----------------------------------------------------------------------+
610    | This source file is subject to version 3.01 of the PHP license,      |
611    | that is bundled with this package in the file LICENSE, and is        |
612    | available through the world-wide-web at the following url:           |
613    | http://www.php.net/license/3_01.txt                                  |
614    | If you did not receive a copy of the PHP license and are unable to   |
615    | obtain it through the world-wide-web, please send a note to          |
616    | license@php.net so we can mail you a copy immediately.               |
617    +----------------------------------------------------------------------+
620 // File contents start here.
623 We do not require copyright assignment for external contributions, so
624 non-Facebook contributors should include their own header. The exact contents
625 are up to you, as long as the license is compatible with the PHP license.