Code Style Guidelines

Indentation

Use spaces, not tabs. Tabs should only appear in files that require them for semantic meaning, like Makefiles.

The indent size is 4 spaces.

Right:
intmain() { return0; } 
Wrong:
intmain() { return0; } 

The contents of namespaces should not be indented.

Right:
// Document.h namespaceWebCore { classDocument { Document(); ... }; namespaceNestedNamespace { classOtherDocument { OtherDocument(); ... }; } } // namespace WebCore // Document.cpp namespaceWebCore { Document::Document() { ... } namespaceNestedNamespace { OtherDocument::OtherDocument() { ... } } // namespace NestedNamespace  } // namespace WebCore 
Right:
// PrivateClickMeasurementDatabase.h namespaceWebKit::PCM { classDatabase { ... }; } // namespace WebKit::PCM 
Wrong:
// Document.h namespaceWebCore { classDocument { Document(); ... }; namespaceNestedNamespace { ... } } // namespace WebCore // Document.cpp namespaceWebCore { Document::Document() { ... } } // namespace WebCore 

A case label should line up with its switch statement. The case statement is indented.

Right:
switch (condition) { casefooCondition: casebarCondition: i++; break; default: i--; } 
Wrong:
switch (condition) { casefooCondition: casebarCondition: i++; break; default: i--; } 

Boolean expressions at the same nesting level that span multiple lines should have their operators on the left side of the line instead of the right side.

Right:
returnattribute.name() == srcAttr || attribute.name() == lowsrcAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#'); 
Wrong:
returnattribute.name() == srcAttr || attribute.name() == lowsrcAttr || (attribute.name() == usemapAttr && attr->value().string()[0] != '#'); 

Spacing

Do not place spaces around unary operators.

Right:
i++; 
Wrong:
i ++; 

Do place spaces around binary and ternary operators.

Right:
y = m * x + b; f(a, b); c = a | b; returncondition ? 1 : 0; 
Wrong:
y=m*x+b; f(a,b); c = a|b; returncondition ? 1:0; 

Place spaces around the colon in a range-based for loop.

Right:
Vector<PluginModuleInfo> plugins; for (auto& plugin : plugins) registerPlugin(plugin); 
Wrong:
Vector<PluginModuleInfo> plugins; for (auto& plugin: plugins) registerPlugin(plugin); 

Do not place spaces before comma and semicolon.

Right:
for (inti = 0; i < 10; ++i) doSomething(); f(a, b); 
Wrong:
for (inti = 0 ; i < 10 ; ++i) doSomething(); f(a , b) ; 

Place spaces between control statements and their parentheses.

Right:
if (condition) doIt(); 
Wrong:
if(condition) doIt(); 

Do not place spaces between the name, angle brackets and parentheses of a function declaration or invocation.

Right:
f(); voidg() { ... } h<int>(); 
Wrong:
f (); voidg () { ... } h <int> (); 

Do not place spaces between the parenthesis and its parameters, or angle brackets and its parameters of a function declaration or invocation.

Right:
f(a, b); voidg(inta) { ... } h<int>(); 
Wrong:
f( a, b ); voidg( inta ) { ... } h< int >(); 

Do not place spaces between square brackets, angle brackets and parentheses of a lambda function but do place a space before braces.

Right:
[](intx) { returnx; } [this] { returnm_member; } [=]<typenameT> { returnT(); } [&]<typenameX>(Xparameter) { returnparameter; } 
Wrong:
[] (intx) { returnx; } [this]{ returnm_member; } [=] <typenameT> { returnT(); } [&]<typenameX> (Xparameter) { returnparameter; } 

Do not place spaces between the identifier template and its angle brackets.

Right:
template<typenameT> Tfoo(); template<typenameU> structBar { }; 
Wrong:
template <typenameT> Tfoo(); template <typenameU> structBar { }; 

When initializing an object, place a space before the leading brace as well as between the braces and their content.

Right:
Foofoo { bar }; 
Wrong:
Foofoo{ bar }; Foofoo {bar}; 

In Objective-C, do not place spaces between the start of a block and its arguments, or the start of a block and its opening brace. Do place a space between argument lists and the opening brace of the block.

