Text of clang.llvm.org › docs › ClangTransformerTutorial.html as Styx crawled it on Nov 18, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Clang Transformer Tutorial - Clang

Hide navigation sidebar Hide table of contents sidebar Back to top Edit this page Toggle table of contents sidebar Clang Transformer Tutorial # A tutorial on how to write a source-to-source translation tool using Clang Transformer. What is Clang Transformer? # Clang Transformer is a framework for writing C++ diagnostics and program transformations. It is built on the clang toolchain and the LibTooling library, but aims to hide much of the complexity of clang’s native, low-level libraries.

The core abstraction of Transformer is the rewrite rule , which specifies how to change a given program pattern into a new form. Here are some examples of tasks you can achieve with Transformer: warn against using the name MkX for a declared function, change MkX to MakeX , where MkX is the name of a declared function, change s.size() to Size(s) , where s is a string , collapse e.child().m() to e.m() , for any expression e and method named m .

All of the examples have a common form: they identify a pattern that is the target of the transformation, they specify an edit to the code identified by the pattern, and their pattern and edit refer to common variables, like s , e , and m , that range over code fragments. Our first and second examples also specify constraints on the pattern that aren’t apparent from the syntax alone, like “ s is a string .” Even the first example (“warn …”) shares this form, even though it doesn’t change any of the code – it’s “edit” is simply a no-op.

Transformer helps users succinctly specify rules of this sort and easily execute them locally over a collection of files, apply them to selected portions of a codebase, or even bundle them as a clang-tidy check for ongoing application. Who is Clang Transformer for? # Clang Transformer is for developers who want to write clang-tidy checks or write tools to modify a large number of C++ files in (roughly) the same way. What qualifies as “large” really depends on the nature of the change and your patience for repetitive editing.

In our experience, automated solutions become worthwhile somewhere between 100 and 500 files. Getting Started # Patterns in Transformer are expressed with clang’s AST matchers . Matchers are a language of combinators for describing portions of a clang Abstract Syntax Tree (AST). Since clang’s AST includes complete type information (within the limits of single Translation Unit (TU) ), these patterns can even encode rich constraints on the type properties of AST nodes.

We assume a familiarity with the clang AST and the corresponding AST matchers for the purpose of this tutorial. Users who are unfamiliar with either are encouraged to start with the recommended references in Related Reading . Example: style-checking names # Assume you have a style-guide rule which forbids functions from being named “MkX” and you want to write a check that catches any violations of this rule. We can express this a Transformer rewrite rule: makeRule ( functionDecl ( hasName ( "MkX" )). bind ( "fun" ), noopEdit ( node ( "fun" )), cat ( "The name ``MkX`` is not allowed for functions; please rename" )); makeRule is our go-to function for generating rewrite rules.

It takes three arguments: the pattern, the edit, and (optionally) an explanatory note. In our example, the pattern ( functionDecl(...) ) identifies the declaration of the function MkX . Since we’re just diagnosing the problem, but not suggesting a fix, our edit is a no-op. But, it contains an anchor for the diagnostic message: node("fun") says to associate the message with the source range of the AST node bound to “fun”; in this case, the ill-named function declaration.

Finally, we use cat to build a message that explains the change. Regarding the name cat – we’ll discuss it in more detail below, but suffice it to say that it can also take multiple arguments and concatenate their results. Note that the result of makeRule is a value of type clang::transformer::RewriteRule , but most users don’t need to care about the details of this type. Example: renaming a function # Now, let’s extend this example to a transformation ; specifically, the second example above: makeRule ( declRefExpr ( to ( functionDecl ( hasName ( "MkX" )))), changeTo ( cat ( "MakeX" )), cat ( "MkX has been renamed MakeX" )); In this example, the pattern ( declRefExpr(...) ) identifies any reference to the function MkX , rather than the declaration itself, as in our previous example.

Our edit ( changeTo(...) ) says to change the code matched by the pattern to the text “MakeX”. Finally, we use cat again to build a message that explains the change. Here are some example changes that this rule would make: Original Result X x = MkX(3); X x = MakeX(3); CallFactory(MkX, 3); CallFactory(MakeX, 3); auto f = MkX; auto f = MakeX; Example: method to function # Next, let’s write a rule to replace a method call with a (free) function call, applied to the original method call’s target object.

Specifically, “change s.size() to Size(s) , where s is a string .” We start with a simpler change that ignores the type of s . That is, it will modify any method call where the method is named “size”: llvm :: StringRef s = "str" ; makeRule ( cxxMemberCallExpr ( on ( expr (). bind ( s )), callee ( cxxMethodDecl ( hasName ( "size" )))), changeTo ( cat ( "Size(" , node ( s ), ")" )), cat ( "Method ``size`` is deprecated in favor of free function ``Size``" )); We express the pattern with the given AST matcher, which binds the method call’s target to s [ 1 ] .

For the edit, we again use changeTo , but this time we construct the term from multiple parts, which we compose with cat . The second part of our term is node(s) , which selects the source code corresponding to the AST node s that was bound when a match was found in the AST for our rule’s pattern. node(s) constructs a RangeSelector , which, when used in cat , indicates that the selected source should be inserted in the output at that point.

Now, we probably don’t want to rewrite all invocations of “size” methods, just those on std::string s. We can achieve this change simply by refining our matcher. The rest of the rule remains unchanged: llvm :: StringRef s = "str" ; makeRule ( cxxMemberCallExpr ( on ( expr ( hasType ( namedDecl ( hasName ( "std::string" )))) . bind ( s )), callee ( cxxMethodDecl ( hasName ( "size" )))), changeTo ( cat ( "Size(" , node ( s ), ")" )), cat ( "Method ``size`` is deprecated in favor of free function ``Size``" )); Example: rewriting method calls # In this example, we delete an “intermediary” method call in a string of invocations.

This scenario can arise, for example, if you want to collapse a substructure into its parent. llvm :: StringRef e = "expr" , m = "member" ; auto child_call = cxxMemberCallExpr ( on ( expr (). bind ( e )), callee ( cxxMethodDecl ( hasName ( "child" )))); makeRule ( cxxMemberCallExpr ( on ( child_call ), callee ( memberExpr (). bind ( m )), changeTo ( cat ( e , "." , member ( m ), "()" ))), cat ( "``child`` accessor is being removed; call " , member ( m ), " directly on parent" )); This rule isn’t quite what we want: it will rewrite my_object.child().foo() to my_object.foo() , but it will also rewrite my_ptr->child().foo() to my_ptr.foo() , which is not what we intend.

We could fix this by restricting the pattern with not(isArrow()) in the definition of child_call . Yet, we want to rewrite calls through pointers. To capture this idiom, we provide the access combinator to intelligently construct a field/method access. In our example, the member access is expressed as: access ( e , cat ( member ( m ))) The first argument specifies the object being accessed and the second, a description of the field/method name.

In this case, we specify that the method name should be copied from the source – specifically, the source range of m ’s member. To construct the method call, we would use this expression in cat : cat ( acc

The rest of this page is on the live site.