//! AST manipulation utilities for MessageFormat elements //! //! This module provides utilities for transforming and analyzing MessageFormat ASTs: //! - **Hoisting**: Moving plural/select elements to the top level to create complete sentences //! - **Variable collection**: Extracting all variables and their types from an AST //! - **Structural comparison**: Checking if two ASTs have the same variable structure use crate::types::*; use indexmap::IndexMap; use std::fmt; /// Error type for AST manipulation operations. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ManipulatorError { /// A plural or select element was found nested within a tag element. /// Tag elements should be placed inside each plural/select option instead. PluralOrSelectInTag, /// A variable was used with conflicting types in the same message. ConflictingVariableType { /// The name of the variable with conflicting types variable: String, /// The first type encountered expected: Type, /// The conflicting type found: Type, }, } impl fmt::Display for ManipulatorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ManipulatorError::PluralOrSelectInTag => { write!( f, "Cannot hoist plural/select within a tag element. \ Please put the tag element inside each plural/select option" ) } ManipulatorError::ConflictingVariableType { variable, expected, found, } => { write!( f, "Variable '{}' has conflicting types: {:?} vs {:?}", variable, expected, found ) } } } } impl std::error::Error for ManipulatorError {} /// Result type for structural comparison operations. pub type StructuralComparisonResult = Result<(), StructuralComparisonError>; /// Error indicating why two ASTs are not structurally the same. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StructuralComparisonError { /// The two ASTs have different numbers of variables DifferentVariableCount { /// Variables in the first AST a_vars: Vec, /// Variables in the second AST b_vars: Vec, /// Optional context (e.g., message ID or source/target locales) context: Option, }, /// A variable is missing in one of the ASTs MissingVariable { /// The name of the missing variable variable: String, /// The type of the missing variable var_type: Type, /// Optional context (e.g., message ID or source/target locales) context: Option, }, } impl fmt::Display for StructuralComparisonError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { StructuralComparisonError::DifferentVariableCount { a_vars, b_vars, context, } => { if let Some(ctx) = context { write!( f, "[{}] Different number of variables: [{}] vs [{}]", ctx, a_vars.join(", "), b_vars.join(", ") ) } else { write!( f, "Different number of variables: [{}] vs [{}]", a_vars.join(", "), b_vars.join(", ") ) } } StructuralComparisonError::MissingVariable { variable, var_type, context, } => { if let Some(ctx) = context { write!( f, "[{}] Missing variable '{}' of type {:?} in message", ctx, variable, var_type ) } else { write!( f, "Missing variable '{}' of type {:?} in message", variable, var_type ) } } } } } impl std::error::Error for StructuralComparisonError {} /// Checks if an element is a plural or select element. /// /// # Arguments /// /// * `el` - The element to check /// /// # Returns /// /// `true` if the element is a plural or select, `false` otherwise #[inline] fn is_plural_or_select_element(el: &MessageFormatElement) -> bool { matches!( el, MessageFormatElement::Plural(_) | MessageFormatElement::Select(_) ) } /// Replaces pound elements with number elements referencing the given variable. /// /// This is needed when nesting plurals - the # in the outer plural should become /// an explicit variable reference when nested inside another plural. /// /// GH #4202 /// /// # Arguments /// /// * `ast` - The AST to transform /// * `variable_name` - The variable name to use in place of # /// /// # Returns /// /// A new AST with pound elements replaced by number elements fn replace_pound_with_argument( ast: &[MessageFormatElement], variable_name: &str, ) -> Vec { ast.iter() .map(|el| match el { MessageFormatElement::Pound(pound) => { // Replace # with {variableName, number} MessageFormatElement::Number(NumberElement { value: variable_name.to_string(), style: None, location: pound.location.clone(), }) } MessageFormatElement::Tag(tag) => { let children = replace_pound_with_argument(&tag.children, variable_name); MessageFormatElement::Tag(TagElement { value: tag.value.clone(), children, location: tag.location.clone(), }) } _ => el.clone(), }) .collect() } /// Recursively searches for a plural or select element in an AST. /// /// This checks if the AST contains any plural or select elements, /// including those nested inside tag elements. /// /// # Arguments /// /// * `ast` - The AST to search /// /// # Returns /// /// `true` if a plural or select element is found, `false` otherwise fn find_plural_or_select_element(ast: &[MessageFormatElement]) -> bool { ast.iter().any(|el| match el { MessageFormatElement::Plural(_) | MessageFormatElement::Select(_) => true, MessageFormatElement::Tag(tag) => find_plural_or_select_element(&tag.children), _ => false, }) } /// Hoists a plural or select element to the top level of the AST. /// /// This transformation takes a plural/select element that appears in the middle /// of a message and moves it to the outermost level, distributing the surrounding /// text into each option. This creates complete sentences in each option, which /// is more translator-friendly. /// /// # Example /// /// Before: `["I have ", {count, plural, one{a dog} other{many dogs}}]` /// After: `[{count, plural, one{I have a dog} other{I have many dogs}}]` /// /// # Arguments /// /// * `ast` - The full AST containing the element /// * `el` - The plural or select element to hoist (must be Plural or Select variant) /// * `position` - The index of the element in the AST /// /// # Returns /// /// A new plural or select element with the surrounding AST distributed into each option fn has_pound(ast: &[MessageFormatElement]) -> bool { ast.iter().any(|el| match el { MessageFormatElement::Pound(_) => true, MessageFormatElement::Tag(tag) => has_pound(&tag.children), _ => false, }) } fn hoist_element( ast: &[MessageFormatElement], el: &MessageFormatElement, position: usize, parent_plural: Option<&PluralElement>, ) -> Result { let rebind = |elements: &[MessageFormatElement]| match parent_plural { Some(parent) => replace_pound_with_argument(elements, &parent.value), None => elements.to_vec(), }; let before = rebind(&ast[..position]); let after = rebind(&ast[position + 1..]); let scope = match el { MessageFormatElement::Plural(plural) => Some(plural), _ => None, }; let mut cloned = el.clone(); let options: Vec<&mut PluralOrSelectOption> = match &mut cloned { MessageFormatElement::Plural(plural) => plural.options.values_mut().collect(), MessageFormatElement::Select(select) => select.options.values_mut().collect(), _ => unreachable!("Only plural or select elements can be hoisted"), }; for option in options { let mut value = Vec::with_capacity(before.len() + option.value.len() + after.len()); value.extend_from_slice(&before); value.extend_from_slice(&option.value); value.extend_from_slice(&after); option.value = hoist_selectors_in_context(value, scope)?; } Ok(cloned) } /// Internal implementation of `hoist_selectors` that returns a Result. fn hoist_selectors_impl( ast: Vec, ) -> Result, ManipulatorError> { hoist_selectors_in_context(ast, None) } fn hoist_selectors_in_context( ast: Vec, parent_plural: Option<&PluralElement>, ) -> Result, ManipulatorError> { for el in &ast { if matches!(el, MessageFormatElement::Tag(_)) && find_plural_or_select_element(std::slice::from_ref(el)) { return Err(ManipulatorError::PluralOrSelectInTag); } } for (i, el) in ast.iter().enumerate() { if !is_plural_or_select_element(el) { continue; } if parent_plural.is_some_and(|parent| parent.offset != 0) && (has_pound(&ast[..i]) || has_pound(&ast[i + 1..])) { // Offset pounds need their original plural scope; ICU has no subtraction argument. return ast .iter() .map(|node| { if is_plural_or_select_element(node) { hoist_element(std::slice::from_ref(node), node, 0, None) } else { Ok(node.clone()) } }) .collect(); } return Ok(vec![hoist_element(&ast, el, i, parent_plural)?]); } Ok(ast) } /// Hoists all plural and select elements to the beginning of the AST. /// /// This transformation flattens the AST by moving plural/select elements to the top level /// and distributing surrounding text into each option. This creates complete sentences /// in each option, which is more translator-friendly than fragmented sentences. /// /// If there are multiple selectors, the order of which one is hoisted first is /// based on their position in the AST (left-to-right). /// /// # Example /// /// Input: `"I have {count, plural, one{a dog} other{many dogs}}"` /// Output: `"{count, plural, one{I have a dog} other{I have many dogs}}"` /// /// # Arguments /// /// * `ast` - The AST to transform /// /// # Returns /// /// A new AST with selectors hoisted /// /// # Panics /// /// Panics if a plural/select element is found within a tag element. /// This maintains compatibility with the TypeScript implementation. pub fn hoist_selectors(ast: Vec) -> Vec { hoist_selectors_impl(ast).unwrap_or_else(|e| panic!("{}", e)) } /// Tries to hoist all plural and select elements to the beginning of the AST. /// /// This is the same as `hoist_selectors` but returns a Result instead of panicking. /// /// # Arguments /// /// * `ast` - The AST to transform /// /// # Returns /// /// A Result containing the new AST with selectors hoisted, or an error if hoisting fails. /// /// # Errors /// /// Returns an error if a plural/select element is found within a tag element. pub fn try_hoist_selectors( ast: Vec, ) -> Result, ManipulatorError> { hoist_selectors_impl(ast) } /// Collects all variables and their types from an AST. /// /// This recursively walks the AST and builds a map of variable names to their types. /// Variables can come from: /// - Argument elements: `{name}` /// - Number elements: `{count, number}` /// - Date elements: `{today, date}` /// - Time elements: `{now, time}` /// - Plural elements: `{count, plural, ...}` /// - Select elements: `{gender, select, ...}` /// - Tag elements: `text` /// /// # Arguments /// /// * `ast` - The AST to collect variables from /// * `vars` - The map to populate with variables (modified in place) /// /// # Errors /// /// Returns an error if the same variable name is used with conflicting types /// (e.g., `{x, number}` and `{x, date}` in the same message). /// A variable may use both date and time formats. fn collect_variables( ast: &[MessageFormatElement], vars: &mut IndexMap>, ) -> Result<(), ManipulatorError> { for el in ast { match el { MessageFormatElement::Argument(arg) => { insert_variable(vars, &arg.value, Type::Argument)?; } MessageFormatElement::Number(num) => { insert_variable(vars, &num.value, Type::Number)?; } MessageFormatElement::Date(date) => { insert_variable(vars, &date.value, Type::Date)?; } MessageFormatElement::Time(time) => { insert_variable(vars, &time.value, Type::Time)?; } MessageFormatElement::Plural(plural) => { vars.insert(plural.value.clone(), vec![Type::Plural]); // Recursively collect from each plural option for option in plural.options.values() { collect_variables(&option.value, vars)?; } } MessageFormatElement::Select(select) => { vars.insert(select.value.clone(), vec![Type::Select]); // Recursively collect from each select option for option in select.options.values() { collect_variables(&option.value, vars)?; } } MessageFormatElement::Tag(tag) => { vars.insert(tag.value.clone(), vec![Type::Tag]); // Recursively collect from tag children collect_variables(&tag.children, vars)?; } // Literal and Pound elements don't contain variables MessageFormatElement::Literal(_) | MessageFormatElement::Pound(_) => {} } } Ok(()) } fn insert_variable( vars: &mut IndexMap>, variable: &str, var_type: Type, ) -> Result<(), ManipulatorError> { if let Some(existing_types) = vars.get_mut(variable) { if existing_types.contains(&var_type) || existing_types.contains(&Type::Plural) || existing_types.contains(&Type::Select) { return Ok(()); } if matches!(var_type, Type::Date | Type::Time) && existing_types .iter() .all(|t| matches!(t, Type::Date | Type::Time)) { existing_types.push(var_type); } else { return Err(ManipulatorError::ConflictingVariableType { variable: variable.to_string(), expected: existing_types[0], found: var_type, }); } } else { vars.insert(variable.to_string(), vec![var_type]); } Ok(()) } /// Checks if two ASTs are structurally the same. /// /// Two ASTs are considered structurally the same if they have the same set of /// variables with the same types. This is useful for validating that translations /// maintain the same variable structure as the source message. /// /// The actual text content and order of elements doesn't matter - only that the /// same variables are present with matching types. /// Shared date/time variables must retain both roles, in any order. /// /// # Example /// /// These are structurally the same: /// - English: "Hello {name}, you have {count, number} messages" /// - Spanish: "Hola {name}, tienes {count, number} mensajes" /// /// These are NOT structurally the same: /// - English: "Hello {name}" /// - Spanish: "Hola {username}" (different variable name) /// /// # Arguments /// /// * `a` - The first AST to compare /// * `b` - The second AST to compare /// * `context` - Context string (e.g., message ID or "en vs es") to include in error messages /// /// # Returns /// /// `Ok(())` if the ASTs are structurally the same. /// `Err(StructuralComparisonError)` if they differ, with details including context. /// /// # Example /// /// ``` /// use formatjs_icu_messageformat_parser::{Parser, ParserOptions, is_structurally_same}; /// /// let source = "Hello {name}!"; /// let target = "Hola {name}!"; /// /// let parser_options = ParserOptions::default(); /// let source_ast = Parser::new(source, parser_options.clone()).parse().unwrap(); /// let target_ast = Parser::new(target, parser_options).parse().unwrap(); /// /// // Check with message ID context for better error messages /// let result = is_structurally_same(&source_ast, &target_ast, "app.greeting".to_string()); /// assert!(result.is_ok()); /// ``` pub fn is_structurally_same( a: &[MessageFormatElement], b: &[MessageFormatElement], context: String, ) -> StructuralComparisonResult { let mut a_vars = IndexMap::new(); let mut b_vars = IndexMap::new(); // Panic on conflicting variable types within a single message // (maintains compatibility with TypeScript implementation) collect_variables(a, &mut a_vars).unwrap_or_else(|e| panic!("{}", e)); collect_variables(b, &mut b_vars).unwrap_or_else(|e| panic!("{}", e)); // Check if they have the same number of variables if a_vars.len() != b_vars.len() { return Err(StructuralComparisonError::DifferentVariableCount { a_vars: a_vars.keys().cloned().collect(), b_vars: b_vars.keys().cloned().collect(), context: Some(context), }); } // Check if all variables match with the same types for (key, a_types) in &a_vars { if !b_vars.get(key).is_some_and(|b_types| { a_types.len() == b_types.len() && a_types.iter().all(|t| b_types.contains(t)) }) { return Err(StructuralComparisonError::MissingVariable { variable: key.clone(), var_type: a_types[0], context: Some(context.clone()), }); } } Ok(()) }