Right:
block = ^{ ... }; block = ^(int, int) { ... }; 
Wrong:
block = ^ { ... }; block = ^ (int, int){ ... }; 

In Objective-C, do not place a space between the type name and the protocol name.

Right:
id<MTLDevice> device = ...; 
Wrong:
id <MTLDevice> device = ...; 

Line breaking

Each statement should get its own line.

Right:
x++; y++; if (condition) doIt(); 
Wrong:
x++; y++; if (condition) doIt(); 

Chained = assignments should be broken up into multiple statements.

Right:
rightSpacing = totalSpacing / 2; leftSpacing = rightSpacing; 
Wrong:
leftSpacing = rightSpacing = totalSpacing / 2; 

An else statement should go on the same line as a preceding close brace if one is present, else it should line up with the if statement.

Right:
if (condition) { ... } else { ... } if (condition) doSomething(); elsedoSomethingElse(); if (condition) doSomething(); else { ... } 
Wrong:
if (condition) { ... } else { ... } if (condition) doSomething(); elsedoSomethingElse(); if (condition) doSomething(); else { ... } 

An else if statement should be written as an if statement when the prior if concludes with a return statement.

Right:
if (condition) { ... returnsomeValue; } if (condition) { ... } 
Wrong:
if (condition) { ... returnsomeValue; } elseif (condition) { ... } 

Braces

Function definitions: place each brace on its own line.

Right:
intmain() { ... } 
Wrong:
intmain() { ... } 

Other braces: place the open brace on the line preceding the code block; place the close brace on its own line.

Right:
classMyClass { ... }; namespaceWebCore { ... } for (inti = 0; i < 10; ++i) { ... } 
Wrong:
classMyClass { ... }; 

One-line control clauses should not use braces unless comments are included or a single statement spans multiple lines.

