Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Simple C++ code transformations

Visiting the CppElement tree

Let’s transform the following code into a tree of CppElement:

We can then “visit” this tree, and for example log the type of all encountered elements:

CppUnit
  CppEmptyLine
  CppFunctionDecl name=AddNumbers
    CppType name=int
    CppParameterList
      CppParameter
        CppDecl name=c
          CppType name=MyModule_Class
  CppEmptyLine

Transforming the CppElement tree

Let’s suppose we want to apply a mass source code transformation where:

  • all functions names should be transformed to “snake_case” (with a warning on top)

  • all types whose name start with MyModule_ should be replaced by MyModule:: (i.e. we want to add a namespace)

In our example,

int AddNumbers(const MyModule_Class& c);

should be transformed to

// Was changed to snake_case!
int add_numbers(const MyModule::Class& c);

We can achieve this by defining my_refactor_visitor this way:

Let’s run this visitor and see its output:

Loading...

Note: str_code_verbatim still retains the original source code

Loading...