Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions crates/core/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn number_stored_as_text(s: &str) -> Option<f64> {
let t = s.trim();
// The same parentheses typed entry reads, accounting forms included: `$(5)`, `(5)%`.
match parenthesized(t) {
Some(inner) if inner.strip_prefix('$').map_or(inner.as_str(), str::trim_start).starts_with(['-', '+', '(']) => None,
Some(inner) if signed_inside(&inner, true) => None,
Some(inner) => parse_plain(&inner, true).map(|(n, _)| -n),
None => parse_plain(t, true).map(|(n, _)| n),
}
Expand All @@ -69,7 +69,7 @@ fn parse_numeric(t: &str, sys: DateSystem, entry: bool) -> Option<(f64, Option<&
// Parenthesised negatives: (100) = -100, and the accounting forms `$(100)` and `(5)%`.
if let Some(inner) = parenthesized(t) {
// Excel reads no sign and no nested parentheses inside: `(-5)`, `($-5)`, `((5))`.
if inner.strip_prefix('$').map_or(inner.as_str(), str::trim_start).starts_with(['-', '+', '(']) {
if signed_inside(&inner, entry) {
return None;
}
let r = parse_plain(&inner, entry).or_else(|| parse_fraction(&inner).map(|n| (n, Some("# ?/?"))));
Expand All @@ -94,6 +94,13 @@ fn parse_unparenthesised(t: &str, sys: DateSystem, entry: bool) -> Option<(f64,
None
}

/// Whether the text inside accounting parentheses carries a sign or more parentheses, after a
/// leading currency symbol: `-5`, `$-5`, `(5)`, and for typed entry `€-5`. Excel reads none of them.
fn signed_inside(inner: &str, entry: bool) -> bool {
let symbols: &[char] = if entry { &['$', '€'] } else { &['$'] };
inner.strip_prefix(symbols).map_or(inner, str::trim_start).starts_with(['-', '+', '('])
}

/// The number inside accounting parentheses, as plain text: `(5)` gives `5`. A dollar sign may
/// stand before them (`$(5)` reads as `($5)`) and a percent sign after them (`(5)%` reads as
/// `(5%)`), with spaces around either. The caller reads only a plain number or a fraction from it.
Expand Down Expand Up @@ -443,12 +450,18 @@ pub fn delocalize_input(s: &str, region: Region) -> Option<String> {
if t.is_empty() || t.starts_with(['=', '\'']) {
return None;
}
// Booleans as the Spanish interface writes them.
if region == Region::EsEs {
if t.eq_ignore_ascii_case("VERDADERO") {
// Booleans as the Spanish and Ukrainian interfaces write them, in any case (`істина`).
let booleans = match region {
Region::EsEs => Some(("VERDADERO", "FALSO")),
Region::UkUa => Some(("ІСТИНА", "ХИБНІСТЬ")),
Region::EnUs => None,
};
if let Some((yes, no)) = booleans {
let upper = t.to_uppercase();
if upper == yes {
return Some("TRUE".into());
}
if t.eq_ignore_ascii_case("FALSO") {
if upper == no {
return Some("FALSE".into());
}
}
Expand Down
23 changes: 23 additions & 0 deletions crates/core/tests/regional_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,26 @@ fn arithmetic_reads_only_the_en_us_currency() {
// Typed entry and the stored-as-text check still read them.
assert_eq!(number_stored_as_text("12.50 €"), Some(12.5));
}

#[test]
fn ukrainian_booleans_read_in_any_case() {
let uk = Region::UkUa;
for (typed, value) in [("ІСТИНА", true), ("істина", true), ("Хибність", false), ("хибність", false)] {
assert_eq!(read(typed, uk).0, Value::Bool(value), "{typed}");
}
// Each region reads its own words only.
assert!(matches!(read("істина", Region::EsEs).0, Value::Text(_)));
assert!(matches!(read("verdadero", uk).0, Value::Text(_)));
}

#[test]
fn a_sign_after_the_euro_inside_parentheses_is_not_a_number() {
use gridcraft_core::parse::number_stored_as_text;
// Excel reads no sign inside accounting parentheses, after a currency symbol either.
for text in ["(€-5)", "(€ -5)", "(€+5)", "($-5)"] {
assert_eq!(parse_input(text, DateSystem::D1900).value, Value::text(text), "{text}");
assert_eq!(number_stored_as_text(text), None, "{text}");
}
assert_eq!(parse_input("(€5)", DateSystem::D1900).value, Value::Number(-5.0));
assert_eq!(number_stored_as_text("(€5)"), Some(-5.0));
}
42 changes: 39 additions & 3 deletions crates/formula/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,41 @@ pub(crate) fn boolean_alias(name: &str) -> Option<bool> {
}
}

/// The Spanish (`display`) or English spelling of a function name that no binding or defined
/// name shadows. Shown in Spanish, a function whose Spanish name a binding shadows keeps its
/// English name; when that English name is the Spanish name of another function (`DECIMAL`,
/// which is FIXED in Spanish), no spelling would read back as the same function, so the
/// formula cannot be shown in Spanish.
fn translate_function(name: &str, display: bool, bound: &impl Fn(&str) -> bool) -> Result<String, ParseError> {
let es = FormulaLocale::Es;
if !display {
return Ok(es.canonical_name(name).to_string());
}
let alias = es.function_name(name);
if !bound(alias) {
return Ok(alias.to_string());
}
if !crate::same_name(es.canonical_name(name), name) {
return Err(ParseError { msg: format!("{name} cannot be shown in Spanish while {alias} names a local value"), pos: 0 });
}
Ok(name.to_string())
}

/// A function given by name as an argument, as in `MAP({1;4};RAIZ)`, is translated like a call.
/// Booleans, bound names and names that are no function's are left alone.
fn function_argument(arg: &mut Expr, display: bool, bound: &impl Fn(&str) -> bool) -> Result<(), ParseError> {
let Expr::Name(name) = arg else { return Ok(()) };
if bound(name) || boolean_alias(name).is_some() {
return Ok(());
}
let es = FormulaLocale::Es;
let other = if display { es.function_name(name) } else { es.canonical_name(name) };
if !crate::same_name(other, name) {
*name = translate_function(name, display, bound)?;
}
Ok(())
}

fn normalize(expr: &mut Expr, known_name: &impl Fn(&str) -> bool, bindings: &mut Vec<String>, depth: usize, display: bool) -> Result<(), ParseError> {
if depth > parser::MAX_DEPTH {
return Err(ParseError { msg: "formula is nested too deeply".into(), pos: 0 });
Expand Down Expand Up @@ -179,17 +214,18 @@ fn normalize(expr: &mut Expr, known_name: &impl Fn(&str) -> bool, bindings: &mut
bindings.truncate(saved);
}
Expr::Call(name, args) => {
let alias = if display { FormulaLocale::Es.function_name(name) } else { FormulaLocale::Es.canonical_name(name) };
if !bound(name, bindings) && (!display || !bound(alias, bindings)) {
*name = alias.to_string();
if !bound(name, bindings) {
*name = translate_function(name, display, &|n| bound(n, bindings))?;
}
for arg in args {
function_argument(arg, display, &|n| bound(n, bindings))?;
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expr::Invoke(callee, args) => {
normalize(callee, known_name, bindings, depth + 1, display)?;
for arg in args {
function_argument(arg, display, &|n| bound(n, bindings))?;
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/formula/src/spanish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ pub(crate) const SPANISH: &[(&str, &str)] = &[
("COUPNUM", "CUPON.NUM"),
("COUPPCD", "CUPON.FECHA.L1"),
("COVAR", "COVAR"),
("COVARIANCE.P", "COVARIANCE.P"),
("COVARIANCE.P", "COVARIANZA.P"),
("COVARIANCE.S", "COVARIANZA.M"),
("CRITBINOM", "BINOM.CRIT"),
("CSC", "CSC"),
Expand Down
33 changes: 33 additions & 0 deletions crates/formula/tests/it/spanish_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,36 @@ fn every_spanish_function_name_round_trips() {
// English names still work when they are not Spanish names of something else.
assert_eq!(input("SUM(1;2)+BUSCARX(1;A:A;B:B)+año(HOY())"), "SUM(1,2)+XLOOKUP(1,A:A,B:B)+YEAR(TODAY())");
}

#[test]
fn a_function_given_by_name_as_an_argument_is_translated() {
let es = FormulaLocale::Es;
assert_eq!(input("MAP({1;4};RAIZ)"), "MAP({1;4},SQRT)");
assert_eq!(input("BYROW(A1:B2;suma)"), "BYROW(A1:B2,SUM)");
assert_eq!(print_input(&parse("MAP({1;4},SQRT)").unwrap(), es, |_| false).unwrap(), "MAP({1;4};RAIZ)");
// Bindings, defined names, booleans and names that are no function's keep their spelling.
assert_eq!(input("LET(RAIZ;LAMBDA(x;x);MAP(A1:A2;RAIZ))"), "LET(RAIZ,LAMBDA(x,x),MAP(A1:A2,RAIZ))");
assert_eq!(print(&parse_input("MAP(A1:A2;RAIZ)", es, |n| n == "RAIZ").unwrap()), "MAP(A1:A2,RAIZ)");
assert_eq!(input("SI(FALSO;total;1)"), "IF(FALSE,total,1)");
let shown = print_input(&parse("LET(RAIZ,1,MAP(A1:A2,SQRT))").unwrap(), es, |_| false).unwrap();
assert_eq!(shown, "LET(RAIZ;1;MAP(A1:A2;SQRT))");
assert_eq!(print(&parse_input(&shown, es, |_| false).unwrap()), "LET(RAIZ,1,MAP(A1:A2,SQRT))");
// A bare name outside an argument list stays a name.
assert_eq!(input("RAIZ+1"), "RAIZ+1");
}

#[test]
fn a_shadowed_alias_never_reads_back_as_another_function() {
let es = FormulaLocale::Es;
// DECIMAL (the base converter) is CONV.DECIMAL in Spanish; with CONV.DECIMAL bound, the
// English DECIMAL would read back as FIXED, so the formula is not shown in Spanish.
for english in ["LET(CONV.DECIMAL,1,DECIMAL(\"FF\",16)+CONV.DECIMAL)", "LET(CONV.DECIMAL,1,MAP(A1:A2,DECIMAL))"] {
assert!(print_input(&parse(english).unwrap(), es, |_| false).is_err(), "{english}");
}
// FIXED keeps its English name when DECIMAL is bound, and reads back as FIXED.
let expr = parse("LET(DECIMAL,1,FIXED(1.5,1)&DECIMAL)").unwrap();
let shown = print_input(&expr, es, |_| false).unwrap();
assert_eq!(shown, "LET(DECIMAL;1;FIXED(1,5;1)&DECIMAL)");
assert_eq!(print(&parse_input(&shown, es, |_| false).unwrap()), print(&expr));
assert_eq!(es.function_name("COVARIANCE.P"), "COVARIANZA.P");
}