Right:
if (condition) doIt(); if (condition) { // Some comment doIt(); } if (condition) { myFunction(reallyLongParam1, reallyLongParam2, ... reallyLongParam5); } 
Wrong:
if (condition) { doIt(); } if (condition) // Some comment doIt(); if (condition) myFunction(reallyLongParam1, reallyLongParam2, ... reallyLongParam5); 

Control clauses without a body should use empty braces:

Right:
for ( ; current; current = current->next) { } 
Wrong:
for ( ; current; current = current->next); 

Any empty braces should contain a space.

Right:
voidf() { } structUnit { }; unionUnit { }; classUnit { }; enumUnit { }; intx { }; autoa = [] { }; while (true) { } 
Wrong:
voidf() {} structUnit {}; unionUnit {}; classUnit {}; enumUnit {}; intx {}; autoa = [] {}; while (true) {} 

Null, false and zero

In C++, the null pointer value should be written as nullptr. In C, it should be written as NULL. In Objective-C and Objective-C++, follow the guideline for C or C++, respectively, but use nil to represent a null Objective-C object.

C++ and C bool values should be written as true and false. Objective-C BOOL values should be written as YES and NO.

Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.

Right:
if (condition) doIt(); if (!ptr) return; if (!count) return; 
Wrong:
if (condition == true) doIt(); if (ptr == NULL) return; if (count == 0) return; 

In Objective-C, instance variables are initialized to zero automatically. Don’t add explicit initializations to nil or NO in an init method.

Floating point literals

Unless required in order to force floating point math, do not append .0, .f and .0f to floating point literals.

Right:
constdoubleduration = 60; voidsetDiameter(floatdiameter) { radius = diameter / 2; } setDiameter(10); constintframesPerSecond = 12; doubleframeDuration = 1.0 / framesPerSecond; 
Wrong:
constdoubleduration = 60.0; voidsetDiameter(floatdiameter) { radius = diameter / 2.f; } setDiameter(10.f); constintframesPerSecond = 12; doubleframeDuration = 1 / framesPerSecond; // integer division 

Names

Use CamelCase. Capitalize the first letter, including all letters in an acronym, in a class, struct, protocol, or namespace name. Lower-case the first letter, including all letters in an acronym, in a variable or function name.

Right:
structData; size_tbufferSize; classHTMLDocument; StringmimeType(); 
Wrong:
structdata; size_tbuffer_size; classHtmlDocument; StringMIMEType(); 

Use full words, except in the rare case where an abbreviation would be more canonical and easier to understand.

Right:
size_tcharacterSize; size_tlength; shorttabIndex; // more canonical 
Wrong:
size_tcharSize; size_tlen; shorttabulationIndex; // bizarre 

Data members in C++ classes should be private. Static data members should be prefixed by “s_”. Other data members should be prefixed by “m_”.

Right:
classString { public: ... private: shortm_length; }; 
Wrong:
classString { public: ... shortlength; }; 

Prefix Objective-C instance variables with “_”.

Right:
@classString ... short_length; @end
Wrong:
@classString ... shortlength; @end

Precede boolean values with words like “is” and “did”.

Right:
boolisValid; booldidSendData; 
Wrong:
boolvalid; boolsentData; 

Precede setters with the word “set”. Use bare words for getters. Setter and getter names should match the names of the variables being set/gotten.

Right:
voidsetCount(size_t); // sets m_count size_tcount(); // returns m_count 
Wrong:
voidsetCount(size_t); // sets m_theCount size_tgetCount(); 

Precede getters that return values through out arguments with the word “get”.

Right:
voidgetInlineBoxAndOffset(InlineBox*&, int& caretOffset) const; 
Wrong:
voidinlineBoxAndOffset(InlineBox*&, int& caretOffset) const; 

Use descriptive verbs in function names.

Right:
boolconvertToASCII(short*, size_t); 
Wrong:
booltoASCII(short*, size_t); 

The getter function for a member variable should not have any suffix or prefix indicating the function can optionally create or initialize the member variable. Suffix the getter function which does not automatically create the object with IfExists if there is a variant which does.

Right:
StyleResolver* styleResolverIfExists(); StyleResolver& styleResolver(); 
Wrong:
StyleResolver* styleResolver(); StyleResolver& ensureStyleResolver(); 
Right:
Frame* frame(); 
Wrong:
Frame* frameIfExists(); 

Leave meaningless variable names out of function declarations. A good rule of thumb is if the parameter type name contains the parameter name (without trailing numbers or pluralization), then the parameter name isn’t needed. Usually, there should be a parameter name for bools, strings, and numerical types.

Right:
voidsetCount(size_t); voiddoSomething(ScriptExecutionContext*); 
Wrong:
voidsetCount(size_tcount); voiddoSomething(ScriptExecutionContext* context); 

Prefer enums to bools on function parameters if callers are likely to be passing constants, since named constants are easier to read at the call site. An exception to this rule is a setter function, where the name of the function already makes clear what the boolean is.

Right:
doSomething(something, AllowFooBar); paintTextWithShadows(context, ..., textStrokeWidth > 0, isHorizontal()); setResizable(false); 
Wrong:
doSomething(something, false); setResizable(NotResizable); 

Objective-C method names should follow the Cocoa naming guidelines — they should read like a phrase and each piece of the selector should start with a lowercase letter and use intercaps.

Enum members should use InterCaps with an initial capital letter.

Prefer const to #define. Prefer inline functions to macros.

#defined constants should use all uppercase names with words separated by underscores.

Macros that expand to function calls or other non-constant computation: these should be named like functions, and should have parentheses at the end, even if they take no arguments (with the exception of some special macros like ASSERT). Note that usually it is preferable to use an inline function in such cases instead of a macro.

Right:
#define WBStopButtonTitle() NSLocalizedString(@"Stop", @"Stop button title") 
Wrong:
#define WB_STOP_BUTTON_TITLENSLocalizedString(@"Stop", @"Stop button title") #define WBStopButtontitleNSLocalizedString(@"Stop", @"Stop button title") 

Use #pragma once instead of #define and #ifdef for header guards.

Right:
// HTMLDocument.h #pragma once
Wrong:
// HTMLDocument.h #ifndef HTMLDocument_h#define HTMLDocument_h

Ref and RefPtr objects meant to protect this from deletion should be named “protectedThis”.

Right:
RefPtr<Node> protectedThis(this); Ref<Element> protectedThis(*this); RefPtr<Widget> protectedThis = this; 
Wrong:
RefPtr<Node> protector(this); Ref<Node> protector = *this; RefPtr<Widget> self(this); Ref<Element> elementRef(*this); 

Ref and RefPtr objects meant to protect variables other than this from deletion should be named either “protector”, or “protected” combined with the capitalized form of the variable name.

Right:
RefPtr<Element> protector(&element); RefPtr<Element> protector = &element; RefPtr<Node> protectedNode(node); RefPtr<Widget> protectedMainWidget(m_mainWidget); RefPtr<Loader> protectedFontLoader = m_fontLoader; 
Wrong:
RefPtr<Node> nodeRef(&rootNode); Ref<Element> protect(*element); RefPtr<Node> protectorNode(node); RefPtr<Widget> protected = widget; 

Other Punctuation

Constructors for C++ classes should initialize all of their members using C++ initializer syntax. Each member (and superclass) should be indented on a separate line, with the colon or comma preceding the member on that line.

Right:
MyClass::MyClass(Document* document) : MySuperClass() , m_myMember(0) , m_document(document) { } MyOtherClass::MyOtherClass() : MySuperClass() { } 
Wrong:
MyClass::MyClass(Document* document) : MySuperClass() { m_myMember = 0; m_document = document; } MyOtherClass::MyOtherClass() : MySuperClass() {} 

Prefer index over iterator in Vector iterations for terse, easier-to-read code.

Right:
for (auto& frameView : frameViews) frameView->updateLayoutAndStyleIfNeededRecursive(); 

OK:

unsignedframeViewsCount = frameViews.size(); for (unsignedi = 0; i < frameViewsCount; ++i) frameViews[i]->updateLayoutAndStyleIfNeededRecursive(); 
Wrong:
constVector<RefPtr<FrameView> >::iteratorend = frameViews.end(); for (Vector<RefPtr<FrameView> >::iteratorit = frameViews.begin(); it != end; ++it) (*it)->updateLayoutAndStyleIfNeededRecursive(); 

Omit parentheses for a C++ lambda whenever possible.

Right:
[this] { returnm_member; } [this]() mutable { returndoWork(WTFMove(m_object)); } 
Wrong:
[this]() { returnm_member; } []() { returnstatic_cast<unsigned>(-1); } 

Only use the arrow for function return types if it allows you to omit redundant information.

Right:
intfoo() { ... } 
Wrong:
autofoo() -> int { ... } 
Right:
autoFoo::bar() -> Baz { ... } 
Wrong:
Foo::BazFoo::bar() { ... } 

Pointers and References

Pointer types in non-C++ code
Pointer types should be written with a space between the type and the * (so the * is adjacent to the following identifier if any).

Pointer and reference types in C++ code
Both pointer types and reference types should be written with no space between the type name and the * or &.

Right:
Image* SVGStyledElement::doSomething(PaintInfo& paintInfo) { SVGStyledElement* element = static_cast<SVGStyledElement*>(node()); constKCDashArray& dashes = dashArray(); 
Wrong:
Image *SVGStyledElement::doSomething(PaintInfo &paintInfo) { SVGStyledElement *element = static_cast<SVGStyledElement *>(node()); constKCDashArray &dashes = dashArray(); 

An out argument of a function should be passed by reference except rare cases where it is optional in which case it should be passed by pointer.

Right:
voidMyClass::getSomeValue(OutArgumentType& outArgument) const { outArgument = m_value; } voidMyClass::doSomething(OutArgumentType* outArgument) const { doSomething(); if (outArgument) *outArgument = m_value; } 
Wrong:
voidMyClass::getSomeValue(OutArgumentType* outArgument) const { *outArgument = m_value; } 

#include Statements

All implementation files must #includeconfig.h first. Header files should never include config.h.

Right:
// RenderLayer.h #include "Node.h"#include "RenderObject.h"#include "RenderView.h"
Wrong:
// RenderLayer.h #include "config.h"#include "RenderObject.h"#include "RenderView.h"#include "Node.h"

All implementation files must #include the primary header second, just after config.h. So for example, Node.cpp should include Node.h first, before other files. This guarantees that each header’s completeness is tested. This also assures that each header can be compiled without requiring any other header files be included first.

Other #include statements should be in sorted order (case sensitive, as done by the command-line sort tool or the Xcode sort selection command). Don’t bother to organize them in a logical order.

Right:
// HTMLDivElement.cpp #include "config.h"#include "HTMLDivElement.h"#include "Attribute.h"#include "HTMLElement.h"#include "QualifiedName.h"
Wrong:
// HTMLDivElement.cpp #include "HTMLElement.h"#include "HTMLDivElement.h"#include "QualifiedName.h"#include "Attribute.h"

Includes of system headers must come after includes of other headers.

Right:
// ConnectionQt.cpp #include "ArgumentEncoder.h"#include "ProcessLauncher.h"#include "WebPageProxyMessageKinds.h"#include "WorkItem.h"#include <QApplication>#include <QLocalServer>#include <QLocalSocket>
Wrong:
// ConnectionQt.cpp #include "ArgumentEncoder.h"#include "ProcessLauncher.h"#include <QApplication>#include <QLocalServer>#include <QLocalSocket>#include "WebPageProxyMessageKinds.h"#include "WorkItem.h"

“using” Statements

In header files, do not use “using” statements in namespace (or global) scope.

Right:
// wtf/Vector.h namespaceWTF { classVectorBuffer { usingstd::min; ... }; } // namespace WTF 
Wrong:
// wtf/Vector.h namespaceWTF { usingstd::min; classVectorBuffer { ... }; } // namespace WTF 

In header files in the WTF sub-library, however, it is acceptable to use “using” declarations at the end of the file to import one or more names in the WTF namespace into the global scope.

Right:
// wtf/Vector.h namespaceWTF { } // namespace WTF usingWTF::Vector; 
Wrong:
// wtf/Vector.h namespaceWTF { } // namespace WTF usingnamespaceWTF; 
Wrong:
// runtime/JSObject.h namespaceWTF { } // namespace WTF usingWTF::PlacementNewAdopt; 

In C++ implementation files, do not use “using” declarations of any kind to import names in the standard template library. Directly qualify the names at the point they’re used instead.

Right:
// HTMLBaseElement.cpp namespaceWebCore { std::swap(a, b); c = std::numeric_limits<int>::max() } // namespace WebCore 
Wrong:
// HTMLBaseElement.cpp usingstd::swap; namespaceWebCore { swap(a, b); } // namespace WebCore 
Wrong:
// HTMLBaseElement.cpp usingnamespacestd; namespaceWebCore { swap(a, b); } // namespace WebCore 

In implementation files, if a “using namespace” statement is for a nested namespace whose parent namespace is defined in the file, put the statement inside that namespace definition.

Right:
// HTMLBaseElement.cpp namespaceWebCore { usingnamespaceHTMLNames; } // namespace WebCore 
Wrong:
// HTMLBaseElement.cpp usingnamespaceWebCore::HTMLNames; namespaceWebCore { } // namespace WebCore 

In implementation files, put all “using namespace” statements inside namespace definitions.

Right:
// HTMLSelectElement.cpp namespaceWebCore { usingnamespaceother; } // namespace WebCore 
Wrong:
// HTMLSelectElement.cpp usingnamespaceother; namespaceWebCore { } // namespace WebCore 

Lambdas

Prefer lambdas with explicit template argument lists when the explicit type of a parameter is required in the body.

Right:
[]<typenameT>(Targ) { ifconstexpr (T::isGood) go(); } 
Wrong:
[](autoarg) { usingT = std::decay_t<decltype(arg)>; ifconstexpr (T::isGood) go(); } 

Types

Omit “int” when using “unsigned” modifier. Do not use “signed” modifier. Use “int” by itself instead.

Right:
unsigneda; intb; 
Wrong:
unsignedinta; // Doesn't omit "int". signedb; // Uses "signed" instead of "int". signedintc; // Doesn't omit "signed". 

Classes

Use a constructor to do an implicit conversion when the argument is reasonably thought of as a type conversion and the type conversion is fast. Otherwise, use the explicit keyword or a function returning the type. This only applies to single argument constructors.

Right:
classLargeInt { public: LargeInt(int); ... classVector { public: explicitVector(intsize); // Not a type conversion. Vectorcreate(Array); // Costly conversion. ... 
Wrong:
classTask { public: Task(ScriptExecutionContext&); // Not a type conversion. explicitTask(); // No arguments. explicitTask(ScriptExecutionContext&, Other); // More than one argument. ... 

Singleton pattern

Use a static member function named “singleton()” to access the instance of the singleton.

Right:
classMySingleton { public: staticMySingleton& singleton(); ... 
Wrong:
classMySingleton { public: staticMySingleton& shared(); ... 
Wrong:
classMySingleton { ... }; MySingleton& mySingleton(); // free function. 

Comments

Use only one space before end of line comments and in between sentences in comments.

Right:
f(a, b); // This explains why the function call was done. This is another sentence. 
Wrong:
inti; // This is a comment with several spaces before it, which is a non-conforming style. doublef; // This is another comment. There are two spaces before this sentence which is a non-conforming style. 

Make comments look like sentences by starting with a capital letter and ending with a period (punctation). One exception may be end of line comments like this if (x == y) // false for NaN.

Use FIXME: (without attribution) to denote items that need to be addressed in the future.

Right:
drawJpg(); // FIXME: Make this code handle jpg in addition to the png support. 
Wrong:
drawJpg(); // FIXME(joe): Make this code handle jpg in addition to the png support. 
drawJpg(); // TODO: Make this code handle jpg in addition to the png support. 

If needed for clarity, add a comment containing the source class name for a block of virtual function override declarations.

Right:
classGPUProcessConnection : publicRefCounted<GPUProcessConnection>, publicIPC::Connection::Client { public: /// ... // IPC::Connection::Client voiddidClose(IPC::Connection&) override; voiddidReceiveMessage(IPC::Connection&, IPC::Decoder&) final; booldidReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, UniqueRef<IPC::Encoder>&) final; voiddidReceiveInvalidMessage(IPC::Connection&, IPC::MessageName) override; // ... }; 

If needed for clarity, add // Messages before a block of IPC message function declarations.

Right:
classGPUProcessConnection : publicRefCounted<GPUProcessConnection>, publicIPC::Connection::Client { public: /// ... // Messages voiddidReceiveRemoteCommand(WebCore::PlatformMediaSession::RemoteControlCommandType, constWebCore::PlatformMediaSession::RemoteCommandArgument&); voiddidInitialize(std::optional<GPUProcessConnectionInfo>&&); // ... }; 

Overriding Virtual Methods

The base level declaration of a virtual method inside a class must be declared with the virtual keyword. All subclasses of that class must either specify the override keyword when overriding the virtual method or the final keyword when overriding the virtual method and requiring that no further subclasses can override it. You never want to annotate a method with more than one of the virtual, override, or final keywords.

Right:
classPerson { public: virtualStringdescription() { ... }; } classStudent : publicPerson { public: Stringdescription() override { ... }; // This is correct because it only contains the "override" keyword to indicate that the method is overridden. } 
classPerson { public: virtualStringdescription() { ... }; } classStudent : publicPerson { public: Stringdescription() final { ... }; // This is correct because it only contains the "final" keyword to indicate that the method is overridden and that no subclasses of "Student" can override "description". } 
Wrong:
classPerson { public: virtualStringdescription() { ... }; } classStudent : publicPerson { public: virtualStringdescription() override { ... }; // This is incorrect because it uses both the "virtual" and "override" keywords to indicate that the method is overridden. Instead, it should only use the "override" keyword. } 
classPerson { public: virtualStringdescription() { ... }; } classStudent : publicPerson { public: virtualStringdescription() final { ... }; // This is incorrect because it uses both the "virtual" and "final" keywords to indicate that the method is overridden and final. Instead, it should only use the "final" keyword. } 
classPerson { public: virtualStringdescription() { ... }; } classStudent : publicPerson { public: virtualStringdescription() { ... }; // This is incorrect because it uses the "virtual" keyword to indicate that the method is overridden. } 

Python

For Python use PEP8 style.

close