diff --git a/src/format/formulas.rs b/src/format/formulas.rs index 0eef0da..81ef924 100644 --- a/src/format/formulas.rs +++ b/src/format/formulas.rs @@ -153,15 +153,74 @@ impl<'formula> std::fmt::Debug for FormulaDisplay<'formula> }, crate::Formula::Implies(crate::Implies{direction, antecedent, implication}) => { + let antecedent_requires_parentheses = match **antecedent + { + // Implication is right-associative and thus requires parentheses when nested on + // the antecedent side + crate::Formula::Implies(_) => true, + _ => false, + }; + + let implication_requires_parentheses = match **antecedent + { + // Implication is right-associative and thus doesn’t require parentheses when + // nested on the implication side with the same implication direction + crate::Formula::Implies(crate::Implies{direction: nested_direction, ..}) + if nested_direction == *direction => false, + // If the nested implication is in the other direction, parentheses are needed + crate::Formula::Implies(_) => true, + _ => false, + }; + + let format_antecedent = |format: &mut std::fmt::Formatter| -> Result<_, _> + { + if antecedent_requires_parentheses + { + write!(format, "(")?; + } + + write!(format, "{:?}", display_formula(antecedent, precedence))?; + + if antecedent_requires_parentheses + { + write!(format, ")")?; + } + + Ok(()) + }; + + let format_implication = |format: &mut std::fmt::Formatter| -> Result<_, _> + { + if implication_requires_parentheses + { + write!(format, "(")?; + } + + write!(format, "{:?}", display_formula(implication, precedence))?; + + if implication_requires_parentheses + { + write!(format, ")")?; + } + + Ok(()) + }; + match direction { crate::ImplicationDirection::LeftToRight => - write!(format, "{:?} -> {:?}", display_formula(antecedent, precedence), - display_formula(implication, precedence))?, + { + format_antecedent(format)?; + write!(format, " -> ")?; + format_implication(format)?; + }, crate::ImplicationDirection::RightToLeft => - write!(format, "{:?} <- {:?}", display_formula(implication, precedence), - display_formula(antecedent, precedence))?, - }; + { + format_implication(format)?; + write!(format, " <- ")?; + format_antecedent(format)?; + }, + } }, crate::Formula::IfAndOnlyIf(arguments) => {