refix-codegen 0.8.0

Code generator for typed FIX protocol messages, for the ReFIX engine
Documentation
use refix_dictionary::dictionary;
use refix_dictionary::spec::{EnumValue, Field};

use crate::groups::instance_context;
use crate::naming::{
    field_base_name, group_accessor_base_name, group_source_name, module_base_name,
};
use crate::rust::Error;
use crate::{pascal_case, snake_case};

pub(super) fn method_name(field: &Field) -> Result<String, Error> {
    identifier(field_base_name(field)).ok_or_else(|| Error::UnrepresentableName {
        field: field.name.clone(),
    })
}

/// The type of a group's instances.
///
/// It is the component the group makes up. A group without one takes the
/// name of `owner`, the type it is declared in, followed by its own.
pub(super) fn group_type_name(group: dictionary::Group<'_>, owner: &str) -> Result<String, Error> {
    let name = match group.component() {
        Some(component) => component.to_owned(),
        None => format!("{owner}{}", group_source_name(group)),
    };
    if name == "Self" {
        return Err(Error::UnrepresentableGroupName {
            context: instance_context(group),
        });
    }
    Ok(name)
}

/// The accessor of a group, escaped for Rust.
pub(super) fn group_accessor_name(group: dictionary::Group<'_>) -> Result<String, Error> {
    group_identifier(group_accessor_base_name(group), group)
}

fn group_identifier(name: String, group: dictionary::Group<'_>) -> Result<String, Error> {
    identifier(name).ok_or_else(|| Error::UnrepresentableGroupName {
        context: group.declared_in().group(&group.count_field().name),
    })
}

pub(super) fn variant_name(field: &Field, value: &EnumValue) -> Result<String, Error> {
    let mut name = pascal_case(&value.description);

    // A name cannot start with a digit, so `5YR` becomes `N5yr`.
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        name.insert(0, 'N');
    }

    let starts_with_letter = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic());
    let alphanumeric = name.chars().all(|c| c.is_ascii_alphanumeric());
    if !starts_with_letter || !alphanumeric || name == "Self" {
        return Err(Error::UnrepresentableValue {
            field: field.name.clone(),
            description: value.description.clone(),
        });
    }
    Ok(name)
}

/// Numbers a variant an earlier value of its field is named like, so the
/// second `Euribor` becomes `Euribor2`.
pub(super) fn numbered_variant(name: &str, number: u32) -> String {
    format!("{name}{number}")
}

/// The accessor of a component's view, escaped for Rust.
pub(super) fn component_accessor_name(component: &str) -> Result<String, Error> {
    identifier(snake_case(component)).ok_or_else(|| Error::UnrepresentableComponentName {
        component: component.to_owned(),
    })
}

/// The module holding the type named `type_name`.
///
/// A keyword takes a trailing underscore, so the file is named as the
/// module is.
pub(super) fn module_name(type_name: &str) -> String {
    let name = module_base_name(type_name);
    if RESERVED_WORDS.contains(&name.as_str()) || UNESCAPABLE.contains(&name.as_str()) {
        return format!("{name}_");
    }
    name
}

/// Escapes a keyword as a raw identifier, or `None` for a keyword that
/// cannot be escaped.
fn identifier(name: String) -> Option<String> {
    if UNESCAPABLE.contains(&name.as_str()) {
        return None;
    }
    if RESERVED_WORDS.contains(&name.as_str()) {
        return Some(format!("r#{name}"));
    }
    Some(name)
}

/// The keywords that cannot be raw identifiers.
const UNESCAPABLE: &[&str] = &["self", "super", "crate"];

/// Rust's strict and reserved keywords.
const RESERVED_WORDS: &[&str] = &[
    "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn",
    "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let",
    "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return",
    "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use",
    "virtual", "where", "while", "yield",
];

#[cfg(test)]
mod tests {
    use super::{
        component_accessor_name, group_accessor_name, group_type_name, method_name, module_name,
        variant_name,
    };
    use crate::rust::Error;
    use crate::test_utils::with_group;
    use refix_dictionary::spec::{DataType, EnumValue, Field};
    use refix_dictionary::{MemberContext, Tag};

    fn field(name: &str, tag: u32, data_type: DataType) -> Field {
        Field {
            name: name.to_owned(),
            tag: Tag(tag),
            data_type,
            length_tag: None,
            values: vec![],
        }
    }

    fn variant_of(description: &str) -> Result<String, Error> {
        let value = EnumValue {
            value: "1".to_owned(),
            description: description.to_owned(),
        };
        variant_name(&field("OrdType", 40, DataType::Char), &value)
    }

    fn type_named(component: Option<&str>, count_field: &str) -> Result<String, Error> {
        with_group(component, count_field, |group| {
            group_type_name(group, "NewOrderSingle")
        })
    }

    fn accessor_named(component: Option<&str>, count_field: &str) -> Result<String, Error> {
        with_group(component, count_field, group_accessor_name)
    }

