EXTRACLANGTOOLS(1)

NAME
extraclangtools - Extra Clang Tools Documentation

Welcome to the clang-tools-extra project which contains extra tools built using Clang's tooling API's.

CLANG-TIDY

  Clang-Tidy Checks

  cert-dcl03-c

The cert-dcl03-c checker is an alias, please see misc-static-assert for more information.

  cert-dcl50-cpp

This check flags all function definitions (but not declarations) of C-style variadic functions.

This check corresponds to the CERT C++ Coding Standard rule DCL50-CPP. Do not define a C-style variadic function.

  cert-dcl54-cpp

The cert-dcl54-cpp checker is an alias, please see misc-new-delete-overloads for more information.

  cert-dcl59-cpp

The cert-dcl59-cpp checker is an alias, please see google-build-namespaces for more information.

  cert-err52-cpp

This check flags all call expressions involving setjmp() and longjmp().

This check corresponds to the CERT C++ Coding Standard rule ERR52-CPP. Do not use setjmp() or longjmp().

  cert-err58-cpp

This check flags all static or thread_local variable declarations where the constructor for the object may throw an exception.

This check corresponds to the CERT C++ Coding Standard rule ERR58-CPP. Constructors of objects with static or thread storage duration must not throw exceptions.

  cert-err60-cpp

This check flags all throw expressions where the exception object is not nothrow copy constructible.

This check corresponds to the CERT C++ Coding Standard rule ERR60-CPP. Exception objects must be nothrow copy constructible.

  cert-err61-cpp

The cert-err61-cpp checker is an alias, please see misc-throw-by-value-catch-by-reference for more information.

  cert-fio38-c

The cert-fio38-c checker is an alias, please see misc-non-copyable-objects for more information.

  cert-oop11-cpp

The cert-oop11-cpp checker is an alias, please see misc-move-constructor-init for more information.

  cppcoreguidelines-pro-bounds-array-to-pointer-decay

This check flags all array to pointer decays.

Pointers should not be used as arrays. span<T> is a bounds-checked, safe alternative to using pointers to access arrays.

This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-decay.

  cppcoreguidelines-pro-bounds-constant-array-index

This check flags all array subscript expressions on static arrays and std::arrays that either do not have a constant integer expression index or are out of bounds (for std::array). For out-of-bounds checking of static arrays, see the clang-diagnostic-array-bounds check.

The check can generate fixes after the option cppcoreguidelines-pro-bounds-constant-array-index.GslHeader has been set to the name of the include file that contains gsl::at(), e.g. "gsl/gsl.h".

This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arrayindex.

  cppcoreguidelines-pro-bounds-pointer-arithmetic

This check flags all usage of pointer arithmetic, because it could lead to an invalid pointer. Subtraction of two pointers is not flagged by this check.

Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. span<T> is a bounds-checked, safe type for accessing arrays of data.

This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arithmetic.

  cppcoreguidelines-pro-type-const-cast

This check flags all uses of const_cast in C++ code.

Modifying a variable that was declared const is undefined behavior, even with const_cast.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-constcast.

  cppcoreguidelines-pro-type-cstyle-cast

This check flags all use of C-style casts that perform a static_cast downcast, const_cast, or reinterpret_cast.

Use of these casts can violate type safety and cause the program to access a variable that is actually of type X to be accessed as if it were of an unrelated type Z. Note that a C-style (T)expression cast means to perform the first of the following that is possible: a const_cast, a static_cast, a static_cast followed by a const_cast, a reinterpret_cast, or a reinterpret_cast followed by a const_cast. This rule bans (T)expression only when used to perform an unsafe cast.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-cstylecast.

  cppcoreguidelines-pro-type-reinterpret-cast

This check flags all uses of reinterpret_cast in C++ code.

Use of these casts can violate type safety and cause the program to access a variable that is actually of type X to be accessed as if it were of an unrelated type Z.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-reinterpretcast.

  cppcoreguidelines-pro-type-static-cast-downcast

This check flags all usages of static_cast, where a base class is casted to a derived class. In those cases, a fixit is provided to convert the cast to a dynamic_cast.

Use of these casts can violate type safety and cause the program to access a variable that is actually of type X to be accessed as if it were of an unrelated type Z.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-downcast.

  cppcoreguidelines-pro-type-union-access

This check flags all access to members of unions. Passing unions as a whole is not flagged.

Reading from a union member assumes that member was the last one written, and writing to a union member assumes another member with a nontrivial destructor had its destructor called. This is fragile because it cannot generally be enforced to be safe in the language and so relies on programmer discipline to get it right.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-unions.

  cppcoreguidelines-pro-type-vararg

This check flags all calls to c-style vararg functions and all use of va_arg.

To allow for SFINAE use of vararg functions, a call is not flagged if a literal 0 is passed as the only vararg argument.

Passing to varargs assumes the correct type will be read. This is fragile because it cannot generally be enforced to be safe in the language and so relies on programmer discipline to get it right.

This rule is part of the "Type safety" profile of the C++ Core Guidelines, see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-varargs.

  google-build-explicit-make-pair

Check that make_pair's template arguments are deduced.

G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case.

Corresponding cpplint.py check name: 'build/explicit_make_pair'.

  google-build-namespaces

"cert-dcl59-cpp" redirects here as an alias for this checker.

Finds anonymous namespaces in headers.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Namespaces#Namespaces

Corresponding cpplint.py check name: 'build/namespaces'.

  google-build-using-namespace

Finds using namespace directives.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Namespaces#Namespaces

The check implements the following rule of the Google C++ Style Guide: You may not use a using-directive to make all names from a namespace available.

// Forbidden -- This pollutes the namespace.
using namespace foo;

Corresponding cpplint.py check name: build/namespaces.

  google-explicit-constructor

Checks that all single-argument constructors are explicit.

See http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Explicit_Constructors

  google-global-names-in-headers

Flag global namespace pollution in header files. Right now it only triggers on using declarations and directives.

  google-readability-braces-around-statements

Checks that bodies of if statements and loops (for, range-for, do-while, and while) are inside braces

Before:

if (condition)
  statement;

After:

if (condition) {
  statement;
}

Additionally, one can define an option ShortStatementLines defining the minimal number of lines that the statement should have in order to trigger this check.

The number of lines is counted from the end of condition or initial keyword (do/else) until the last line of the inner statement. Default value 0 means that braces will be added to all statements (not having them already).

  google-readability-casting

Finds usages of C-style casts.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Casting#Casting

Corresponding cpplint.py check name: 'readability/casting'.

This check is similar to -Wold-style-cast, but it suggests automated fixes in some cases. The reported locations should not be different from the ones generated by -Wold-style-cast.

  google-readability-function-size

Checks for large functions based on various metrics.

These options are supported:

•   LineThreshold - flag functions exceeding this number of lines. The default is -1 (ignore the number of lines).

•   StatementThreshold - flag functions exceeding this number of statements. This may differ significantly from the number of lines for macro-heavy code. The default is 800.

•   BranchThreshold - flag functions exceeding this number of control statements. The default is -1 (ignore the number of branches).

  google-readability-namespace-comments

Checks that long namespaces have a closing comment.

http://llvm.org/docs/CodingStandards.html#namespace-indentation

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Namespaces

  google-readability-redundant-smartptr-get

Find and remove redundant calls to smart pointer's .get() method.

Examples:

ptr.get()->Foo()  ==>  ptr->Foo()
*ptr.get()  ==>  *ptr
*ptr->get()  ==>  **ptr

  google-readability-todo

Finds TODO comments without a username or bug number.

Corresponding cpplint.py check: 'readability/todo'

  google-runtime-int

Finds uses of short, long and long long and suggest replacing them with u?intXX(_t)?.

The corresponding style guide rule: https://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Integer_Types.

Correspondig cpplint.py check: 'runtime/int'.

  google-runtime-member-string-references

Finds members of type const string&.

const string reference members are generally considered unsafe as they can be created from a temporary quite easily.

struct S {
  S(const string &Str) : Str(Str) {}
  const string &Str;
};
S instance("string");

In the constructor call a string temporary is created from const char * and destroyed immediately after the call. This leaves around a dangling reference.

This check emit warnings for both std::string and ::string const reference members.

Corresponding cpplint.py check name: 'runtime/member_string_reference'.

  google-runtime-memset

Finds calls to memset with a literal zero in the length argument.

This is most likely unintended and the length and value arguments are swapped.

Corresponding cpplint.py check name: 'runtime/memset'.

  google-runtime-operator

Finds overloads of unary operator &.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Operator_Overloading#Operator_Overloading

Corresponding cpplint.py check name: 'runtime/operator'.

  llvm-header-guard

TODO: add docs

  llvm-include-order

Checks the correct order of #includes.

See http://llvm.org/docs/CodingStandards.html#include-style

  llvm-namespace-comment

Checks that long namespaces have a closing comment.

http://llvm.org/docs/CodingStandards.html#namespace-indentation

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Namespaces

  llvm-twine-local

Looks for local Twine variables which are prone to use after frees and should be generally avoided.

  misc-argument-comment

Checks that argument comments match parameter names.

The check understands argument comments in the form /*parameter_name=*/ that are placed right before the argument.

void f(bool foo);
...
f(/*bar=*/true);
// warning: argument name 'bar' in comment does not match parameter name 'foo'

The check tries to detect typos and suggest automated fixes for them.

  misc-assert-side-effect

Finds assert() with side effect.

The condition of assert() is evaluated only in debug builds so a condition with side effect can cause different behavior in debug / release builds.

There are two options:

•   AssertMacros: A comma-separated list of the names of assert macros to be checked.

•   CheckFunctionCalls: Whether to treat non-const member and non-member functions as they produce side effects. Disabled by default because it can increase the number of false positive warnings.

  misc-assign-operator-signature

Finds declarations of assign operators with the wrong return and/or argument types.

•   The return type must be Class&.

•   Works with move-assign and assign by value.

•   Private and deleted operators are ignored.

  misc-bool-pointer-implicit-conversion

Checks for conditions based on implicit conversion from a bool pointer to bool.

Example:

bool *p;
if (p) {
  // Never used in a pointer-specific way.
}

  misc-definitions-in-headers

Finds non-extern non-inline function and variable definitions in header files, which can lead to potential ODR violations.

