Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tidy translucent typedefs

Part 1 Tavian Barnes

This is a follow-up to an earlier post that introduced translucent typedefs: type aliases that warn on only one conversion direction. In my case, I wanted them for my dynamic string library, to let you use the full <string.h> API with them while other functions should operate only on dynamic strings:

#include <assert.h>
#include <stdio.h>
#include <string.h>

// Dynamic strings are dchar *; regular strings are char *
typedef char dchar;

/// Create a new dynamic string
dchar *dstralloc(void);
/// O(1) length, only for dynamic strings
size_t dstrlen(const dchar *);
/// Append to a dynamic string
int dstrcat(dchar **dest, const char *src);

int main(void) {
	dchar *dstr = dstralloc();
	dstrcat(&dstr, "Hello world!");

	// Regular string APIs still work
	puts(dstr);
	assert(dstrlen(dstr) == strlen(dstr));
	char *str = strstr(dstr, "world");

	dstrlen(str);                // Warning!
	dstrcat(&str, "\nGoodbye!"); // Warning!
	dstr = str;                  // Warning!

	dstrlen((dchar *)str);       // No warning
	dstr = (dchar *)str;         // No warning
}

The same technique could be useful for other things like escaped/sanitized/validated strings, taint tracking, etc.

My previous way of (almost) achieving this was quite ugly, but luckily this year’s Clang version 22 brings a new feature that makes custom warnings like this much easier: query based custom clang-tidy checks. This lets you write queries with a DSL for matching Clang’s AST

match binaryOperator(
  isAssignmentOperator(),
  hasLHS(hasType(dcharPtr)),
  hasRHS(hasType(charPtr)),
)

and turn the results into nicely formatted diagnostics.

foo.c:26:9: warning: implicit conversion from 'char' to 'dchar'
   26 |         dstr = str;
      |                ^

To learn how to write these queries, it’s helpful to play around with the interactive clang-query program. You pass it your source file(s) before the --, and your compiler flags (if any) after the --, and you get a REPL for the query DSL.

$ clang-query foo.c -- -std=c23
clang-query> 

There’s a help command and tab-completion to help you figure out how to write matchers, which is great since the official docs are a bit dense.

The match command lists the matches of the query you give it:

clang-query> match typedefDecl(hasName("dchar"))

Match #1:

foo.c:6:1: note: "root" binds here
    6 | typedef char dchar;
      | ^~~~~~~~~~~~~~~~~~
1 match.

By default it highlights the matched locations in the source file like a diagnostic would. You can enable other output formats with the enable output ... command.

You can write let bindings to reuse subqueries:

clang-query> let dchar qualType(hasDeclaration(typedefDecl(hasName("dchar"))))
clang-query> let dcharPtr pointsTo(dchar)
clang-query> match varDecl(hasType(dcharPtr))

Match #1:

foo.c:11:16: note: "root" binds here
   11 | size_t dstrlen(const dchar *);
      |                ^~~~~~~~~~~~~

Match #2:

foo.c:16:2: note: "root" binds here
   16 |         dchar *dstr = dstralloc();
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~
2 matches.

