Skip to main content

Symbol!

A type-level string, used as a field-name tag.

Overview​

In Context-Generic Programming (CGP), field names need to be types. Reading a field goes through HasField<Tag>, where Tag identifies which field is meant. So to look up a field called name, something has to stand in for the string "name" at the type level.

Symbol!("name") is that something. It produces a distinct type whose whole identity is the characters it encodes: two invocations with the same string are the same type, and two with different strings are different types.

HasField<Symbol!("name"), Value = String>

Encoding a string as a type lets field access take part in trait resolution. A context is the type the method runs on, and it supplies the values it needs as its own fields. It can carry a HasField<Symbol!("width")> impl and a HasField<Symbol!("height")> impl side by side, and the compiler picks the right one from the tag alone. Nothing is compared at runtime, because there is nothing at runtime: the tag exists only during compilation.

You rarely write it by hand. #[implicit] arguments, #[cgp_auto_getter], and #[derive(HasField)] all generate the tag from a name you already wrote. It shows up explicitly in a wiring entry that names a field, such as UseField<Symbol!("first_name")>, and it shows up unavoidably in compiler errors, which is the main reason to be able to read it.

Usage​

The macro takes a single string literal and is used wherever a type is expected: in trait bounds, in associated-type positions, and inside a PhantomData tag:

Symbol!("name")
Symbol!("first_name")
Symbol!("")

Any string literal is accepted, including the empty string and multi-byte Unicode (Symbol!("世界")). A raw string or an escape spells the characters it denotes, so Symbol!(r"raw") is the same type as Symbol!("raw"). Anything else fails: a byte string or an identifier with expected string literal, and a second token after the literal with unexpected token. Most often the macro appears inside a field bound:

Self: HasField<Symbol!("name"), Value = String>

The tag for a tuple field​

A tuple-struct field has no name, so it cannot be keyed by a string. #[derive(HasField)] tags those with Index instead (Index<0>, Index<1>), which encodes a number at the type level the way Symbol! encodes a string. A field is keyed by Symbol! when it has a name and by Index when it has only a position.

Raw identifiers​

A field written as a raw identifier is tagged by its logical name, with the r# stripped: a field r#type is tagged Symbol!("type"). The macro itself performs no stripping. It takes the literal verbatim, so Symbol!("type") is the tag that matches, and Symbol!("r#type") would be a different tag matching nothing.

Examples​

The everyday appearance is a wiring entry that points a getter at a particular field. Person is a value context here, the type whose own field the getter reads:

use cgp::core::field::impls::UseField;
use cgp::prelude::*;

#[cgp_getter]
pub trait HasName {
fn name(&self) -> &str;
}

#[derive(HasField)]
pub struct Person {
pub first_name: String,
}

delegate_components! {
Person {
NameGetterComponent: UseField<Symbol!("first_name")>,
}
}

check_components! {
Person {
NameGetterComponent,
}
}

Symbol!("first_name") tells UseField which field to read. This is the one place a reader routinely writes the macro themselves.

It also appears in a hand-written field bound, the shape the ergonomic constructs generate for you:

#[cgp_impl(new GreetHello)]
impl Greeter
where
Self: HasField<Symbol!("name"), Value = String>,
{
fn greet(&self) {
println!("Hello, {}!", self.get_field(PhantomData::<Symbol!("name")>));
}
}

Written idiomatically that provider would use an #[implicit] argument and no Symbol! would be visible at all. That is the point of the ergonomic surface, and why this form is worth recognizing rather than writing.

A type-level string can also be turned back into a runtime string, which is occasionally useful for diagnostics:

let s = <Symbol!("hello")>::default();
assert_eq!(s.to_string(), "hello");

The same text is available as a constant through StaticString, imported from cgp::core::field::traits: <Symbol!("hello") as StaticString>::VALUE is "hello". That trait is the reason the expansion records a length, as Under the hood explains.

When to use it​

