ddn.util.ident

ddn.util.ident — identifier mapping for the DDN code generators.

One implementation of the CODE_STYLE.md identifier rules, shared by the three generators that need them: ddn-x xgen (names.d), ddn-wl wlscan (emit) and the bindings post-processing (keyword escapes only, C enum names are kept there). Everything is CTFE-able, so a generator's name mapping can be pinned in static asserts.

The rules:

  • Types are PascalCase (toPascalCase).
  • Enum items are UPPER_SNAKE (toUpperSnake).
  • A name that starts with a digit gets a caller-chosen prefix

    (prefixDigit); nothing is a valid D identifier otherwise.

  • A name that collides with a D keyword gets a trailing

    underscore (escapeKeyword).

  • Module names are lowercase snake case (toModuleName).

Word splitting, shared by the three conversions: _, `-`, `.` and space separate words (dropped); within a chunk, a word starts at every uppercase letter that follows a lowercase letter or is followed by a lowercase letter (so KeyPress splits Key/Press and HTTPServer splits HTTP/Server, while CHAR2B stays one word). Each word is capitalised as a whole — its first letter up, the rest down — which is why CHAR2B becomes Char2b and not Char2B.

Example:

import ddn.util.ident;

static assert(toPascalCase("CHAR2B") == "Char2b");
static assert(toPascalCase("wl_surface") == "WlSurface");
static assert(toUpperSnake("KeyPress") == "KEY_PRESS");
static assert(escapeKeyword("in") == "in_");
static assert(toModuleName("CHAR2B") == "char2b");

Functions 8

fnstring toPascalCase(string name) @safe pure nothrowConverts a name to PascalCase (the type-name form).
fnstring toUpperSnake(string name) @safe pure nothrowConverts a name to `UPPER_SNAKE` (the enum-item form).
fnstring toSnakeCase(string name) @safe pure nothrowConverts a name to lowercase snake case.
fnbool isDKeyword(string name) @safe pure nothrow @nogcReports whether `name` is a D keyword (or one of the special `__`-tokens that may not be used as identifiers).
fnstring escapeKeyword(string name) @safe pure nothrowResolves a D keyword collision by appending an underscore.
fnstring prefixDigit(string name, string prefix) @safe pure nothrowPrefixes `name` with `prefix` when it would otherwise start with a digit (no D identifier can).
fnbool isValidIdentifier(string name) @safe pure nothrow @nogcReports whether `name` is a valid D identifier: non-empty, ASCII letters/digits/underscores, not starting with a digit, and not a keyword.
fnstring toModuleName(string name) @safe pure nothrowConverts a name to a module name: lowercase snake case, prefixed when digit-leading, keyword-escaped.