We want to write queries that warn where an “implicit conversion” from char to dchar (really char * to dchar *, char ** to dchar **, etc.) would happen. In reality, dchar and char are the same type, so there are no type conversion/implicit cast nodes to look for in the AST. But Clang does track which declarations/expressions use which typedef aliases, and we can use that to find contexts where plain char is used but dchar is expected. There are only a few cases worth checking:

  • function calls
    size_t dstrlen(const dchar *dstr);
    dstrlen("string");
            ~~~~~~~~
    
  • return values
    dchar *foo(void) {
    	return "string";
    	       ~~~~~~~~
    
  • variable declarations
    const dchar *dstr = "string";
                        ~~~~~~~~
    
  • assignments
    const dchar *dstr;
    dstr = "string";
           ~~~~~~~~
    
  • struct field initializers, left as an exercise for the reader (I couldn’t figure this out, let me know if you do)
    struct s { const dchar *f; };
    struct s v = { .f = "string" };
                        ~~~~~~~~
    

Let’s start by finding all assignment expressions:

clang-query> match binaryOperator(isAssignmentOperator())

Match #1:

foo.c:26:2: note: "root" binds here
   26 |         dstr = str;                  // Warning!
      |         ^~~~~~~~~~

Match #2:

foo.c:29:2: note: "root" binds here
   29 |         dstr = (dchar *)str;         // No warning
      |         ^~~~~~~~~~~~~~~~~~~
2 matches.

Then narrow it down to the <dchar *> = <char *> ones:

clang-query> let char qualType(isAnyCharacter(), unless(dchar))
clang-query> let charPtr pointsTo(char)
clang-query> match binaryOperator(isAssignmentOperator(), hasLHS(hasType(dcharPtr)), hasRHS(hasType(charPtr)))

Match #1:

foo.c:26:2: note: "root" binds here
   26 |         dstr = str;                  // Warning!
      |         ^~~~~~~~~~
1 match.

Now that we’ve figured out a query, we can write a custom clang-tidy check:

.clang-tidy

Checks: -*,custom-dchar-conversion

CustomChecks:
  - Name: dchar-conversion

    Query: |
      let dchar qualType(hasDeclaration(typedefDecl(hasName("dchar"))))
      let char qualType(isAnyCharacter(), unless(dchar))

      let dcharPtr pointsTo(dchar)
      let charPtr pointsTo(char)

      let bad expr(hasType(charPtr)).bind("bad")

      match binaryOperator(
        isAssignmentOperator(),
        hasLHS(hasType(dcharPtr)),
        hasRHS(bad),
      )

    Diagnostic:
      - BindName: bad
        Message: implicit conversion from 'char' to 'dchar'
        Level: Warning

and see our query turned into a nice warning:

$ clang-tidy --experimental-custom-checks foo.c -- -std=c23
1 warning generated.
foo.c:26:9: warning: implicit conversion from 'char' to 'dchar' [custom-dchar-conversion]
   26 |         dstr = str;                  // Warning!
      |                ^

The .bind("bad") and matching BindName: bad let us associate the warning with a subexpression of the overall match. You can have multiple Diagnostics with multiple BindNames if you want to highlight more than one location.


Now let’s try to handle function calls. We have a dchar ** parameter, so let’s extend the dcharPtr/charPtr matchers to find doubly indirect pointer types too:

clang-query> let dcharPtr anyOf(pointsTo(dchar), pointsTo(pointsTo(dchar)))
clang-query> let charPtr anyOf(pointsTo(char), pointsTo(pointsTo(char)))

We can use forEachArgumentWithParam to find calls where the argument has a char pointer type, but the parameter has a dchar pointer type:

clang-query> match callExpr(forEachArgumentWithParam(hasType(charPtr), parmVarDecl(hasType(dcharPtr))))

Match #1:

foo.c:24:2: note: "root" binds here
   24 |         dstrlen(str);                // Warning!
      |         ^~~~~~~~~~~~

Match #2:

foo.c:25:2: note: "root" binds here
   25 |         dstrcat(&str, "\nGoodbye!"); // Warning!
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #3:

foo.c:28:2: note: "root" binds here
   28 |         dstrlen((dchar *)str);       // No warning
      |         ^~~~~~~~~~~~~~~~~~~~~
3 matches.

Unfortunately, this gives a false positive. It turns out that forEachArgumentWithParam strips casts before matching expressions, so we don’t even see the (dchar *) cast that’s supposed to suppress the warning on line 28. I worked around it by binding the inner expression inside forEachArgumentWithParam, but matching the outer expression outside of it with hasAnyArgument.

I also had to extend bad to look through implicit casts, since Clang adds them when (for example) passing a char * argument to a const dchar * parameter. The implicit cast it generates is effectively (const dchar *)arg, not (const char *)arg, but we don’t want this implicit cast to suppress the warning.

All together, the custom check ends up looking like this:

.clang-tidy

Checks: -*,custom-dchar-conversion

CustomChecks:
  - Name: dchar-conversion

    Query: |
      let dchar qualType(hasDeclaration(typedefDecl(hasName("dchar"))))
      let char qualType(isAnyCharacter(), unless(dchar))

      let dcharPtr anyOf(
        pointsTo(dchar),
        pointsTo(pointsTo(dchar)),
      )

      let charPtr anyOf(
        pointsTo(char),
        pointsTo(pointsTo(char)),
      )

      let bad expr(
        anyOf(
          hasType(charPtr),
          implicitCastExpr(hasSourceExpression(hasType(charPtr))),
        )
      ).bind("bad")

      match callExpr(
        forEachArgumentWithParam(expr().bind("arg"), parmVarDecl(hasType(dcharPtr))),
        hasAnyArgument(expr(bad, ignoringParenCasts(equalsBoundNode("arg")))),
      )

      match returnStmt(
        hasReturnValue(bad),
        forFunction(functionDecl(returns(dcharPtr))),
      )

      match varDecl(hasType(dcharPtr), hasInitializer(bad))

      match binaryOperator(
        isAssignmentOperator(),
        hasLHS(hasType(dcharPtr)),
        hasRHS(bad),
      )

    Diagnostic:
      - BindName: bad
        Message: implicit conversion from 'char' to 'dchar'
        Level: Warning

And it finds all the cases we expect, and none of the ones we don’t:

$ clang-tidy --experimental-custom-checks foo.c -- -std=c23
3 warnings generated.
foo.c:24:10: warning: implicit conversion from 'char' to 'dchar' [custom-dchar-conversion]
   24 |         dstrlen(str);                // Warning!
      |                 ^
foo.c:25:10: warning: implicit conversion from 'char' to 'dchar' [custom-dchar-conversion]
   25 |         dstrcat(&str, "\nGoodbye!"); // Warning!
      |                 ^
foo.c:26:9: warning: implicit conversion from 'char' to 'dchar' [custom-dchar-conversion]
   26 |         dstr = str;                  // Warning!
      |                ^