> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/LadybirdBrowser/ladybird/llms.txt
> Use this file to discover all available pages before exploring further.

# Coding style guide

> C++ coding style conventions and formatting rules for Ladybird

For low-level styling (spaces, parentheses, brace placement, etc), all code should follow the format specified in `.clang-format` in the project root.

<Warning>
  **Important: Make sure you use the correct version of `clang-format`!**

  See [lint-clang-format.py](https://github.com/LadybirdBrowser/ladybird/blob/master/Meta/lint-clang-format.py) for the version enforced in CI.

  See [AdvancedBuildInstructions.md](https://github.com/LadybirdBrowser/ladybird/blob/master/Documentation/AdvancedBuildInstructions.md#clang-format-updates) for instructions on how to get an up-to-date version if your OS distribution does not ship the correct version.
</Warning>

This document describes the coding style used for C++ code in the Ladybird Browser project. All new code should conform to this style.

We'll definitely be tweaking and amending this over time, so let's consider it a living document. :)

## Names

A combination of CamelCase, snake\_case, and SCREAMING\_CASE:

* Use CamelCase (Capitalize the first letter, including all letters in an acronym) in a class, struct, or namespace name
* Use snake\_case (all lowercase, with underscores separating words) for variable and function names
* Use SCREAMING\_CASE for constants (both global and static member variables)

### Right

```cpp theme={null}
struct Entry;
size_t buffer_size;
class FileDescriptor;
String absolute_path();
```

### Wrong

```cpp theme={null}
struct data;
size_t bufferSize;
class Filedescriptor;
String MIME_Type();
```

### Matching spec naming

When implementing spec algorithms and other constructs that a spec explicitly names, prefer closely matching the same names the spec uses, whenever possible.

Given the construct at [https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-being-missing](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#suffering-from-being-missing) which has the literal name *"Suffering from being missing"* in the spec, for example:

```cpp theme={null}
bool HTMLInputElement::suffering_from_being_missing(); // exactly matches the spec naming
```

### Full words vs abbreviations

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

```cpp theme={null}
size_t character_size;
size_t length;
short tab_index; // More canonical.
```

### Data members

Data members in C++ classes should be private. Static data members should be prefixed by "s\_". Other data members should be prefixed by "m\_". Global variables should be prefixed by "g\_".

```cpp theme={null}
class String {
public:
    ...

private:
    int m_length { 0 };
};
```

### Setters and getters

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.

```cpp theme={null}
void set_count(int); // Sets m_count.
int count() const; // Returns m_count.
```

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

```cpp theme={null}
void get_filename_and_inode_id(String&, InodeIdentifier&) const;
```

### Function names

Use descriptive verbs in function names.

```cpp theme={null}
bool convert_to_ascii(short*, size_t);
```

### The ensure\_ prefix

When there are two getters for a variable, and one of them automatically makes sure the requested object is instantiated, prefix that getter function with `ensure_`. As it ensures that an object is created, it should consequently also return a reference, not a pointer.

```cpp theme={null}
Inode* inode();
Inode& ensure_inode();
```

### Function parameters

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.

```cpp theme={null}
void set_count(int);
void do_something(Context*);
```

### Enums vs bools

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.

```cpp theme={null}
do_something(something, AllowFooBar::Yes);
paint_text_with_shadows(context, ..., text_stroke_width > 0, is_horizontal());
set_resizable(false);
```

### Enum members

Enum members should use InterCaps with an initial capital letter.

### Header guards

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

```cpp theme={null}
// MyClass.h
#pragma once
```

## Other punctuation

### Constructor initialization

Constructors for C++ classes should initialize 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. Prefer initialization at member definition whenever possible.

```cpp theme={null}
class MyClass {
    ...
    Document* m_document { nullptr };
    int m_my_member { 0 };
};

MyClass::MyClass(Document* document)
    : MySuperClass()
    , m_document(document)
{
}

MyOtherClass::MyOtherClass()
    : MySuperClass()
{
}
```

### Vector iterations

Prefer index or range-for over iterators in Vector iterations for terse, easier-to-read code.

```cpp theme={null}
for (auto& child : children)
    child->do_child_thing();
```

## Pointers and references

Both pointer types and reference types should be written with no space between the type name and the `*` or `&`.

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.

```cpp theme={null}
void MyClass::get_some_value(OutArgumentType& out_argument) const
{
    out_argument = m_value;
}

void MyClass::do_something(OutArgumentType* out_argument) const
{
    do_the_thing();
    if (out_argument)
        *out_argument = m_value;
}
```

## "using" statements

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

```cpp theme={null}
// AK/Vector.h

namespace AK {

} // namespace AK

using AK::Vector;
```

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.

```cpp theme={null}
// File.cpp

std::swap(a, b);
c = std::numeric_limits<int>::max()
```

## Types

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

```cpp theme={null}
unsigned a;
int b;
```

## Classes

For types with methods, prefer `class` over `struct`.

* For classes, make public getters and setters, keep members private with `m_` prefix.
* For structs, let everything be public and skip the `m_` prefix.

```cpp theme={null}
struct Thingy {
    String name;
    int frob_count { 0 };
};

class Doohickey {
public:
    String const& name() const { return m_name; }
    int frob_count() const { return m_frob_count; }

    void jam();

private:
    String m_name;
    int m_frob_count { 0 };
}
```

### Implicit conversions

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.

```cpp theme={null}
class LargeInt {
public:
    LargeInt(int);
...

class Vector {
public:
    explicit Vector(int size); // Not a type conversion.
    Vector create(Array); // Costly conversion.
...
```

### Singleton pattern

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

```cpp theme={null}
class UniqueObject {
public:
    static UniqueObject& the();
...
```

## Comments

Comments should be written using `//` and not `/* */`, except for the copyright notice.

Write comments as proper sentences starting with a capital letter and ending with a period (or other punctuation). One exception may be end of line comments like this: `if (x == y) // false for NaN`

Another exception is comments copied from specifications. These should be quoted verbatim, and not modified except for wrapping or to insert necessary punctuation such as adding `**` when a number is raised to a power, as this is often done using elements like `<sup>` which do not appear in the copied text.

Please wrap long comments onto multiple lines so that they are easier to read. Generally, 120 characters is a good width to aim for.

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

```cpp theme={null}
draw_jpg(); // FIXME: Make this code handle jpg in addition to the png support.
```

Explain *why* the code does something. The code itself should already say what is happening.

```cpp theme={null}
i++; // Go to the next page.
```

```cpp theme={null}
// Let users toggle the advice functionality by clicking on catdog.
catdog_widget.on_click = [&] {
    if (advice_timer->is_active())
        advice_timer->stop();
    else
        advice_timer->start();
};
```

### Spec notes

Many web specs include notes that are prefixed with `NOTE: ...`. To allow for verbatim copying of these notes into our code, we retain the `NOTE:` prefix and use [`NB:`](https://en.wikipedia.org/wiki/Nota_bene) for our own notes.

This only applies to comments as part of code that is directly implementing a spec algorithm or behavior. Comments in other places do not need a prefix.

```cpp theme={null}
// 2. If property is in already serialized, continue with the steps labeled declaration loop.
// NOTE: The prefabulated aluminite will not be suitable for use here. If the listed spec note is so long that we reach
//       column 120, we wrap around and indent the lines to match up with the first line.
// NB: We _can_ actually use the aluminite since we unprefabulated it in step 1 for performance reasons.
```

## Overriding virtual methods

The declaration of a virtual method inside a class must be declared with the `virtual` keyword. All subclasses of that class must also specify either 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.

```cpp theme={null}
class Person {
public:
    virtual String description() { ... };
}

class Student : public Person {
public:
    virtual String description() override { ... }; // This is correct because it contains both the "virtual" and "override" keywords to indicate that the method is overridden.
}
```

```cpp theme={null}
class Person {
public:
    virtual String description() { ... };
}

class Student : public Person {
public:
    virtual String description() final { ... }; // This is correct because it contains both the "virtual" and "final" keywords to indicate that the method is overridden and that no subclasses of "Student" can override "description".
}
```

## Const placement

Use "east const" style where `const` is written on the right side of the type being qualified. See [this article](https://mariusbancila.ro/blog/2018/11/23/join-the-east-const-revolution/) for more information about east const.

```cpp theme={null}
Salt const& m_salt;
```

## Casts

Before you consider a cast, please see if your problem can be solved another way that avoids the visual clutter.

* Integer constants can be specified to have (some) specific sizes with postfixes like `u, l, ul` etc. The same goes for single-precision floating-point constants with `f`.
* Working with smaller-size integers in arithmetic expressions is hard because of [implicit promotion](https://wiki.sei.cmu.edu/confluence/display/c/INT02-C.+Understand+integer+conversion+rules). Generally, it is fine to use `int` and other "large" types in local variables, and possibly cast at the end.
* If you `const_cast`, *really* consider whether your APIs need to be adjusted in terms of their constness. Does the member function you're writing actually make sense to be `const`?
* If you do checked casts between base and derived types, also consider your APIs. For example: Does the function being called actually need to receive the more general type or is it fine with the more specialized type?

If you *do* need to cast: **Don't use C-style casts**. The C-style cast has [complex behavior](https://en.cppreference.com/w/c/language/cast) that is undesired in many instances. Be aware of what sort of type conversion the code is trying to achieve, and use the appropriate (!) C++ cast operator, like `static_cast`, `reinterpret_cast`, `bit_cast`, `dynamic_cast` etc.

There is a single exception to this rule: marking a function parameter as used with `(void)parameter;`.

```cpp theme={null}
MyParentClass& object = get_object();
// Verify the type...
MyChildClass& casted = static_cast<MyChildClass&>(object);
```

## Omission of curly braces from statement blocks

Curly braces may only be omitted from `if`/`else`/`for`/`while`/etc. statement blocks if the body is a single line.

Additionally, if any body of a connected if/else statement requires curly braces according to this rule, all of them do.

```cpp theme={null}
if (condition)
    foo();
```

```cpp theme={null}
if (condition) {
    foo();
    bar();
}
```

```cpp theme={null}
if (condition) {
    foo();
} else if (condition) {
    bar();
    baz();
} else {
    qux();
}
```

```cpp theme={null}
for (size_t i = i; condition; ++i) {
    if (other_condition)
        foo();
}
```
