Better C++ Syntax Highlighting - Part 3: Namespaces
Namespaces are up next. Their declarations and references appear frequently in C++ code, and Clang exposes several node types for processing them.
Consider the following example:
And corresponding AST:
To annotate namespaces, we’ll define visitor functions for three new node types:
NamespaceDeclnodes, for namespace declarations,NamespaceAliasDeclnodes, for namespace aliases, andUsingDirectiveDeclnodes, forusing namespacedirectives.
Namespace declarations
NamespaceDecl nodes represent standard namespace declarations.
We’ll annotate these with a namespace-name tag:
With this visitor implemented, our tool produces the following output:
Namespace aliases
For NamespaceAliasDecl nodes, which represent namespace aliases, we’ll annotate both the alias and the referenced namespaces.
First, we annotate the alias:
The name and source location of the alias is retrieved from the NamespaceAliasDecl node itself.
The location at which to insert annotations is retrieved via getAliasLoc().
Next, we annotate the namespace being aliased:
As this references an already existing namespace, its name can be retrieved from its declaration using the getAliasedNamespace() function.
Its location is retrieved via getTargetNameLoc().
Both the alias and target namespaces are annotated with the namespace-name tag.
using namespace directives
The UsingDirectiveDecl node handles using namespace directives.
This visitor follows the same pattern as before:
The name of the nominated namespace is retrieved from its declaration using getNominatedNamespace(), which returns a NamespaceDecl.
As before, the namespace name is annotated with the namespace-name tag.
You’ll notice that in both examples, qualifiers these directives (such as math qualifier on the utility namespace) remain unannotated.
We will handle these when we look at generic qualifier processing in a later post in this series.
Styling
The final step is to add a definition for the namespace-name CSS style:
We’ve added support for annotating namespace declarations, aliases, and using namespace directives.
In the <LocalLink text={“next post”} to={“Better C++ Syntax Highlighting - Part 4: Functions”}>, we’ll take a closer look at annotating functions declarations, definitions, calls, and operators.
Thanks for reading!