    #[test]
    fn module_names_are_snake_case() {
        assert_eq!(module_name("NewOrderSingle"), "new_order_single");
        assert_eq!(module_name("XMLnonFIX"), "xml_non_fix");
    }

    #[test]
    fn keyword_module_names_take_a_trailing_underscore() {
        assert_eq!(module_name("Yield"), "yield_");
        assert_eq!(module_name("Super"), "super_");
    }

    #[test]
    fn keyword_method_names_are_escaped() {
        let name = method_name(&field("Yield", 236, DataType::String));
        assert_eq!(name.unwrap(), "r#yield");
    }

    #[test]
    fn suffixed_raw_names_are_not_escaped() {
        let name = method_name(&field("Yield", 236, DataType::Other("PRICE".to_owned())));
        assert_eq!(name.unwrap(), "yield_raw");
    }

    #[test]
    fn an_unescapable_name_is_an_error() {
        assert_eq!(
            method_name(&field("Self", 9000, DataType::String)).unwrap_err(),
            Error::UnrepresentableName {
                field: "Self".to_owned(),
            }
        );
    }

    #[test]
    fn a_suffix_makes_an_unescapable_name_legal() {
        let name = method_name(&field("Self", 9000, DataType::Other("DATA".to_owned())));
        assert_eq!(name.unwrap(), "self_raw");
    }

    #[test]
    fn a_group_type_takes_the_name_of_its_component() {
        let name = type_named(Some("Parties"), "NoPartyIDs");
        assert_eq!(name.unwrap(), "Parties");
    }

    #[test]
    fn a_group_type_without_a_component_follows_its_owner() {
        let name = type_named(None, "NoMsgTypes");
        assert_eq!(name.unwrap(), "NewOrderSingleMsgTypes");
    }

    #[test]
    fn a_group_type_named_self_is_an_error() {
        assert_eq!(
            type_named(Some("Self"), "NoPartyIDs").unwrap_err(),
            Error::UnrepresentableGroupName {
                context: MemberContext::Component("Self".to_owned()).group("NoPartyIDs"),
            }
        );
    }

    #[test]
    fn keyword_group_accessor_names_are_escaped() {
        let name = accessor_named(Some("Types"), "NoType");
        assert_eq!(name.unwrap(), "r#type");
    }

    #[test]
    fn an_unescapable_group_accessor_name_is_an_error() {
        assert_eq!(
            accessor_named(None, "NoSelf").unwrap_err(),
            Error::UnrepresentableGroupName {
                context: MemberContext::Message("NewOrderSingle".to_owned()).group("NoSelf"),
            }
        );
    }

    #[test]
    fn component_accessor_names_are_snake_case() {
        assert_eq!(
            component_accessor_name("OrderQtyData").unwrap(),
            "order_qty_data"
        );
        assert_eq!(component_accessor_name("Yield").unwrap(), "r#yield");
    }

    #[test]
    fn an_unescapable_component_accessor_name_is_an_error() {
        assert_eq!(
            component_accessor_name("Self"),
            Err(Error::UnrepresentableComponentName {
                component: "Self".to_owned()
            })
        );
    }

    #[test]
    fn converts_a_description_to_pascal_case() {
        assert_eq!(variant_of("GOOD_TILL_CANCEL").unwrap(), "GoodTillCancel");
    }

    #[test]
    fn a_digit_leading_description_takes_a_prefix() {
        assert_eq!(variant_of("5YR").unwrap(), "N5yr");
        assert_eq!(variant_of("5_YR").unwrap(), "N5Yr");
        assert_eq!(variant_of("401K").unwrap(), "N401k");
        assert_eq!(variant_of("3").unwrap(), "N3");
    }

    #[test]
    fn leading_underscores_are_dropped_before_the_prefix() {
        assert_eq!(
            variant_of("_5_DAY_MOVING_AVERAGE").unwrap(),
            "N5DayMovingAverage"
        );
    }

    #[test]
    fn an_empty_description_is_an_error() {
        assert!(variant_of("").is_err());
    }

    #[test]
    fn punctuation_in_a_description_is_an_error() {
        assert_eq!(
            variant_of("W/AVG").unwrap_err(),
            Error::UnrepresentableValue {
                field: "OrdType".to_owned(),
                description: "W/AVG".to_owned(),
            }
        );
    }

    #[test]
    fn a_prefixed_name_still_passes_the_gate() {
        assert!(variant_of("5/YR").is_err());
    }

    #[test]
    fn a_non_ascii_description_is_an_error() {
        assert!(variant_of("CAF\u{c9}").is_err());
    }

    #[test]
    fn self_is_an_error() {
        assert!(variant_of("SELF").is_err());
    }

    #[test]
    fn a_description_containing_self_is_fine() {
        assert_eq!(variant_of("SELF_TRADE").unwrap(), "SelfTrade");
    }

    #[test]
    fn capitalized_keywords_are_fine() {
        assert_eq!(variant_of("TRUE").unwrap(), "True");
        assert_eq!(variant_of("SUPER").unwrap(), "Super");
    }
}