// Foo.h
int a = 1; // Warning.
extern int d; // OK: extern variable.
namespace N {
  int e = 2; // Warning.
}
// Internal linkage variable definitions are ignored for now.
// Although these might also cause ODR violations, we can be less certain and
// should try to keep the false-positive rate down.
static int b = 1;
const int c = 1;
// Warning.
int g() {
  return 1;
}
// OK: inline function definition.
inline int e() {
  return 1;
}
class A {
 public:
  int f1() { return 1; } // OK: inline member function definition.
  int f2();
};
int A::f2() { return 1; } // Warning.

  misc-inaccurate-erase

Checks for inaccurate use of the erase() method.

Algorithms like remove() do not actually remove any element from the container but return an iterator to the first redundant element at the end of the container. These redundant elements must be removed using the erase() method. This check warns when not all of the elements will be removed due to using an inappropriate overload.

  misc-inefficient-algorithm

Warns on inefficient use of STL algorithms on associative containers.

Associative containers implements some of the algorithms as methods which should be preferred to the algorithms in the algorithm header. The methods can take advanatage of the order of the elements.

  misc-macro-parentheses

Finds macros that can have unexpected behaviour due to missing parentheses.

Macros are expanded by the preprocessor as-is. As a result, there can be unexpected behaviour; operators may be evaluated in unexpected order and unary operators may become binary operators, etc.

When the replacement list has an expression, it is recommended to surround it with parentheses. This ensures that the macro result is evaluated completely before it is used.

It is also recommended to surround macro arguments in the replacement list with parentheses. This ensures that the argument value is calculated properly.

  misc-macro-repeated-side-effects

Checks for repeated argument with side effects in macros.

  misc-move-constructor-init

"cert-oop11-cpp" redirects here as an alias for this checker.

The check flags user-defined move constructors that have a ctor-initializer initializing a member or base class through a copy constructor instead of a move constructor.

It also flags constructor arguments that are passed by value, have a non-deleted move-constructor and are assigned to a class field by copy construction.

  misc-new-delete-overloads

"cert-dcl54-cpp" redirects here as an alias for this checker.

The check flags overloaded operator new() and operator delete() functions that do not have a corresponding free store function defined within the same scope. For instance, the check will flag a class implementation of a non-placement operator new() when the class does not also define a non-placement operator delete() function as well.

The check does not flag implicitly-defined operators, deleted or private operators, or placement operators.

This check corresponds to CERT C++ Coding Standard rule DCL54-CPP. Overload allocation and deallocation functions as a pair in the same scope.

  misc-noexcept-move-constructor

The check flags user-defined move constructors and assignment operators not marked with noexcept or marked with noexcept(expr) where expr evaluates to false (but is not a false literal itself).

Move constructors of all the types used with STL containers, for example, need to be declared noexcept. Otherwise STL will choose copy constructors instead. The same is valid for move assignment operations.

  misc-non-copyable-objects

"cert-fio38-c" redirects here as an alias for this checker.

The check flags dereferences and non-pointer declarations of objects that are not meant to be passed by value, such as C FILE objects or POSIX pthread_mutex_t objects.

This check corresponds to CERT C++ Coding Standard rule FIO38-C. Do not copy a FILE object.

  misc-sizeof-container

The check finds usages of sizeof on expressions of STL container types. Most likely the user wanted to use .size() instead.

All class/struct types declared in namespace std:: having a const size() method are considered containers, with the exception of std::bitset and std::array.

Examples:

std::string s;
int a = 47 + sizeof(s); // warning: sizeof() doesn't return the size of the container. Did you mean .size()?
int b = sizeof(std::string); // no warning, probably intended.
std::string array_of_strings[10];
int c = sizeof(array_of_strings) / sizeof(array_of_strings[0]); // no warning, definitely intended.
std::array<int, 3> std_array;
int d = sizeof(std_array); // no warning, probably intended.

  misc-static-assert

"cert-dcl03-c" redirects here as an alias for this checker.

Replaces assert() with static_assert() if the condition is evaluatable at compile time.

The condition of static_assert() is evaluated at compile time which is safer and more efficient.

  misc-string-integer-assignment

The check finds assignments of an integer to std::basic_string<CharT> (std::string, std::wstring, etc.). The source of the problem is the following assignment operator of std::basic_string<CharT>:

basic_string& operator=( CharT ch );

Numeric types can be implicity casted to character types.

std::string s;
int x = 5965;
s = 6;
s = x;

Use the appropriate conversion functions or character literals.

std::string s;
int x = 5965;
s = '6';
s = std::to_string(x);

In order to suppress false positives, use an explicit cast.

std::string s;
s = static_cast<char>(6);

  misc-swapped-arguments

Finds potentially swapped arguments by looking at implicit conversions.

  misc-throw-by-value-catch-by-reference

"cert-err61-cpp" redirects here as an alias for this checker.

