generate_enum_info!() { /* proc-macro */ }
Expand description
A procedural macro to generate JSON information about an enum, including its name, variant names, and descriptions, along with a total token count.
This macro leverages the EnumDescriptor
and VariantDescriptors
traits to extract
details about an enum. It compiles these details into a JSON format and calculates
an associated token count based on the structure of the generated JSON. The token count
is an estimation of how many tokens are needed to represent the enum information in a
serialized format, considering the syntax and spacing of JSON.
The macro returns a tuple containing the generated JSON object and the estimated total token count.
§Usage
When applied to an enum, the macro generates code similar to the following example:
{
use serde_json::Value;
let mut token_count = 0;
// Description and token count for the enum's argument (if applicable)
let (arg_desc, arg_tokens) = <MyEnum as EnumDescriptor>::arg_description_with_token_count();
token_count += 6; // Base tokens for argument declaration
token_count += arg_tokens; // Tokens for the argument description
// Enum name and its token count
let enum_name = <MyEnum as EnumDescriptor>::name_with_token_count();
token_count += 6; // Base tokens for enum name declaration
token_count += enum_name.1; // Tokens for the enum name
// Base tokens for enum and type declarations
token_count += 7; // Enum declaration
token_count += 7; // Type declaration
// Variant names and their token counts
let enum_variants = <MyEnum as VariantDescriptors>::variant_names_with_token_counts();
// Adding 3 tokens for each variant for proper JSON formatting
token_count += enum_variants.iter().map(|(_, token_count_i)| *token_count_i + 3).sum::<usize>();
// Constructing the JSON object with enum details
let json_enum = serde_json::json!({
enum_name.0: {
"type": "string",
"enum": enum_variants.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
"description": arg_desc,
}
});
(json_enum, token_count)
}
§Token Count Estimation Details
The estimation of tokens for the generated JSON includes:
- Base tokens for argument and enum declarations: A fixed count to account for the JSON structure around the enum and its arguments.
- Dynamic tokens for the enum name and argument descriptions: Calculated based on the length and structure of the enum name and argument descriptions.
- Tokens for each enum variant: Includes a fixed addition for JSON formatting alongside the variant names.
This approach ensures a precise estimation of the token count required to represent the enum information in JSON, facilitating accurate serialization.
Note: The enum must implement the EnumDescriptor
and VariantDescriptors
traits for the macro to function correctly. The actual token count is computed at compile time using these traits’ methods.