Write Symbol! when a wiring entry has to name a field, and let the macros produce it everywhere else. That is the honest summary: the construct is essential and mostly generated.

  • Use an #[implicit] argument to read a field. The parameter's name becomes the tag, so you never type one.
  • Use #[cgp_auto_getter] for a named accessor. The method name becomes the tag.
  • Write Symbol! explicitly with UseField, where the reason for it is that the field name is a wiring decision rather than fixed to a method name. This is its main hand-written use.
  • Use Index for a tuple field, not a Symbol! of "0". They are different types and the derive generates the former.

A couple of things it is not. It is not a runtime string: there is no &str inside it, and the Display impl above reconstructs the text from the type rather than reading a stored value. And it is not a general type-level string facility to build programs out of; it exists to key field and variant lookups, and the StaticFormat traits recover text from one when that is needed.

Under the hood​

Symbol!("...") expands to a Symbol type wrapping a Chars chain that spells the string one character at a time:

// before
Symbol!("abc")

// after
Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>

Two type constructors do the work. Chars<const CHAR: char, Tail> is one character paired with the rest of the string; chained through its tail and terminated by Nil, it forms a type-level list of characters, the same shape as Product!'s Cons/Nil list, specialized so the head is a const char rather than a type. Symbol<const LEN: usize, Chars> then wraps that list together with a length.

The LEN parameter is the part most likely to surprise, and it exists to work around a limit in stable Rust: the length of a Chars chain cannot be computed inside a const-generic context, so the macro precomputes it and bakes it in. The value is the string's byte length, not its character count:

Symbol!("abc") // Symbol<3, Chars<'a', ...>> — 3 bytes, 3 chars
Symbol!("世界你好") // Symbol<12, Chars<'世', ...>> — 12 bytes, 4 chars

The character list has one Chars node per Unicode scalar value, so those two numbers disagree for any non-ASCII string. LEN is there so length-dependent code can read the size off the type instead of recursing through the list. StaticString is that code: it decodes the characters into a [u8; LEN] buffer at compile time, and an array's size must be a constant.

The expansion is built by folding the characters right to left onto Nil and wrapping the result, so the empty string Symbol!("") becomes Symbol<0, Nil>.

What this means for reading errors is the practical benefit. A missing field on a context is reported against the expanded tag, so an error mentioning HasField<Symbol<5, Chars<'w', Chars<'i', ...>>>> is telling you the field width is missing. Reading the characters in order is enough to decode it, and cargo cgp check names the field directly, as missing field `width` . cargo cgp check leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class.

Formal grammar​

The input is a single string literal, in the Rust Reference's notation:

SymbolInput -> STRING_LITERAL

STRING_LITERAL is the Rust string-literal token, so any string literal is accepted, raw strings included, while a byte string or a C string is not. The macro is used in type position, and this single literal is the whole of its input: a token after it fails with unexpected token.

Common Mistakes​

The LEN in an expanded Symbol is bytes, not characters. For ASCII the two coincide, which is why the distinction only shows up on non-ASCII field names, where the number will not match the visible character count and the Chars chain will be shorter than LEN.

A raw-identifier field is tagged without the r#. Symbol!("r#type") and Symbol!("type") are different types, and the derive generates the second, so the first matches nothing.

Two spellings of the same field are different tags. Symbol!("first_name") and Symbol!("firstName") are unrelated types, and a mismatch reports as a missing HasField bound rather than as a typo. This is the usual cause of a getter that "should" work.

It is a type, so it goes in type position. Writing Symbol!("name") where a value is expected fails with errors that do not mention the macro, because the expanded Symbol<4, Chars<…>> parses as a chain of comparisons:

error: macro expansion ignores `,` and any tokens following

followed by an E0369 and an E0308 about < and struct constructors. The PhantomData::<Symbol!("name")> form is how the tag is passed to get_field, and the tag is the type argument rather than the value.

  • Index — the position-keyed tag for tuple-struct fields.
  • HasField — what a tag is looked up through.
  • #[derive(HasField)] — generates one tag per named field.
  • #[implicit] — generates the tag from an argument name.
  • #[cgp_auto_getter] — generates it from a method name.
  • UseField — where the tag is written by hand, as a wiring decision.
  • Type-level lists — the Chars/Nil chain the expansion builds.
  • Product! and Sum! — the record and variant lists whose entries carry these tags.
  • StaticFormat — recovering runtime text from a type-level string.

The ideas behind it:

Source​


An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.