Finds violations of the rule "Throw by value, catch by reference" presented for example in "C++ Coding Standards" by H. Sutter and A. Alexandrescu. This check also has the option to find violations of the rule "Throw anonymous temporaries" (https://www.securecoding.cert.org/confluence/display/cplusplus/ERR09-CPP.+Throw+anonymous+temporaries). The option is named "CheckThrowTemporaries" and it's on by default.

Exceptions: - throwing string literals will not be flagged despite being a pointer. They are not susceptible to slicing and the usage of string literals is idomatic. - catching character pointers (char, wchar_t, unicode character types) will not be flagged to allow catching sting literals. - moved named values will not be flagged as not throwing an anonymous temporary. In this case we can be sure that the user knows that the object can't be accessed outside catch blocks handling the error. - throwing function parameters will not be flagged as not throwing an anonymous temporary. This allows helper functions for throwing. - re-throwing caught exception variables will not be flragged as not throwing an anonymous temporary. Although this can usually be done by just writing "throw;" it happens often enough in real code.

  misc-undelegated-constructor

Finds creation of temporary objects in constructors that look like a function call to another constructor of the same class.

The user most likely meant to use a delegating constructor or base class initializer.

  misc-uniqueptr-reset-release

Find and replace unique_ptr::reset(release()) with std::move().

Example:

std::unique_ptr<Foo> x, y;
x.reset(y.release()); -> x = std::move(y);

If y is already rvalue, std::move() is not added. x and y can also be std::unique_ptr<Foo>*.

  misc-unused-alias-decls

Finds unused namespace alias declarations.

  misc-unused-parameters

Finds unused parameters and fixes them, so that -Wunused-parameter can be turned on.

  misc-unused-raii

Finds temporaries that look like RAII objects.

The canonical example for this is a scoped lock.

{
  scoped_lock(&global_mutex);
  critical_section();
}

The destructor of the scoped_lock is called before the critical_section is entered, leaving it unprotected.

We apply a number of heuristics to reduce the false positive count of this check:

•   Ignore code expanded from macros. Testing frameworks make heavy use of this.

•   Ignore types with trivial destructors. They are very unlikely to be RAII objects and there's no difference when they are deleted.

•   Ignore objects at the end of a compound statement (doesn't change behavior).

•   Ignore objects returned from a call.

  misc-virtual-near-miss

Warn if a function is a near miss (ie. the name is very similar and the function signiture is the same) to a virtual function from a base class.

Example:

struct Base {
  virtual void func();
};
struct Derived : Base {
  virtual funk();
  // warning: Do you want to override 'func'?
};

  modernize-loop-convert

This check converts for(...; ...; ...) loops to use the new range-based loops in C++11.

Three kinds of loops can be converted:

•   Loops over statically allocated arrays.

•   Loops over containers, using iterators.

•   Loops over array-like containers, using operator[] and at().

  MinConfidence option

  risky

In loops where the container expression is more complex than just a reference to a declared expression (a variable, function, enum, etc.), and some part of it appears elsewhere in the loop, we lower our confidence in the transformation due to the increased risk of changing semantics. Transformations for these loops are marked as risky, and thus will only be converted if the minimum required confidence level is set to risky.

int arr[10][20];
int l = 5;
for (int j = 0; j < 20; ++j)
  int k = arr[l][j] + l; // using l outside arr[l] is considered risky
for (int i = 0; i < obj.getVector().size(); ++i)
  obj.foo(10); // using 'obj' is considered risky

See Range-based loops evaluate end() only once for an example of an incorrect transformation when the minimum required confidence level is set to risky.

  reasonable (Default)

If a loop calls .end() or .size() after each iteration, the transformation for that loop is marked as reasonable, and thus will be converted if the required confidence level is set to reasonable (default) or lower.

// using size() is considered reasonable
for (int i = 0; i < container.size(); ++i)
  cout << container[i];

  safe

Any other loops that do not match the above criteria to be marked as risky or reasonable are marked safe, and thus will be converted if the required confidence level is set to safe or lower.

int arr[] = {1,2,3};
for (int i = 0; i < 3; ++i)
  cout << arr[i];

  Example

Original:

const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (int i = 0; i < N; ++i)
  cout << arr[i];
// reasonable conversion
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
  cout << *it;*
// reasonable conversion
for (int i = 0; i < v.size(); ++i)
  cout << v[i];

After applying the check with minimum confidence level set to reasonable (default):

const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (auto & elem : arr)
  cout << elem;
// reasonable conversion
for (auto & elem : v)
  cout << elem;
// reasonable conversion
for (auto & elem : v)
  cout << elem;

  Limitations

There are certain situations where the tool may erroneously perform transformations that remove information and change semantics. Users of the tool should be aware of the behaviour and limitations of the check outlined by the cases below.

  Comments inside loop headers

Comments inside the original loop header are ignored and deleted when transformed.

for (int i = 0; i < N; /* This will be deleted */ ++i) { }

  Range-based loops evaluate end() only once

The C++11 range-based for loop calls .end() only once during the initialization of the loop. If in the original loop .end() is called after each iteration the semantics of the transformed loop may differ.

// The following is semantically equivalent to the C++11 range-based for loop,
// therefore the semantics of the header will not change.
for (iterator it = container.begin(), e = container.end(); it != e; ++it) { }
// Instead of calling .end() after each iteration, this loop will be
// transformed to call .end() only once during the initialization of the loop,
// which may affect semantics.
for (iterator it = container.begin(); it != container.end(); ++it) { }

As explained above, calling member functions of the container in the body of the loop is considered risky. If the called member function modifies the container the semantics of the converted loop will differ due to .end() being called only once.

bool flag = false;
for (vector<T>::iterator it = vec.begin(); it != vec.end(); ++it) {
  // Add a copy of the first element to the end of the vector.
  if (!flag) {
    // This line makes this transformation 'risky'.
    vec.push_back(*it);
    flag = true;
  }
  cout << *it;
}

The original code above prints out the contents of the container including the newly added element while the converted loop, shown below, will only print the original contents and not the newly added element.

bool flag = false;
for (auto & elem : vec) {
  // Add a copy of the first element to the end of the vector.
  if (!flag) {
    // This line makes this transformation 'risky'
    vec.push_back(elem);
    flag = true;
  }
  cout << elem;
}

Semantics will also be affected if .end() has side effects. For example, in the case where calls to .end() are logged the semantics will change in the transformed loop if .end() was originally called after each iteration.

iterator end() {
  num_of_end_calls++;
  return container.end();
}

  Overloaded operator->() with side effects

Similarly, if operator->() was overloaded to have side effects, such as logging, the semantics will change. If the iterator's operator->() was used in the original loop it will be replaced with <container element>.<member> instead due to the implicit dereference as part of the range-based for loop. Therefore any side effect of the overloaded operator->() will no longer be performed.

for (iterator it = c.begin(); it != c.end(); ++it) {
  it->func(); // Using operator->()
}
// Will be transformed to:
for (auto & elem : c) {
  elem.func(); // No longer using operator->()
}

  Pointers and references to containers

While most of the check's risk analysis is dedicated to determining whether the iterator or container was modified within the loop, it is possible to circumvent the analysis by accessing and modifying the container through a pointer or reference.

If the container were directly used instead of using the pointer or reference the following transformation would have only been applied at the risky level since calling a member function of the container is considered risky. The check cannot identify expressions associated with the container that are different than the one used in the loop header, therefore the transformation below ends up being performed at the safe level.

vector<int> vec;
vector<int> *ptr = &vec;
vector<int> &ref = vec;
for (vector<int>::iterator it = vec.begin(), e = vec.end(); it != e; ++it) {
  if (!flag) {
    // Accessing and modifying the container is considered risky, but the risk
    // level is not raised here.
    ptr->push_back(*it);
    ref.push_back(*it);
    flag = true;
  }
}

  modernize-make-unique

This check finds the creation of std::unique_ptr objects by explicitly calling the constructor and a new expression, and replaces it with a call to std::make_unique, introduced in C++14.

auto my_ptr = std::unique_ptr<MyPair>(new MyPair(1, 2));
// becomes
auto my_ptr = std::make_unique<MyPair>(1, 2);

  modernize-pass-by-value

With move semantics added to the language and the standard library updated with move constructors added for many types it is now interesting to take an argument directly by value, instead of by const-reference, and then copy. This check allows the compiler to take care of choosing the best way to construct the copy.

The transformation is usually beneficial when the calling code passes an rvalue and assumes the move construction is a cheap operation. This short example illustrates how the construction of the value happens:

void foo(std::string s);
std::string get_str();
void f(const std::string &str) {
  foo(str);       // lvalue  -> copy construction
  foo(get_str()); // prvalue -> move construction
}

NOTE: Currently, only constructors are transformed to make use of pass-by-value. Contributions that handle other situations are welcome!

  Pass-by-value in constructors

Replaces the uses of const-references constructor parameters that are copied into class fields. The parameter is then moved with std::move().

Since std::move() is a library function declared in <utility> it may be necessary to add this include. The check will add the include directive when necessary.

 #include <string>
 class Foo {
 public:
-  Foo(const std::string &Copied, const std::string &ReadOnly)
-    : Copied(Copied), ReadOnly(ReadOnly)
+  Foo(std::string Copied, const std::string &ReadOnly)
+    : Copied(std::move(Copied)), ReadOnly(ReadOnly)
   {}
 private:
   std::string Copied;
   const std::string &ReadOnly;
 };
 std::string get_cwd();
 void f(const std::string &Path) {
   // The parameter corresponding to 'get_cwd()' is move-constructed. By
   // using pass-by-value in the Foo constructor we managed to avoid a
   // copy-construction.
   Foo foo(get_cwd(), Path);
 }

If the parameter is used more than once no transformation is performed since moved objects have an undefined state. It means the following code will be left untouched:

#include <string>
void pass(const std::string &S);
struct Foo {
  Foo(const std::string &S) : Str(S) {
    pass(S);
  }
  std::string Str;
};

  Known limitations

A situation where the generated code can be wrong is when the object referenced is modified before the assignment in the init-list through a "hidden" reference.

Example:

 std::string s("foo");
 struct Base {
   Base() {
     s = "bar";
   }
 };
 struct Derived : Base {
-  Derived(const std::string &S) : Field(S)
+  Derived(std::string S) : Field(std::move(S))
   { }
   std::string Field;
 };
 void f() {
-  Derived d(s); // d.Field holds "bar"
+  Derived d(s); // d.Field holds "foo"
 }

  Note about delayed template parsing

When delayed template parsing is enabled, constructors part of templated contexts; templated constructors, constructors in class templates, constructors of inner classes of template classes, etc., are not transformed. Delayed template parsing is enabled by default on Windows as a Microsoft extension: Clang Compiler User’s Manual - Microsoft extensions.

Delayed template parsing can be enabled using the -fdelayed-template-parsing flag and disabled using -fno-delayed-template-parsing.

Example:

  template <typename T> class C {
    std::string S;
  public:
=  // using -fdelayed-template-parsing (default on Windows)
=  C(const std::string &S) : S(S) {}
+  // using -fno-delayed-template-parsing (default on non-Windows systems)
+  C(std::string S) : S(std::move(S)) {}
  };

SEE ALSO: For more information about the pass-by-value idiom, read: Want Speed? Pass by Value.

  modernize-redundant-void-arg

Find and remove redundant void argument lists.

Examples:
    Initial code | Code with applied fixes
    int f(void); | int f();
    int (*f(void))(void); | int (*f())();
    typedef int (*f_t(void))(void); | typedef int (*f_t())();
    void (C::*p)(void); | void (C::*p)();
    C::C(void) {} | C::C() {}
    C::~C(void) {} | C::~C() {}

  modernize-replace-auto-ptr

This check replaces the uses of the deprecated class std::auto_ptr by std::unique_ptr (introduced in C++11). The transfer of ownership, done by the copy-constructor and the assignment operator, is changed to match std::unique_ptr usage by using explicit calls to std::move().

Migration example:

-void take_ownership_fn(std::auto_ptr<int> int_ptr);
+void take_ownership_fn(std::unique_ptr<int> int_ptr);
 void f(int x) {
-  std::auto_ptr<int> a(new int(x));
-  std::auto_ptr<int> b;
+  std::unique_ptr<int> a(new int(x));
+  std::unique_ptr<int> b;
-  b = a;
-  take_ownership_fn(b);
+  b = std::move(a);
+  take_ownership_fn(std::move(b));
 }

Since std::move() is a library function declared in <utility> it may be necessary to add this include. The check will add the include directive when necessary.

  Known Limitations

•   If headers modification is not activated or if a header is not allowed to be changed this check will produce broken code (compilation error), where the headers' code will stay unchanged while the code using them will be changed.

•   Client code that declares a reference to an std::auto_ptr coming from code that can't be migrated (such as a header coming from a 3rd party library) will produce a compilation error after migration. This is because the type of the reference will be changed to std::unique_ptr but the type returned by the library won't change, binding a reference to std::unique_ptr from an std::auto_ptr. This pattern doesn't make much sense and usually std::auto_ptr are stored by value (otherwise what is the point in using them instead of a reference or a pointer?).

     // <3rd-party header...>
     std::auto_ptr<int> get_value();
     const std::auto_ptr<int> & get_ref();
     // <calling code (with migration)...>
    -std::auto_ptr<int> a(get_value());
    +std::unique_ptr<int> a(get_value()); // ok, unique_ptr constructed from auto_ptr
    -const std::auto_ptr<int> & p = get_ptr();
    +const std::unique_ptr<int> & p = get_ptr(); // won't compile

•   Non-instantiated templates aren't modified.

    template <typename X>
    void f() {
        std::auto_ptr<X> p;
    }
    // only 'f<int>()' (or similar) will trigger the replacement.

  modernize-shrink-to-fit

Replace copy and swap tricks on shrinkable containers with the shrink_to_fit() method call.

The shrink_to_fit() method is more readable and more effective than the copy and swap trick to reduce the capacity of a shrinkable container. Note that, the shrink_to_fit() method is only available in C++11 and up.

  modernize-use-auto

This check is responsible for using the auto type specifier for variable declarations to improve code readability and maintainability. For example:

std::vector<int>::iterator I = my_container.begin();
// transforms to:
auto I = my_container.begin();

The auto type specifier will only be introduced in situations where the variable type matches the type of the initializer expression. In other words auto should deduce the same type that was originally spelled in the source. However, not every situation should be transformed:

int val = 42;
InfoStruct &I = SomeObject.getInfo();
// Should not become:
auto val = 42;
auto &I = SomeObject.getInfo();

In this example using auto for builtins doesn't improve readability. In other situations it makes the code less self-documenting impairing readability and maintainability. As a result, auto is used only introduced in specific situations described below.

  Iterators

Iterator type specifiers tend to be long and used frequently, especially in loop constructs. Since the functions generating iterators have a common format, the type specifier can be replaced without obscuring the meaning of code while improving readability and maintainability.

for (std::vector<int>::iterator I = my_container.begin(),
                                E = my_container.end();
     I != E; ++I) {
}
// becomes
for (auto I = my_container.begin(), E = my_container.end(); I != E; ++I) {
}

The check will only replace iterator type-specifiers when all of the following conditions are satisfied:

•   The iterator is for one of the standard container in std namespace:

•   array

•   deque

•   forward_list

•   list

•   vector

•   map

•   multimap

•   set

•   multiset

•   unordered_map

•   unordered_multimap

•   unordered_set

•   unordered_multiset

•   queue

•   priority_queue

•   stack

•   The iterator is one of the possible iterator types for standard containers:

•   iterator

•   reverse_iterator

•   const_iterator

•   const_reverse_iterator

•   In addition to using iterator types directly, typedefs or other ways of referring to those types are also allowed. However, implementation-specific types for which a type like std::vector<int>::iterator is itself a typedef will not be transformed. Consider the following examples:

    // The following direct uses of iterator types will be transformed.
    std::vector<int>::iterator I = MyVec.begin();
    {
      using namespace std;
      list<int>::iterator I = MyList.begin();
    }
    // The type specifier for J would transform to auto since it's a typedef
    // to a standard iterator type.
    typedef std::map<int, std::string>::const_iterator map_iterator;
    map_iterator J = MyMap.begin();
    // The following implementation-specific iterator type for which
    // std::vector<int>::iterator could be a typedef would not be transformed.
    __gnu_cxx::__normal_iterator<int*, std::vector> K = MyVec.begin();

•   The initializer for the variable being declared is not a braced initializer list. Otherwise, use of auto would cause the type of the variable to be deduced as``std::initializer_list``.

  New expressions

Frequently, when a pointer is declared and initialized with new, the pointee type has to be written twice: in the declaration type and in the new expression. In this cases, the declaration type can be replaced with auto improving readability and maintainability.

TypeName *my_pointer = new TypeName(my_param);
// becomes
auto my_pointer = new TypeName(my_param);

The check will also replace the declaration type in multiple declarations, if the following conditions are satisfied:

•   All declared variables have the same type (i.e. all of them are pointers to the same type).

•   All declared variables are initialized with a new expression.

•   The types of all the new expressions are the same than the pointee of the declaration type.

    TypeName *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
    // becomes
    auto my_first_pointer = new TypeName, my_second_pointer = new TypeName;

  Known Limitations

•   If the initializer is an explicit conversion constructor, the check will not replace the type specifier even though it would be safe to do so.

•   User-defined iterators are not handled at this time.

  modernize-use-default

This check replaces default bodies of special member functions with = default;. The explicitly defaulted function declarations enable more opportunities in optimization, because the compiler might treat explicitly defaulted functions as trivial.

struct A {
  A() {}
  ~A();
};
A::~A() {}
// becomes
struct A {
  A() = default;
  ~A();
};
A::~A() = default;

NOTE: Copy-constructor, copy-assignment operator, move-constructor and move-assignment operator are not supported yet.

  modernize-use-nullptr

The check converts the usage of null pointer constants (eg. NULL, 0) to use the new C++11 nullptr keyword.

  Example

void assignment() {
  char *a = NULL;
  char *b = 0;
  char c = 0;
}
int *ret_ptr() {
  return 0;
}

transforms to:

void assignment() {
  char *a = nullptr;
  char *b = nullptr;
  char c = 0;
}
int *ret_ptr() {
  return nullptr;
}

  User defined macros

By default this check will only replace the NULL macro and will skip any user-defined macros that behaves like NULL. The user can use the :option:UserNullMacros option to specify a comma-separated list of macro names that will be transformed along with NULL.

  Example

#define MY_NULL (void*)0
void assignment() {
  void *p = MY_NULL;
}

transforms to:

#define MY_NULL NULL
void assignment() {
  int *p = nullptr;
}

if the UserNullMacros option is set to MY_NULL.

  modernize-use-override

Use C++11's override and remove virtual where applicable.

  readability-braces-around-statements

Checks that bodies of if statements and loops (for, range-for, do-while, and while) are inside braces

Before:

if (condition)
  statement;

After:

if (condition) {
  statement;
}

Additionally, one can define an option ShortStatementLines defining the minimal number of lines that the statement should have in order to trigger this check.

The number of lines is counted from the end of condition or initial keyword (do/else) until the last line of the inner statement. Default value 0 means that braces will be added to all statements (not having them already).

  readability-container-size-empty

Checks whether a call to the size() method can be replaced with a call to empty().

The emptiness of a container should be checked using the empty() method instead of the size() method. It is not guaranteed that size() is a constant-time function, and it is generally more efficient and also shows clearer intent to use empty(). Furthermore some containers may implement the empty() method but not implement the size() method. Using empty() whenever possible makes it easier to switch to another container in the future.

  readability-else-after-return

Flags the usages of else after return.

http://llvm.org/docs/CodingStandards.html#don-t-use-else-after-a-return

  readability-function-size

Checks for large functions based on various metrics.

These options are supported:

•   LineThreshold - flag functions exceeding this number of lines. The default is -1 (ignore the number of lines).

•   StatementThreshold - flag functions exceeding this number of statements. This may differ significantly from the number of lines for macro-heavy code. The default is 800.

•   BranchThreshold - flag functions exceeding this number of control statements. The default is -1 (ignore the number of branches).

  readability-identifier-naming

Checks for identifiers naming style mismatch.

This check will try to enforce coding guidelines on the identifiers naming. It supports lower_case, UPPER_CASE, camelBack and CamelCase casing and tries to convert from one to another if a mismatch is detected.

It also supports a fixed prefix and suffix that will be prepended or appended to the identifiers, regardless of the casing.

Many configuration options are available, in order to be able to create different rules for different kind of identifier. In general, the rules are falling back to a more generic rule if the specific case is not configured.

  readability-implicit-bool-cast

This check can be used to find implicit conversions between built-in types and booleans. Depending on use case, it may simply help with readability of the code, or in some cases, point to potential bugs which remain unnoticed due to implicit conversions.

The following is a real-world example of bug which was hiding behind implicit bool cast:

class Foo {
  int m_foo;
public:
  void setFoo(bool foo) { m_foo = foo; } // warning: implicit cast bool -> int
  int getFoo() { return m_foo; }
};
void use(Foo& foo) {
  bool value = foo.getFoo(); // warning: implicit cast int -> bool
}

This code is the result of unsuccessful refactoring, where type of m_foo changed from bool to int. The programmer forgot to change all occurences of bool, and the remaining code is no longer correct, yet it still compiles without any visible warnings.

In addition to issuing warnings, FixIt hints are provided to help solve the reported issues. This can be used for improving readabilty of code, for example:

void conversionsToBool() {
  float floating;
  bool boolean = floating;
  // ^ propose replacement: bool boolean = floating != 0.0f;
  int integer;
  if (integer) {}
  // ^ propose replacement: if (integer != 0) {}
  int* pointer;
  if (!pointer) {}
  // ^ propose replacement: if (pointer == nullptr) {}
  while (1) {}
  // ^ propose replacement: while (true) {}
}
void functionTakingInt(int param);
void conversionsFromBool() {
  bool boolean;
  functionTakingInt(boolean);
  // ^ propose replacement: functionTakingInt(static_cast<int>(boolean));
  functionTakingInt(true);
  // ^ propose replacement: functionTakingInt(1);
}

In general, the following cast types are checked:

•   integer expression/literal to boolean,

•   floating expression/literal to boolean,

•   pointer/pointer to member/nullptr/NULL to boolean,

•   boolean expression/literal to integer,

•   boolean expression/literal to floating.

The rules for generating FixIt hints are:

•   in case of casts from other built-in type to bool, an explicit comparison is proposed to make it clear what exaclty is being compared:

•   bool boolean = floating; is changed to bool boolean = floating == 0.0f;,

•   for other types, appropriate literals are used (0, 0u, 0.0f, 0.0, nullptr),

•   in case of negated expressions cast to bool, the proposed replacement with comparison is simplified:

•   if (!pointer) is changed to if (pointer == nullptr),

•   in case of casts from bool to other built-in types, an explicit static_cast is proposed to make it clear that a cast is taking place:

•   int integer = boolean; is changed to int integer = static_cast<int>(boolean);,

•   if the cast is performed on type literals, an equivalent literal is proposed, according to what type is actually expected, for example:

•   functionTakingBool(0); is changed to functionTakingBool(false);,

•   functionTakingInt(true); is changed to functionTakingInt(1);,

•   for other types, appropriate literals are used (false, true, 0, 1, 0u, 1u, 0.0f, 1.0f, 0.0, 1.0f).

Some additional accommodations are made for pre-C++11 dialects:

•   false literal cast to pointer is detected,

•   instead of nullptr literal, 0 is proposed as replacement.

    Occurences of implicit casts inside macros and template instantiations are deliberately ignored, as it is not clear how to deal with such cases.

  readability-inconsistent-declaration-parameter-name

Find function declarations which differ in parameter names.

Example:

// in foo.hpp:
void foo(int a, int b, int c);
// in foo.cpp:
void foo(int d, int e, int f); // warning

This check should help to enforce consistency in large projects, where it often happens that a definition of function is refactored, changing the parameter names, but its declaration in header file is not updated. With this check, we can easily find and correct such inconsistencies, keeping declaration and definition always in sync.

Unnamed parameters are allowed and are not taken into account when comparing function declarations, for example:

void foo(int a);
void foo(int); // no warning

To help with refactoring, in some cases FixIt hints are generated to align parameter names to a single naming convention. This works with the assumption that the function definition is the most up-to-date version, as it directly references parameter names in its body. Example:

void foo(int a); // warning and FixIt hint (replace "a" to "b")
int foo(int b) { return b + 2; } // definition with use of "b"

In the case of multiple redeclarations or function template specializations, a warning is issued for every redeclaration or specialization inconsistent with the definition or the first declaration seen in a translation unit.

  readability-named-parameter

Find functions with unnamed arguments.

The check implements the following rule originating in the Google C++ Style Guide:

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Function_Declarations_and_Definitions#Function_Declarations_and_Definitions

All parameters should be named, with identical names in the declaration and implementation.

Corresponding cpplint.py check name: 'readability/function'.

  readability-redundant-smartptr-get

Find and remove redundant calls to smart pointer's .get() method.

Examples:

ptr.get()->Foo()  ==>  ptr->Foo()
*ptr.get()  ==>  *ptr
*ptr->get()  ==>  **ptr

  readability-redundant-string-cstr

Finds unnecessary calls to std::string::c_str().

  readability-simplify-boolean-expr

Looks for boolean expressions involving boolean constants and simplifies them to use the appropriate boolean expression directly.

Examples:
Initial expression | Result
if (b == true) | if (b)
if (b == false) | if (!b)
if (b && true) | if (b)
if (b && false) | if (false)
if (b || true) | if (true)
if (b || false) | if (b)
e ? true : false | e
e ? false : true | !e
if (true) t(); else f(); | t();
if (false) t(); else f(); | f();
if (e) return true; else return false; | return e;
if (e) return false; else return true; | return !e;
if (e) b = true; else b = false; | b = e;
if (e) b = false; else b = true; | b = !e;
if (e) return true; return false; | return e;
if (e) return false; return true; | return !e;

The resulting expression e is modified as follows:

1.  Unnecessary parentheses around the expression are removed.

2.  Negated applications of ! are eliminated.

3.  Negated applications of comparison operators are changed to use the opposite condition.

4.  Implicit conversions of pointer to bool are replaced with explicit comparisons to nullptr.

5.  Implicit casts to bool are replaced with explicit casts to bool.

6.  Object expressions with explicit operator bool conversion operators are replaced with explicit casts to bool.

Examples:

1.  The ternary assignment bool b = (i < 0) ? true : false; has redundant parentheses and becomes bool b = i < 0;.

2.  The conditional return if (!b) return false; return true; has an implied double negation and becomes return b;.

3.  The conditional return if (i < 0) return false; return true; becomes return i >= 0;.

    The conditional return if (i != 0) return false; return true; becomes return i == 0;.

4.  The conditional return if (p) return true; return false; has an implicit conversion of a pointer to bool and becomes return p != nullptr;.

    The ternary assignment bool b = (i & 1) ? true : false; has an implicit conversion of i & 1 to bool and becomes bool b = static_cast<bool>(i & 1);.

5.  The conditional return if (i & 1) return true; else return false; has an implicit conversion of an integer quantity i & 1 to bool and becomes return static_cast<bool>(i & 1);

6.  Given struct X { explicit operator bool(); };, and an instance x of struct X, the conditional return if (x) return true; return false; becomes return static_cast<bool>(x);

    When a conditional boolean return or assignment appears at the end of a chain of if, else if statements, the conditional statement is left unchanged unless the option ChainedConditionalReturn or ChainedConditionalAssignment, respectively, is specified as non-zero. The default value for both options is zero.

  readability-uniqueptr-delete-release

Replace delete <unique_ptr>.release() with <unique_ptr> = nullptr. The latter is shorter, simpler and does not require use of raw pointer APIs.

clang-tidy is a clang-based C++ linter tool. Its purpose is to provide an extensible framework for diagnosing and fixing typical programming errors, like style violations, interface misuse, or bugs that can be deduced via static analysis. clang-tidy is modular and provides a convenient interface for writing new checks.

  Using clang-tidy

clang-tidy is a LibTooling-based tool, and it's easier to work with if you set up a compile command database for your project (for an example of how to do this see How To Setup Tooling For LLVM). You can also specify compilation options on the command line after --:

$ clang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ...

clang-tidy has its own checks and can also run Clang static analyzer checks. Each check has a name and the checks to run can be chosen using the -checks= option, which specifies a comma-separated list of positive and negative (prefixed with -) globs. Positive globs add subsets of checks, negative globs remove them. For example,

$ clang-tidy test.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-alpha*

will disable all default checks (-*) and enable all clang-analyzer-* checks except for clang-analyzer-alpha* ones.

The -list-checks option lists all the enabled checks. When used without -checks=, it shows checks enabled by default. Use -checks=* to see all available checks or with any other value of -checks= to see which checks are enabled by this value.

There are currently the following groups of checks:

•   Checks related to the LLVM coding conventions have names starting with llvm-.

•   Checks related to the Google coding conventions have names starting with google-.

•   Checks named modernize-* advocate the usage of modern (currently "modern" means "C++11") language constructs.

•   The readability- checks target readability-related issues that don't relate to any particular coding style.

•   Checks with names starting with misc- the checks that we didn't have a better category for.

•   Clang static analyzer checks are named starting with clang-analyzer-.

    Clang diagnostics are treated in a similar way as check diagnostics. Clang diagnostics are displayed by clang-tidy and can be filtered out using -checks= option. However, the -checks= option does not affect compilation arguments, so it can not turn on Clang warnings which are not already turned on in build configuration.

    Clang diagnostics have check names starting with clang-diagnostic-. Diagnostics which have a corresponding warning option, are named clang-diagostic-<warning-option>, e.g. Clang warning controlled by -Wliteral-conversion will be reported with check name clang-diagnostic-literal-conversion.

    The -fix flag instructs clang-tidy to fix found errors if supported by corresponding checks.

    An overview of all the command-line options:

    $ clang-tidy -help
    USAGE: clang-tidy [options] <source0> [... <sourceN>]
    OPTIONS:
    General options:
      -help                    - Display available options (-help-hidden
                                 for more)
      -help-list               - Display list of available options
                                 (-help-list-hidden for more)
      -version                 - Display the version of this program
    clang-tidy options:
      -analyze-temporary-dtors   - Enable temporary destructor-aware analysis in
                                   clang-analyzer- checks.
                                   This option overrides the value read from a
                                   .clang-tidy file.
      -checks=<string>           - Comma-separated list of globs with optional '-'
                                   prefix. Globs are processed in order of appearance
                                   in the list. Globs without '-' prefix add checks
                                   with matching names to the set, globs with the '-'
                                   prefix remove checks with matching names from the
                                   set of enabled checks.
                                   This option's value is appended to the value read
                                   from a .clang-tidy file, if any.
      -config=<string>           - Specifies a configuration in YAML/JSON format:
                                     -config="{Checks: '*', CheckOptions: [{key: x, value: y}]}"
                                   When the value is empty, clang-tidy will attempt to find
                                   a file named .clang-tidy for each source file in its parent
                                   directories.
      -dump-config               - Dumps configuration in the YAML format to stdout. This option
                                   should be used along with a file name (and '--' if the file is
                                   outside of a project with configured compilation database). The
                                   configuration used for this file will be printed.
      -enable-check-profile      - Enable per-check timing profiles, and print a report to stderr.
      -export-fixes=<filename>   - YAML file to store suggested fixes in. The
                                   stored fixes can be applied to the input source
                                   code with clang-apply-replacements.
      -extra-arg=<string>        - Additional argument to append to the compiler command line
      -extra-arg-before=<string> - Additional argument to prepend to the compiler command line
      -fix                       - Apply suggested fixes. Without -fix-errors
                                   clang-tidy will bail out if any compilation
                                   errors were found.
      -fix-errors                - Apply suggested fixes even if compilation errors
                                   were found. If compiler errors have attached
                                   fix-its, clang-tidy will apply them as well.
      -header-filter=<string>    - Regular expression matching the names of the
                                   headers to output diagnostics from. Diagnostics
                                   from the main file of each translation unit are
                                   always displayed.
                                   Can be used together with -line-filter.
                                   This option overrides the value read from a
                                   .clang-tidy file.
      -line-filter=<string>      - List of files with line ranges to filter the
                                   warnings. Can be used together with
                                   -header-filter. The format of the list is a JSON
                                   array of objects:
                                     [
                                       {"name":"file1.cpp","lines":[[1,3],[5,7]]},
                                       {"name":"file2.h"}
                                     ]
      -list-checks               - List all enabled checks and exit. Use with
                                   -checks=* to list all available checks.
      -p=<string>                - Build path
      -system-headers            - Display the errors from system headers.
    -p <build-path> is used to read a compile command database.
            For example, it can be a CMake build directory in which a file named
            compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
            CMake option to get this output). When no build path is specified,
            a search for compile_commands.json will be attempted through all
            parent paths of the first input file . See:
            http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
            example of setting up Clang Tooling on a source tree.
    <source0> ... specify the paths of source files. These paths are
            looked up in the compile command database. If the path of a file is
            absolute, it needs to point into CMake's source tree. If the path is
            relative, the current working directory needs to be in the CMake
            source tree and the file must be in a subdirectory of the current
            working directory. "./" prefixes in the relative files will be
            automatically removed, but the rest of a relative path must be a
            suffix of a path in the compile command database.
    Configuration files:
      clang-tidy attempts to read configuration for each source file from a
      .clang-tidy file located in the closest parent directory of the source
      file. If any configuration options have a corresponding command-line
      option, command-line option takes precedence. The effective
      configuration can be inspected using -dump-config:
        $ clang-tidy -dump-config - --
        ---
        Checks:          '-*,some-check'
        HeaderFilterRegex: ''
        AnalyzeTemporaryDtors: false
        User:            user
        CheckOptions:
          - key:             some-check.SomeOption
            value:           'some value'
        ...

  Getting Involved

clang-tidy has several own checks and can run Clang static analyzer checks, but its power is in the ability to easily write custom checks.

Checks are organized in modules, which can be linked into clang-tidy with minimal or no code changes in clang-tidy.

Checks can plug the analysis on the preprocessor level using PPCallbacks or on the AST level using AST Matchers. When an error is found, checks can report them in a way similar to how Clang diagnostics work. A fix-it hint can be attached to a diagnostic message.

The interface provided by clang-tidy makes it easy to write useful and precise checks in just a few lines of code. If you have an idea for a good check, the rest of this document explains how to do this.

  Choosing the Right Place for your Check

If you have an idea of a check, you should decide whether it should be implemented as a:

•   Clang diagnostic: if the check is generic enough, targets code patterns that most probably are bugs (rather than style or readability issues), can be implemented effectively and with extremely low false positive rate, it may make a good Clang diagnostic.

•   Clang static analyzer check: if the check requires some sort of control flow analysis, it should probably be implemented as a static analyzer check.

•   clang-tidy check is a good choice for linter-style checks, checks that are related to a certain coding style, checks that address code readability, etc.

  Preparing your Workspace

If you are new to LLVM development, you should read the Getting Started with the LLVM System, Using Clang Tools and How To Setup Tooling For LLVM documents to check out and build LLVM, Clang and Clang Extra Tools with CMake.

Once you are done, change to the llvm/tools/clang/tools/extra directory, and let's start!

  The Directory Structure

clang-tidy source code resides in the llvm/tools/clang/tools/extra directory and is structured as follows:

clang-tidy/                       # Clang-tidy core.
|-- ClangTidy.h                   # Interfaces for users and checks.
|-- ClangTidyModule.h             # Interface for clang-tidy modules.
|-- ClangTidyModuleRegistry.h     # Interface for registering of modules.
   ...
|-- google/                       # Google clang-tidy module.
|-+
  |-- GoogleTidyModule.cpp
  |-- GoogleTidyModule.h
        ...
|-- llvm/                         # LLVM clang-tidy module.
|-+
  |-- LLVMTidyModule.cpp
  |-- LLVMTidyModule.h
        ...
|-- tool/                         # Sources of the clang-tidy binary.
        ...
test/clang-tidy/                  # Integration tests.
    ...
unittests/clang-tidy/             # Unit tests.
|-- ClangTidyTest.h
|-- GoogleModuleTest.cpp
|-- LLVMModuleTest.cpp
    ...

  Writing a clang-tidy Check

So you have an idea of a useful check for clang-tidy.

You need to decide which module the check belongs to. If the check verifies conformance of the code to a certain coding style, it probably deserves a separate module and a directory in clang-tidy/ (there are LLVM and Google modules already).

After choosing the module, you need to create a class for your check:

#include "../ClangTidy.h"
namespace clang {
namespace tidy {
class MyCheck : public ClangTidyCheck {
};
} // namespace tidy
} // namespace clang

Next, you need to decide whether it should operate on the preprocessor level or on the AST level. Let's imagine that we need to work with the AST in our check. In this case we need to override two methods:

...
class ExplicitConstructorCheck : public ClangTidyCheck {
public:
  ExplicitConstructorCheck(StringRef Name, ClangTidyContext *Context)
      : ClangTidyCheck(Name, Context) {}
  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
  void check(ast_matchers::MatchFinder::MatchResult &Result) override;
};

Constructor of the check receives the Name and Context parameters, and must forward them to the ClangTidyCheck constructor.

In the registerMatchers method we create an AST Matcher (see AST Matchers for more information) that will find the pattern in the AST that we want to inspect. The results of the matching are passed to the check method, which can further inspect them and report diagnostics.

using namespace ast_matchers;
void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(constructorDecl().bind("ctor"), this);
}
void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
  const CXXConstructorDecl *Ctor =
      Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
  // Do not be confused: isExplicit means 'explicit' keyword is present,
  // isImplicit means that it's a compiler-generated constructor.
  if (Ctor->isOutOfLine() || Ctor->isExplicit() || Ctor->isImplicit())
    return;
  if (Ctor->getNumParams() == 0 || Ctor->getMinRequiredArguments() > 1)
    return;
  SourceLocation Loc = Ctor->getLocation();
  diag(Loc, "single-argument constructors must be explicit")
      << FixItHint::CreateInsertion(Loc, "explicit ");
}

(The full code for this check resides in clang-tidy/google/ExplicitConstructorCheck.{h,cpp}).

  Registering your Check

The check should be registered in the corresponding module with a distinct name:

class MyModule : public ClangTidyModule {
 public:
  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
    CheckFactories.registerCheck<ExplicitConstructorCheck>(
        "my-explicit-constructor");
  }
};

Now we need to register the module in the ClangTidyModuleRegistry using a statically initialized variable:

static ClangTidyModuleRegistry::Add<MyModule> X("my-module",
                                                "Adds my lint checks.");

When using LLVM build system, we need to use the following hack to ensure the module is linked into the clang-tidy binary:

Add this near the ClangTidyModuleRegistry::Add<MyModule> variable:

// This anchor is used to force the linker to link in the generated object file
// and thus register the MyModule.
volatile int MyModuleAnchorSource = 0;

And this to the main translation unit of the clang-tidy binary (or the binary you link the clang-tidy library in) clang-tidy/tool/ClangTidyMain.cpp:

// This anchor is used to force the linker to link the MyModule.
extern volatile int MyModuleAnchorSource;
static int MyModuleAnchorDestination = MyModuleAnchorSource;

  Configuring Checks

If a check needs configuration options, it can access check-specific options using the Options.get<Type>("SomeOption", DefaultValue) call in the check constructor. In this case the check should also override the ClangTidyCheck::storeOptions method to make the options provided by the check discoverable. This method lets clang-tidy know which options the check implements and what the current values are (e.g. for the -dump-config command line option).

class MyCheck : public ClangTidyCheck {
  const unsigned SomeOption1;
  const std::string SomeOption2;
public:
  MyCheck(StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      SomeOption(Options.get("SomeOption1", -1U)),
      SomeOption(Options.get("SomeOption2", "some default")) {}
  void storeOptions(ClangTidyOptions::OptionMap &Opts) override {
    Options.store(Opts, "SomeOption1", SomeOption1);
    Options.store(Opts, "SomeOption2", SomeOption2);
  }
  ...

Assuming the check is registered with the name "my-check", the option can then be set in a .clang-tidy file in the following way:

CheckOptions:
  - key: my-check.SomeOption1
    value: 123
  - key: my-check.SomeOption2
    value: 'some other value'

If you need to specify check options on a command line, you can use the inline YAML format:

$ clang-tidy -config="{CheckOptions: [{key: a, value: b}, {key: x, value: y}]}" ...

  Testing Checks

clang-tidy checks can be tested using either unit tests or lit tests. Unit tests may be more convenient to test complex replacements with strict checks. Lit tests allow using partial text matching and regular expressions which makes them more suitable for writing compact tests for diagnostic messages.

The check_clang_tidy.py script provides an easy way to test both diagnostic messages and fix-its. It filters out CHECK lines from the test file, runs clang-tidy and verifies messages and fixes with two separate FileCheck invocations. To use the script, put a .cpp file with the appropriate RUN line in the test/clang-tidy directory. Use CHECK-MESSAGES: and CHECK-FIXES: lines to write checks against diagnostic messages and fixed code.

It's advised to make the checks as specific as possible to avoid checks matching to incorrect parts of the input. Use [[@LINE+X]]/[[@LINE-X]] substitutions and distinct function and variable names in the test code.

Here's an example of a test using the check_clang_tidy.py script:

// RUN: %python %S/check_clang_tidy.py %s google-readability-casting %t
void f(int a) {
  int b = (int)a;
  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: redundant cast to the same type [google-readability-casting]
  // CHECK-FIXES: int b = a;
}

  Running clang-tidy on LLVM

To test a check it's best to try it out on a larger code base. LLVM and Clang are the natural targets as you already have the source around. The most convenient way to run clang-tidy is with a compile command database; CMake can automatically generate one, for a description of how to enable it see How To Setup Tooling For LLVM. Once compile_commands.json is in place and a working version of clang-tidy is in PATH the entire code base can be analyzed with clang-tidy/tool/run-clang-tidy.py. The script executes clang-tidy with the default set of checks on every translation unit in the compile command database and displays the resulting warnings and errors. The script provides multiple configuration flags.

•   The default set of checks can be overridden using the -checks argument, taking the identical format as clang-tidy does. For example -checks=-*,modernize-use-override will run the modernize-use-override check only.

•   To restrict the files examined you can provide one or more regex arguments that the file names are matched against. run-clang-tidy.py clang-tidy/.*Check\.cpp will only analyze clang-tidy checkers. It may also be necessary to restrict the header files warnings are displayed from using the -header-filter flag. It has the same behavior as the corresponding clang-tidy flag.

•   To apply suggested fixes -fix can be passed as an argument. This gathers all changes in a temporary directory and applies them. Passing -format will run clang-format over changed lines.

MODULARIZE USER'S MANUAL

  Modularize Usage

modularize [<modularize-options>] [<module-map>|<include-files-list>]* [<front-end-options>...]

<modularize-options> is a place-holder for options specific to modularize, which are described below in Modularize Command Line Options.

<module-map> specifies the path of a file name for an existing module map. The module map must be well-formed in terms of syntax. Modularize will extract the header file names from the map. Only normal headers are checked, assuming headers marked "private", "textual", or "exclude" are not to be checked as a top-level include, assuming they either are included by other headers which are checked, or they are not suitable for modules.

<include-files-list> specifies the path of a file name for a file containing the newline-separated list of headers to check with respect to each other. Lines beginning with '#' and empty lines are ignored. Header file names followed by a colon and other space-separated file names will include those extra files as dependencies. The file names can be relative or full paths, but must be on the same line. For example:

header1.h
header2.h
header3.h: header1.h header2.h

Note that unless a -prefix (header path) option is specified, non-absolute file paths in the header list file will be relative to the header list file directory. Use -prefix to specify a different directory.

<front-end-options> is a place-holder for regular Clang front-end arguments, which must follow the <include-files-list>. Note that by default, modularize assumes .h files contain C++ source, so if you are using a different language, you might need to use a -x option to tell Clang that the header contains another language, i.e.: -x c

Note also that because modularize does not use the clang driver, you will likely need to pass in additional compiler front-end arguments to match those passed in by default by the driver.

  Modularize Command Line Options

-prefix=<header-path>
    Prepend the given path to non-absolute file paths in the header list file. By default, headers are assumed to be relative to the header list file directory. Use -prefix to specify a different directory.

-module-map-path=<module-map-path>
    Generate a module map and output it to the given file. See the description in module-map-generation.

-problem-files-list=<problem-files-list-file-name>
    For use only with module map assistant. Input list of files that have problems with respect to modules. These will still be included in the generated module map, but will be marked as "excluded" headers.

-root-module=<root-name>
    Put modules generated by the -module-map-path option in an enclosing module with the given name. See the description in module-map-generation.

-block-check-header-list-only
    Limit the #include-inside-extern-or-namespace-block check to only those headers explicitly listed in the header list. This is a work-around for avoiding error messages for private includes that purposefully get included inside blocks.

-no-coverage-check
    Don't do the coverage check for a module map.

-coverage-check-only
    Only do the coverage check for a module map.

-display-file-lists
    Display lists of good files (no compile errors), problem files, and a combined list with problem files preceded by a '#'. This can be used to quickly determine which files have problems. The latter combined list might be useful in starting to modularize a set of headers. You can start with a full list of headers, use -display-file-lists option, and then use the combined list as your intermediate list, uncommenting-out headers as you fix them.

    modularize is a standalone tool that checks whether a set of headers provides the consistent definitions required to use modules. For example, it detects whether the same entity (say, a NULL macro or size_t typedef) is defined in multiple headers or whether a header produces different definitions under different circumstances. These conditions cause modules built from the headers to behave poorly, and should be fixed before introducing a module map.

    modularize also has an assistant mode option for generating a module map file based on the provided header list. The generated file is a functional module map that can be used as a starting point for a module.map file.

  Getting Started

To build from source:

1.  Read Getting Started with the LLVM System and Clang Tools Documentation for information on getting sources for LLVM, Clang, and Clang Extra Tools.

2.  Getting Started with the LLVM System and Building LLVM with CMake give directions for how to build. With sources all checked out into the right place the LLVM build will build Clang Extra Tools and their dependencies automatically.

•   If using CMake, you can also use the modularize target to build just the modularize tool and its dependencies.

    Before continuing, take a look at ModularizeUsage to see how to invoke modularize.

  What Modularize Checks

Modularize will check for the following:

•   Duplicate global type and variable definitions

•   Duplicate macro definitions

•   Macro instances, 'defined(macro)', or #if, #elif, #ifdef, #ifndef conditions that evaluate differently in a header

•   #include directives inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks

•   Module map header coverage completeness (in the case of a module map input only)

    Modularize will do normal C/C++ parsing, reporting normal errors and warnings, but will also report special error messages like the following:

    error: '(symbol)' defined at multiple locations:
       (file):(row):(column)
       (file):(row):(column)
    error: header '(file)' has different contents depending on how it was included

    The latter might be followed by messages like the following:

    note: '(symbol)' in (file) at (row):(column) not always provided

    Checks will also be performed for macro expansions, defined(macro) expressions, and preprocessor conditional directives that evaluate inconsistently, and can produce error messages like the following:

     (...)/SubHeader.h:11:5:
    #if SYMBOL == 1
        ^
    error: Macro instance 'SYMBOL' has different values in this header,
           depending on how it was included.
      'SYMBOL' expanded to: '1' with respect to these inclusion paths:
        (...)/Header1.h
          (...)/SubHeader.h
    (...)/SubHeader.h:3:9:
    #define SYMBOL 1
            ^
    Macro defined here.
      'SYMBOL' expanded to: '2' with respect to these inclusion paths:
        (...)/Header2.h
            (...)/SubHeader.h
    (...)/SubHeader.h:7:9:
    #define SYMBOL 2
            ^
    Macro defined here.

    Checks will also be performed for '#include' directives that are nested inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks, and can produce error message like the following:

    IncludeInExtern.h:2:3:
    #include "Empty.h"
    ^
    error: Include directive within extern "C" {}.
    IncludeInExtern.h:1:1:
    extern "C" {
    ^
    The "extern "C" {}" block is here.

  Module Map Coverage Check

The coverage check uses the Clang library to read and parse the module map file. Starting at the module map file directory, or just the include paths, if specified, it will collect the names of all the files it considers headers (no extension, .h, or .inc--if you need more, modify the isHeader function). It then compares the headers against those referenced in the module map, either explicitly named, or implicitly named via an umbrella directory or umbrella file, as parsed by the ModuleMap object. If headers are found which are not referenced or covered by an umbrella directory or file, warning messages will be produced, and this program will return an error code of 1. If no problems are found, an error code of 0 is returned.

Note that in the case of umbrella headers, this tool invokes the compiler to preprocess the file, and uses a callback to collect the header files included by the umbrella header or any of its nested includes. If any front end options are needed for these compiler invocations, these can be included on the command line after the module map file argument.

Warning message have the form: warning: module.modulemap does not account for file: Level3A.h

Note that for the case of the module map referencing a file that does not exist, the module map parser in Clang will (at the time of this writing) display an error message.

To limit the checks modularize does to just the module map coverage check, use the -coverage-check-only option.

For example:

modularize -coverage-check-only module.modulemap

  Module Map Generation

If you specify the -module-map-path=<module map file>, modularize will output a module map based on the input header list. A module will be created for each header. Also, if the header in the header list is a partial path, a nested module hierarchy will be created in which a module will be created for each subdirectory component in the header path, with the header itself represented by the innermost module. If other headers use the same subdirectories, they will be enclosed in these same modules also.

For example, for the header list:

SomeTypes.h
SomeDecls.h
SubModule1/Header1.h
SubModule1/Header2.h
SubModule2/Header3.h
SubModule2/Header4.h
SubModule2.h

The following module map will be generated:

// Output/NoProblemsAssistant.txt
// Generated by: modularize -module-map-path=Output/NoProblemsAssistant.txt \
     -root-module=Root NoProblemsAssistant.modularize
module SomeTypes {
  header "SomeTypes.h"
  export *
}
module SomeDecls {
  header "SomeDecls.h"
  export *
}
module SubModule1 {
  module Header1 {
    header "SubModule1/Header1.h"
    export *
  }
  module Header2 {
    header "SubModule1/Header2.h"
    export *
  }
}
module SubModule2 {
  module Header3 {
    header "SubModule2/Header3.h"
    export *
  }
  module Header4 {
    header "SubModule2/Header4.h"
    export *
  }
  header "SubModule2.h"
  export *
}

An optional -root-module=<root-name> option can be used to cause a root module to be created which encloses all the modules.

An optional -problem-files-list=<problem-file-name> can be used to input a list of files to be excluded, perhaps as a temporary stop-gap measure until problem headers can be fixed.

For example, with the same header list from above:

// Output/NoProblemsAssistant.txt
// Generated by: modularize -module-map-path=Output/NoProblemsAssistant.txt \
     -root-module=Root NoProblemsAssistant.modularize
module Root {
  module SomeTypes {
    header "SomeTypes.h"
    export *
  }
  module SomeDecls {
    header "SomeDecls.h"
    export *
  }
  module SubModule1 {
    module Header1 {
      header "SubModule1/Header1.h"
      export *
    }
    module Header2 {
      header "SubModule1/Header2.h"
      export *
    }
  }
  module SubModule2 {
    module Header3 {
      header "SubModule2/Header3.h"
      export *
    }
    module Header4 {
      header "SubModule2/Header4.h"
      export *
    }
    header "SubModule2.h"
    export *
  }
}

Note that headers with dependents will be ignored with a warning, as the Clang module mechanism doesn't support headers the rely on other headers to be included first.

The module map format defines some keywords which can't be used in module names. If a header has one of these names, an underscore ('_') will be prepended to the name. For example, if the header name is header.h, because header is a keyword, the module name will be _header. For a list of the module map keywords, please see: Lexical structure

PP-TRACE USER'S MANUAL

pp-trace is a standalone tool that traces preprocessor activity. It's also used as a test of Clang's PPCallbacks interface. It runs a given source file through the Clang preprocessor, displaying selected information from callback functions overidden in a PPCallbacks derivation. The output is in a high-level YAML format, described in pp-trace Output Format.

  pp-trace Usage

  Command Line Format

pp-trace [<pp-trace-options>] <source-file> [<front-end-options>]

<pp-trace-options> is a place-holder for options specific to pp-trace, which are described below in Command Line Options.

<source-file> specifies the source file to run through the preprocessor.

<front-end-options> is a place-holder for regular Clang Compiler Options, which must follow the <source-file>.

  Command Line Options

-ignore <callback-name-list>
    This option specifies a comma-separated list of names of callbacks that shouldn't be traced. It can be used to eliminate unwanted trace output. The callback names are the name of the actual callback function names in the PPCallbacks class:

•   FileChanged

•   FileSkipped

•   FileNotFound

•   InclusionDirective

•   moduleImport

•   EndOfMainFile

•   Ident

•   PragmaDirective

•   PragmaComment

•   PragmaDetectMismatch

•   PragmaDebug

•   PragmaMessage

•   PragmaDiagnosticPush

•   PragmaDiagnosticPop

•   PragmaDiagnostic

•   PragmaOpenCLExtension

•   PragmaWarning

•   PragmaWarningPush

•   PragmaWarningPop

•   MacroExpands

•   MacroDefined

•   MacroUndefined

•   Defined

•   SourceRangeSkipped

•   If

•   Elif

•   Ifdef

•   Ifndef

•   Else

•   Endif

-output <output-file>
    By default, pp-trace outputs the trace information to stdout. Use this option to output the trace information to a file.

  pp-trace Output Format

The pp-trace output is formatted as YAML. See http://yaml.org/ for general YAML information. It's arranged as a sequence of information about the callback call, including the callback name and argument information, for example::

---
- Callback: Name
  Argument1: Value1
  Argument2: Value2
(etc.)
...

With real data::

---
- Callback: FileChanged
  Loc: "c:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-include.cpp:1:1"
  Reason: EnterFile
  FileType: C_User
  PrevFID: (invalid)
  (etc.)
- Callback: FileChanged
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-include.cpp:5:1"
  Reason: ExitFile
  FileType: C_User
  PrevFID: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/Input/Level1B.h"
- Callback: EndOfMainFile
...

In all but one case (MacroDirective) the "Argument" scalars have the same name as the argument in the corresponding PPCallbacks callback function.

  Callback Details

The following sections describe the pupose and output format for each callback.

Click on the callback name in the section heading to see the Doxygen documentation for the callback.

The argument descriptions table describes the callback argument information displayed.

The Argument Name field in most (but not all) cases is the same name as the callback function parameter.

The Argument Value Syntax field describes the values that will be displayed for the argument value. It uses an ad hoc representation that mixes literal and symbolic representations. Enumeration member symbols are shown as the actual enum member in a (member1|member2|...) form. A name in parentheses can either represent a place holder for the described value, or confusingly, it might be a literal, such as (null), for a null pointer. Locations are shown as quoted only to avoid confusing the documentation generator.

The Clang C++ Type field is the type from the callback function declaration.

The description describes the argument or what is displayed for it.

Note that in some cases, such as when a structure pointer is an argument value, only some key member or members are shown to represent the value, instead of trying to display all members of the structure.

  FileChanged Callback

FileChanged is called when the preprocessor enters or exits a file, both the top level file being compiled, as well as any #include directives. It will also be called as a result of a system header pragma or in internal renaming of a file.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Reason | (EnterFile|ExitFile|SystemHeaderPragma|RenameFile) | PPCallbacks::FileChangeReason | Reason for change.
FileType | (C_User|C_System|C_ExternCSystem) | SrcMgr::CharacteristicKind | Include type.
PrevFID | ((file)|(invalid)) | FileID | Previous file, if any.

Example::

- Callback: FileChanged
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-include.cpp:1:1"
  Reason: EnterFile
  FileType: C_User
  PrevFID: (invalid)

  FileSkipped Callback

FileSkipped is called when a source file is skipped as the result of header guard optimization.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
ParentFile | ("(file)" or (null)) | const FileEntry | The file that #included the skipped file.
FilenameTok | (token) | const Token | The token in ParentFile that indicates the skipped file.
FileType | (C_User|C_System|C_ExternCSystem) | SrcMgr::CharacteristicKind | The file type.

Example::

- Callback: FileSkipped
  ParentFile: "/path/filename.h"
  FilenameTok: "filename.h"
  FileType: C_User

  FileNotFound Callback

FileNotFound is called when an inclusion directive results in a file-not-found error.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
FileName | "(file)" | StringRef | The name of the file being included, as written in the source code.
RecoveryPath | (path) | SmallVectorImpl<char> | If this client indicates that it can recover from this missing file, the client should set this as an additional header search patch.

Example::

- Callback: FileNotFound
  FileName: "/path/filename.h"
  RecoveryPath:

  InclusionDirective Callback

InclusionDirective is called when an inclusion directive of any kind (#include</code>, #import</code>, etc.) has been processed, regardless of whether the inclusion will actually result in an inclusion.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
HashLoc | "(file):(line):(col)" | SourceLocation | The location of the '#' that starts the inclusion directive.
IncludeTok | (token) | const Token | The token that indicates the kind of inclusion directive, e.g., 'include' or 'import'.
FileName | "(file)" | StringRef | The name of the file being included, as written in the source code.
IsAngled | (true|false) | bool | Whether the file name was enclosed in angle brackets; otherwise, it was enclosed in quotes.
FilenameRange | "(file)" | CharSourceRange | The character range of the quotes or angle brackets for the written file name.
File | "(file)" | const FileEntry | The actual file that may be included by this inclusion directive.
SearchPath | "(path)" | StringRef | Contains the search path which was used to find the file in the file system.
RelativePath | "(path)" | StringRef | The path relative to SearchPath, at which the include file was found.
Imported | ((module name)|(null)) | const Module | The module, whenever an inclusion directive was automatically turned into a module import or null otherwise.

Example::

- Callback: InclusionDirective
  IncludeTok: include
  FileName: "Input/Level1B.h"
  IsAngled: false
  FilenameRange: "Input/Level1B.h"
  File: "D:/Clang/llvmnewmod/tools/clang/tools/extra/test/pp-trace/Input/Level1B.h"
  SearchPath: "D:/Clang/llvmnewmod/tools/clang/tools/extra/test/pp-trace"
  RelativePath: "Input/Level1B.h"
  Imported: (null)

  moduleImport Callback

moduleImport is called when there was an explicit module-import syntax.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
ImportLoc | "(file):(line):(col)" | SourceLocation | The location of import directive token.
Path | "(path)" | ModuleIdPath | The identifiers (and their locations) of the module "path".
Imported | ((module name)|(null)) | const Module | The imported module; can be null if importing failed.

Example::

- Callback: moduleImport
  ImportLoc: "d:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-modules.cpp:4:2"
  Path: [{Name: Level1B, Loc: "d:/Clang/llvmnewmod/tools/clang/tools/extra/test/pp-trace/pp-trace-modules.cpp:4:9"}, {Name: Level2B, Loc: "d:/Clang/llvmnewmod/tools/clang/tools/extra/test/pp-trace/pp-trace-modules.cpp:4:17"}]
  Imported: Level2B

  EndOfMainFile Callback

EndOfMainFile is called when the end of the main file is reached.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
(no arguments) |  |  |

Example::

- Callback: EndOfMainFile

  Ident Callback

Ident is called when a #ident or #sccs directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
str | (name) | const std::string | The text of the directive.

Example::

- Callback: Ident
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-ident.cpp:3:1"
  str: "$Id$"

  PragmaDirective Callback

PragmaDirective is called when start reading any pragma directive.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Introducer | (PIK_HashPragma|PIK__Pragma|PIK___pragma) | PragmaIntroducerKind | The type of the pragma directive.

Example::

- Callback: PragmaDirective
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Introducer: PIK_HashPragma

  PragmaComment Callback

PragmaComment is called when a #pragma comment directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Kind | ((name)|(null)) | const IdentifierInfo | The comment kind symbol.
Str | (message directive) | const std::string | The comment message directive.

Example::

- Callback: PragmaComment
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Kind: library
  Str: kernel32.lib

  PragmaDetectMismatch Callback

PragmaDetectMismatch is called when a #pragma detect_mismatch directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Name | "(name)" | const std::string | The name.
Value | (string) | const std::string | The value.

Example::

- Callback: PragmaDetectMismatch
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Name: name
  Value: value

  PragmaDebug Callback

PragmaDebug is called when a #pragma clang __debug directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
DebugType | (string) | StringRef | Indicates type of debug message.

Example::

- Callback: PragmaDebug
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  DebugType: warning

  PragmaMessage Callback

PragmaMessage is called when a #pragma message directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Namespace | (name) | StringRef | The namespace of the message directive.
Kind | (PMK_Message|PMK_Warning|PMK_Error) | PPCallbacks::PragmaMessageKind | The type of the message directive.
Str | (string) | StringRef | The text of the message directive.

Example::

- Callback: PragmaMessage
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
  Kind: PMK_Message
  Str: The message text.

  PragmaDiagnosticPush Callback

PragmaDiagnosticPush is called when a #pragma gcc dianostic push directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Namespace | (name) | StringRef | Namespace name.

Example::

- Callback: PragmaDiagnosticPush
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"

  PragmaDiagnosticPop Callback

PragmaDiagnosticPop is called when a #pragma gcc dianostic pop directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Namespace | (name) | StringRef | Namespace name.

Example::

- Callback: PragmaDiagnosticPop
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"

  PragmaDiagnostic Callback

PragmaDiagnostic is called when a #pragma gcc dianostic directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Namespace | (name) | StringRef | Namespace name.
mapping | (0|MAP_IGNORE|MAP_WARNING|MAP_ERROR|MAP_FATAL) | diag::Severity | Mapping type.
Str | (string) | StringRef | Warning/error name.

Example::

- Callback: PragmaDiagnostic
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
  mapping: MAP_WARNING
  Str: WarningName

  PragmaOpenCLExtension Callback

PragmaOpenCLExtension is called when OpenCL extension is either disabled or enabled with a pragma.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
NameLoc | "(file):(line):(col)" | SourceLocation | The location of the name.
Name | (name) | const IdentifierInfo | Name symbol.
StateLoc | "(file):(line):(col)" | SourceLocation | The location of the state.
State | (1|0) | unsigned | Enabled/disabled state.

Example::

- Callback: PragmaOpenCLExtension
  NameLoc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:10"
  Name: Name
  StateLoc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:18"
  State: 1

  PragmaWarning Callback

PragmaWarning is called when a #pragma warning directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
WarningSpec | (string) | StringRef | The warning specifier.
Ids | [(number)[, ...]] | ArrayRef<int> | The warning numbers.

Example::

- Callback: PragmaWarning
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  WarningSpec: disable
  Ids: 1,2,3

  PragmaWarningPush Callback

PragmaWarningPush is called when a #pragma warning(push) directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
Level | (number) | int | Warning level.

Example::

- Callback: PragmaWarningPush
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Level: 1

  PragmaWarningPop Callback

PragmaWarningPop is called when a #pragma warning(pop) directive is read.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.

Example::

- Callback: PragmaWarningPop
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-pragma.cpp:3:1"

  MacroExpands Callback

MacroExpands is called when ::HandleMacroExpandedIdentifier when a macro invocation is found.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.
Range | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange | The source range for the expansion.
Args | [(name)|(number)|<(token name)>[, ...]] | const MacroArgs | The argument tokens. Names and numbers are literal, everything else is of the form '<' tokenName '>'.

Example::

- Callback: MacroExpands
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define
  Range: [(nonfile), (nonfile)]
  Args: [a <plus> y, b]

  MacroDefined Callback

MacroDefined is called when a macro definition is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.

Example::

- Callback: MacroDefined
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define

  MacroUndefined Callback

MacroUndefined is called when a macro #undef is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.

Example::

- Callback: MacroUndefined
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define

  Defined Callback

Defined is called when the 'defined' operator is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.
Range | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange | The source range for the directive.

Example::

- Callback: Defined
  MacroNameTok: MACRO
  MacroDirective: (null)
  Range: ["D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:5", "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:19"]

  SourceRangeSkipped Callback

SourceRangeSkipped is called when a source range is skipped.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Range | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange | The source range skipped.

Example::

- Callback: SourceRangeSkipped
  Range: [":/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:2", ":/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:9:2"]

  If Callback

If is called when an #if is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
ConditionRange | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange | The source range for the condition.
ConditionValue | (true|false) | bool | The condition value.

Example::

- Callback: If
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:2"
  ConditionRange: ["D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:4", "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:9:1"]
  ConditionValue: false

  Elif Callback

Elif is called when an #elif is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
ConditionRange | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange | The source range for the condition.
ConditionValue | (true|false) | bool | The condition value.
IfLoc | "(file):(line):(col)" | SourceLocation | The location of the directive.

Example::

- Callback: Elif
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  ConditionRange: ["D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:10:4", "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:11:1"]
  ConditionValue: false
  IfLoc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:2"

  Ifdef Callback

Ifdef is called when an #ifdef is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.

Example::

- Callback: Ifdef
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-conditional.cpp:3:1"
  MacroNameTok: MACRO
  MacroDirective: MD_Define

  Ifndef Callback

Ifndef is called when an #ifndef is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the directive.
MacroNameTok | (token) | const Token | The macro name token.
MacroDirective | (MD_Define|MD_Undefine|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure.

Example::

- Callback: Ifndef
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-conditional.cpp:3:1"
  MacroNameTok: MACRO
  MacroDirective: MD_Define

  Else Callback

Else is called when an #else is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the else directive.
IfLoc | "(file):(line):(col)" | SourceLocation | The location of the if directive.

Example::

- Callback: Else
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  IfLoc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:2"

  Endif Callback

Endif is called when an #endif is seen.

Argument descriptions:
Argument Name | Argument Value Syntax | Clang C++ Type | Description
Loc | "(file):(line):(col)" | SourceLocation | The location of the endif directive.
IfLoc | "(file):(line):(col)" | SourceLocation | The location of the if directive.

Example::

- Callback: Endif
  Loc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  IfLoc: "D:/Clang/llvm/tools/clang/tools/extra/test/pp-trace/pp-trace-macro.cpp:8:2"

  Building pp-trace

To build from source:

1.  Read Getting Started with the LLVM System and Clang Tools Documentation for information on getting sources for LLVM, Clang, and Clang Extra Tools.

2.  Getting Started with the LLVM System and Building LLVM with CMake give directions for how to build. With sources all checked out into the right place the LLVM build will build Clang Extra Tools and their dependencies automatically.

•   If using CMake, you can also use the pp-trace target to build just the pp-trace tool and its dependencies.

•   genindex

•   search

AUTHOR
The Clang Team

COPYRIGHT
2007-2016, The Clang Team