diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md index 367056ef9..25da83220 100644 --- a/crates/xlsx/README.md +++ b/crates/xlsx/README.md @@ -88,8 +88,9 @@ A binary workbook gives the same `Workbook`, strings, rows (with their heights, hidden flags and styles), columns, default sizes and merged cells. Its styles are not read (each cell keeps its format index). The descent Excel records for rows and the sheet (`x14ac:dyDescent`) is in alternate-content blocks, which are skipped. Its cell formulas are -decoded from their tokens into the -text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as written, no implicit `@`), with +decoded from their tokens into the text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as +written, apart from the four ISO/IEC 29500 functions `.xlsx` names bare, no implicit `@`, the +spaces and line breaks typed in the formula, numbers as Excel spells them), with `FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the file keeps the tokens once. A formula whose decoding needs something the reader does not read diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index 20953cbad..8dd281b76 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -357,9 +357,10 @@ pub(crate) fn workbook( if let SheetKind::Other(_) = kind { return Err(invalid("unknown sheet relationship type")); } - // Only a worksheet has cells a formula can refer to. + // Only worksheets and macro sheets have cells a formula can refer to (a macro's + // name refers to its macro sheet: `Macro1!$A$1`). if let Some(l) = links.as_mut() { - l.sheets.push((kind == SheetKind::Worksheet).then(|| name.clone())); + l.sheets.push(matches!(kind, SheetKind::Worksheet | SheetKind::Macrosheet).then(|| name.clone())); } wb.sheets.push(SheetEntry { name, sheet_id, visibility, rel_id, kind, part: Some(rel.target.clone()) }); } diff --git a/crates/xlsx/src/xlsb/expr.rs b/crates/xlsx/src/xlsb/expr.rs index 3dd643a6a..197644a33 100644 --- a/crates/xlsx/src/xlsb/expr.rs +++ b/crates/xlsx/src/xlsb/expr.rs @@ -120,6 +120,9 @@ pub(crate) enum Expr { Ref(Reference), /// A defined name. Name(String), + /// Spaces and line breaks typed before and after an expression (`PtgAttrSpace`), which + /// `.xlsx` formula text keeps. + Spaced(String, Box, String), Unary(UnOp, Box), Binary(BinOp, Box, Box), Call(String, Vec), @@ -195,23 +198,33 @@ fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } -/// A number as a formula spells it: up to 15 significant digits, scientific for very large or -/// very small magnitudes. +/// A number as Excel spells it in a formula: rounded to 15 significant digits, written out in +/// full (`100000000000000000000`, `0.0000000000000000001`) when that takes at most 21 characters +/// without the sign, and scientific (`1E+21`, `1.5E-19`, `1.23456789012345E-06`) when it would +/// take more. pub(crate) fn number_to_text(n: f64) -> String { if n == 0.0 || !n.is_finite() { return "0".into(); } - let a = n.abs(); - if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 { + let s = format!("{:.14e}", n.abs()); + let Some((mant, exp)) = s.split_once('e') else { return s }; + let Ok(e) = exp.parse::() else { return s }; + let digits: String = mant.chars().filter(char::is_ascii_digit).collect(); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let k = digits.len() as i32; + let plain_len = if e >= 0 { (e + 1).max(k + i32::from(k > e + 1)) } else { 1 - e + k }; + if plain_len > 21 { return sci_text(n, 15); } - // A value just below 1e15 can round up to 1e15 at 15 significant digits. - if format!("{a:.14e}").parse::().is_ok_and(|r| r >= 1e15) { - return sci_text(n, 15); - } - let mag = a.log10().floor() as i32; - let decimals = (14 - mag).clamp(0, 30) as usize; - trim_decimal(&format!("{n:.decimals$}")) + let sign = if n < 0.0 { "-" } else { "" }; + let plain = if e >= 0 { + let int = (e + 1) as usize; + if digits.len() <= int { format!("{digits}{}", "0".repeat(int - digits.len())) } else { format!("{}.{}", &digits[..int], &digits[int..]) } + } else { + format!("0.{}{digits}", "0".repeat((-e - 1) as usize)) + }; + format!("{sign}{plain}") } fn number(n: f64) -> String { @@ -248,11 +261,14 @@ fn sheet_split(n: &str) -> Option<(&str, &str)> { at.and_then(|i| Some((n.get(..i)?, n.get(i + 1..)?))) } -/// Prints an expression in A1 notation. +/// Prints an expression in A1 notation, trimmed as the `.xlsx` reader trims formula text. pub(crate) fn print(e: &Expr) -> String { let mut s = String::new(); write_expr(&mut s, e); - s + match s.trim() { + t if t.len() == s.len() => s, + t => t.to_string(), + } } fn write_args(s: &mut String, args: &[Expr], sep: char) { @@ -323,6 +339,11 @@ fn write_expr(s: &mut String, e: &Expr) { write_expr(s, x); s.push(')'); } + Expr::Spaced(before, x, after) => { + s.push_str(before); + write_expr(s, x); + s.push_str(after); + } } } @@ -336,10 +357,21 @@ mod tests { assert_eq!(number_to_text(-2.5), "-2.5"); assert_eq!(number_to_text(0.1 + 0.2), "0.3"); assert_eq!(number_to_text(123456789012345.0), "123456789012345"); - assert_eq!(number_to_text(1e15), "1E+15"); - assert_eq!(number_to_text(1234567890123456.0), "1.23456789012346E+15"); + // Written out in full up to 21 characters, as Excel writes them in .xlsx. + assert_eq!(number_to_text(1e15), "1000000000000000"); + assert_eq!(number_to_text(1234567890123456.0), "1234567890123460"); + assert_eq!(number_to_text(-1e20), "-100000000000000000000"); + assert_eq!(number_to_text(1e21), "1E+21"); + assert_eq!(number_to_text(1.5e21), "1.5E+21"); assert_eq!(number_to_text(0.0001), "0.0001"); - assert_eq!(number_to_text(1e-10), "1E-10"); + assert_eq!(number_to_text(1e-10), "0.0000000001"); + assert_eq!(number_to_text(1e-19), "0.0000000000000000001"); + assert_eq!(number_to_text(1e-20), "1E-20"); + assert_eq!(number_to_text(1.5e-19), "1.5E-19"); + assert_eq!(number_to_text(1.23456789012345e-5), "0.0000123456789012345"); + assert_eq!(number_to_text(1.23456789012345e-6), "1.23456789012345E-06"); + assert_eq!(number_to_text(1234567890.12345), "1234567890.12345"); + assert_eq!(number_to_text(1e100), "1E+100"); assert!(number(f64::MAX).parse::().is_ok_and(f64::is_finite)); } } diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs index 327ffcc25..3a6960b39 100644 --- a/crates/xlsx/src/xlsb/formula.rs +++ b/crates/xlsx/src/xlsb/formula.rs @@ -46,9 +46,10 @@ fn pop_n(stack: &mut Stack, n: usize, kids: &mut usize) -> Result, Uns Ok(popped.into_iter().map(|(e, _)| e).collect()) } -/// Pushes the result of a token one level above the operands it consumed. +/// Pushes the result of a token one level above the operands it consumed (two for one with the +/// spacing typed around it, which prints as a level of its own). fn push(stack: &mut Stack, kids: usize, e: Expr) -> Result<(), Unsupported> { - let depth = kids.saturating_add(1); + let depth = kids.saturating_add(1).saturating_add(usize::from(matches!(e, Expr::Spaced(..)))); if depth > MAX_DEPTH { return Err(Unsupported("formula nested too deeply")); } @@ -56,6 +57,48 @@ fn push(stack: &mut Stack, kids: usize, e: Expr) -> Result<(), Unsupported> { Ok(()) } +/// Spaces and line breaks typed in the formula (`PtgAttrSpace`, [MS-XLSB] 2.5.98.32), waiting +/// for the token they belong to. Excel writes the attribute just before that token: spaces +/// before an operand, an operator's symbol or a function call go in `before`; those before a +/// parenthesis's `(`, or before the `)` of a parenthesis or a call, in `open` and `close`. +#[derive(Default)] +struct Spacing { + before: String, + open: String, + close: String, +} + +/// `e` with `ws` typed before it. +fn spaced_before(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(ws + &b, x, a), + e => Expr::Spaced(ws, Box::new(e), String::new()), + } +} + +/// `e` with `ws` typed after it. +fn spaced_after(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(b, x, a + &ws), + e => Expr::Spaced(String::new(), Box::new(e), ws), + } +} + +/// A call's arguments with the spacing typed before its `)`: after the last argument, or alone +/// between the parentheses (`PI( )`). +fn close_args(mut args: Vec, ws: String) -> Vec { + if ws.is_empty() { + return args; + } + match args.pop() { + Some(last) => args.push(spaced_after(last, ws)), + None => args.push(Expr::Spaced(String::new(), Box::new(Expr::Missing), ws)), + } + args +} + /// An error constant's code ([MS-XLSB] 2.5.98.21, `BErr`). fn error_code(code: u8) -> Option { Some(match code { @@ -104,8 +147,8 @@ pub(super) struct Name { /// Workbook-level tables formulas refer to. #[derive(Default)] pub(crate) struct Links { - /// Every sheet's name in `BrtBundleSh` order, `None` for sheets the reader skips or that hold - /// no cells (chart, dialog and macro sheets). + /// Every sheet's name in `BrtBundleSh` order, `None` for the sheets that hold no cells (chart, + /// dialog and module sheets). pub(super) sheets: Vec>, /// Every `BrtName`, in order: `PtgName` indexes them from 1. pub(super) names: Vec, @@ -136,14 +179,11 @@ impl Links { let (Ok(first), Ok(last)) = (usize::try_from(x.first), usize::try_from(x.last)) else { return Err(Unsupported("reference to a missing sheet")); }; - // A span takes every sheet between its ends, so a skipped one anywhere in it changes - // what the reference means. + // A span is spelled by its ends. A sheet between them with no cells (a chart sheet) adds + // nothing to it, and `.xlsx` spells the span the same; an end with no cells can't be named. let span = self.sheets.get(first..=last).filter(|s| !s.is_empty()).ok_or(Unsupported("reference to a missing sheet"))?; - if span.iter().any(Option::is_none) { - return Err(Unsupported("references to sheets the reader skips")); - } let (Some(Some(a)), Some(Some(b))) = (span.first(), span.last()) else { - return Err(Unsupported("reference to a missing sheet")); + return Err(Unsupported("references to sheets with no cells")); }; Ok(Some(if first == last { SheetSel::Named(a.clone()) } else { SheetSel::Span(a.clone(), b.clone()) })) } @@ -261,11 +301,16 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res let mut t = Bytes { b: rgce, pos: 0 }; let mut extra = Bytes { b: rgcb, pos: 0 }; let mut stack: Stack = Vec::new(); + let mut ws = Spacing::default(); while t.pos < rgce.len() { let ptg = t.u8()?; let mut kids = 0usize; // Operand classes (reference / value / array) share one token number. let id = if ptg & 0x60 != 0 { 0x20 | (ptg & 0x1F) } else { ptg }; + // An operand (a constant, reference or name) takes the spacing typed before it; operators, + // calls and parentheses place theirs below, and attribute and cache tokens take none. + let operand = !matches!(id, 0x03..=0x15 | 0x19 | 0x21 | 0x22 | 0x26..=0x29); + let height = stack.len(); match id { 0x03..=0x11 => { let op = match id { @@ -287,6 +332,10 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res }; let b = pop(&mut stack, &mut kids)?; let a = pop(&mut stack, &mut kids)?; + // Spacing before the operator's symbol follows the left operand. + let before = std::mem::take(&mut ws.before); + kids = kids.saturating_add(usize::from(!before.is_empty())); + let a = spaced_after(a, before); push(&mut stack, kids, Expr::Binary(op, Box::new(a), Box::new(b)))?; } 0x12..=0x14 => { @@ -296,11 +345,23 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res _ => UnOp::Percent, }; let x = pop(&mut stack, &mut kids)?; - push(&mut stack, kids, Expr::Unary(op, Box::new(x)))?; + // A sign's spacing comes before it; `%`'s before its symbol, after the operand. + let before = std::mem::take(&mut ws.before); + let e = if op == UnOp::Percent { + kids = kids.saturating_add(usize::from(!before.is_empty())); + Expr::Unary(op, Box::new(spaced_after(x, before))) + } else { + spaced_before(Expr::Unary(op, Box::new(x)), before) + }; + push(&mut stack, kids, e)?; } 0x15 => { let x = pop(&mut stack, &mut kids)?; - push(&mut stack, kids, Expr::Paren(Box::new(x)))?; + let close = std::mem::take(&mut ws.close); + kids = kids.saturating_add(usize::from(!close.is_empty())); + let x = spaced_after(x, close); + let before = std::mem::take(&mut ws.open) + &std::mem::take(&mut ws.before); + push(&mut stack, kids, spaced_before(Expr::Paren(Box::new(x)), before))?; } 0x16 => push(&mut stack, kids, Expr::Missing)?, // PtgStr: cch (u16, at most 255) and always UTF-16, unlike BIFF8. @@ -318,14 +379,27 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res let n = usize::from(t.u16()?) + 1; t.take(n * 2)?; } else { - t.take(2)?; + let data = t.take(2)?; + if kind & 0x40 != 0 { + // PtgAttrSpace / PtgAttrSpaceSemi: PtgAttrSpaceType's `type` and `cch`. + let (kind, n) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0)); + let text = if matches!(kind, 1 | 3 | 5) { "\n" } else { " " }.repeat(usize::from(n)); + match kind { + 0 | 1 | 6 => ws.before.push_str(&text), + 2 | 3 => ws.open.push_str(&text), + 4 | 5 => ws.close.push_str(&text), + _ => return Err(Unsupported("unknown spacing in a formula")), + } + } } if kind & 0x10 != 0 { // PtgAttrSum: SUM of the single operand. let x = pop(&mut stack, &mut kids)?; - push(&mut stack, kids, Expr::Call("SUM".into(), vec![x]))?; + let args = close_args(vec![x], std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call("SUM".into(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; } - // Semi (volatile), If, Goto, Space, Baxcel: no effect on the expression. + // Semi (volatile), If, Goto, Baxcel: no effect on the expression. } 0x1C => { let e = t.u8()?; @@ -346,8 +420,9 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res let iftab = t.u16()?; let (name, args) = function(iftab).ok_or(Unsupported("unknown function"))?; let n = usize::try_from(args).map_err(|_| Unsupported("unknown function argument count"))?; - let args = pop_n(&mut stack, n, &mut kids)?; - push(&mut stack, kids, Expr::Call(name.to_string(), args))?; + let args = close_args(pop_n(&mut stack, n, &mut kids)?, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; } 0x22 => { let n = usize::from(t.u8()?); @@ -362,20 +437,33 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res if args.is_empty() { return Err(Unsupported("malformed function call")); } - let name = match args.remove(0) { + // Spacing typed after the `(` comes before the name's token: it belongs to the + // first argument. + let (lead, first) = match args.remove(0) { + Expr::Spaced(before, x, _) => (before, *x), + e => (String::new(), e), + }; + let name = match first { Expr::Name(n) => n, _ => return Err(Unsupported("function call through an expression")), }; + if let Some(a) = args.first_mut() { + *a = spaced_before(std::mem::replace(a, Expr::Missing), lead); + } // `PY(index, …)` runs a script stored elsewhere in the package, which this // import doesn't read. `PY("code", …)` carries its code and becomes a Python cell. let py = name.rsplit('.').next().is_some_and(|n| n.eq_ignore_ascii_case("PY")); if py && !args.first().is_some_and(literal_text) { return Err(Unsupported("Python code stored outside the cell")); } - push(&mut stack, kids, Expr::Call(name, args))?; + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(bare_function(name), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; } else { let (name, _) = function(tab & 0x7FFF).ok_or(Unsupported("unknown function"))?; - push(&mut stack, kids, Expr::Call(name.to_string(), args))?; + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; } } 0x23 => { @@ -456,6 +544,10 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res } _ => return Err(Unsupported("unknown formula token")), } + if operand && !ws.before.is_empty() && stack.len() == height + 1 { + let (e, depth) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + push(&mut stack, depth, spaced_before(e, std::mem::take(&mut ws.before)))?; + } if stack.len() > MAX_RGCE { return Err(Unsupported("formula too complex")); } @@ -467,11 +559,23 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res Ok(grouped(e, false)) } +/// The name a function called through a hidden name is written with in `.xlsx`: that name +/// (`_xlfn.CONCAT`), except for the four ISO/IEC 29500 functions, which `.xlsx` names without the +/// prefix though `.xlsb` calls them as it calls newer functions. +fn bare_function(name: String) -> String { + const ISO: [&str; 4] = ["ISO.CEILING", "ECMA.CEILING", "NETWORKDAYS.INTL", "WORKDAY.INTL"]; + match name.get(..6).filter(|p| p.eq_ignore_ascii_case("_xlfn.")).and(name.get(6..)) { + Some(bare) if ISO.iter().any(|f| f.eq_ignore_ascii_case(bare)) => bare.to_string(), + _ => name, + } +} + /// Text written out in the formula: a string, or strings joined with `&` (how Python code /// longer than a string constant is written). fn literal_text(e: &Expr) -> bool { match e { Expr::Text(_) => true, + Expr::Spaced(_, x, _) => literal_text(x), Expr::Binary(BinOp::Concat, a, b) => literal_text(a) && literal_text(b), _ => false, } @@ -494,6 +598,7 @@ fn binding(e: &Expr) -> u8 { Expr::Binary(op, ..) => op.precedence(), Expr::Unary(UnOp::Neg | UnOp::Plus, _) => 60, Expr::Unary(UnOp::Percent, _) => 70, + Expr::Spaced(_, x, _) => binding(x), _ => u8::MAX, } } @@ -550,6 +655,7 @@ fn grouped(e: Expr, in_args: bool) -> Expr { Expr::Unary(op, Box::new(if needs { paren(x) } else { x })) } Expr::Paren(x) => paren(grouped(*x, false)), + Expr::Spaced(before, x, after) => Expr::Spaced(before, Box::new(grouped(*x, in_args)), after), Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| grouped(a, true)).collect()), other => other, } diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index 0cf2c5c14..884c7b64f 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1057,3 +1057,108 @@ fn damaged_sizes_are_skipped_or_refused() { assert!(matches!(sizes_of(&file(&sheet)), Err(Error::Invalid(_))), "{why}"); } } + +/// `PtgAttrSpace` ([MS-XLSB] 2.5.98.31): its type (0 spaces before the next token, 1 line breaks +/// before it, 2 spaces before a `(`, 4 spaces before a `)`) and count. +fn space(kind: u8, n: u8) -> Vec { + vec![0x19, 0x40, kind, n] +} + +#[test] +fn typed_spacing_numbers_and_iso_functions_read_as_in_xlsx() { + let a1 = || [&[0x24u8][..], &loc(0, REL)].concat(); + let b1 = || [&[0x24u8][..], &loc(0, 1 | REL)].concat(); + let num = |n: f64| [&[0x1Fu8][..], &n.to_le_bytes()].concat(); + let area = |c: u16| [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &(c | REL).to_le_bytes(), &(c | REL).to_le_bytes()].concat(); + let goto = [0x19u8, 0x08, 0, 0]; + let cells: Vec> = vec![ + // Spacing goes before the next token: an operand, or an operator's symbol. + [&[0x1Eu8, 1, 0][..], &space(0, 2), &[0x1E, 2, 0], &space(0, 1), &[0x03]].concat(), + // ... or a call's `)`, and inside a call's parentheses. + [space(0, 1), a1(), space(0, 1), b1(), space(4, 1), vec![0x42, 2, 4, 0]].concat(), + // Line breaks. + [ + a1(), + vec![0x1E, 0, 0, 0x0D, 0x19, 0x02, 0, 0], + space(1, 1), + space(0, 2), + vec![0x1E, 1, 0], + goto.to_vec(), + space(1, 1), + space(0, 2), + vec![0x1E, 2, 0], + goto.to_vec(), + vec![0x42, 3, 1, 0], + ] + .concat(), + // Inside and before parentheses. + [space(0, 1), vec![0x1E, 1, 0], space(0, 1), vec![0x1E, 2, 0], space(0, 1), vec![0x03], space(4, 1), vec![0x15]].concat(), + [vec![0x1E, 1, 0, 0x1E, 2, 0], space(2, 1), vec![0x15, 0x03]].concat(), + // A call with no arguments, and one through PtgAttrSum. + [space(4, 1), vec![0x41, 19, 0]].concat(), + [area(0), area(1), space(0, 1), vec![0x0F, 0x19, 0x10, 0, 0]].concat(), + // A sign, `%`, and leading spacing (trimmed, as `.xlsx` text is read). + [space(0, 1), vec![0x1E, 1, 0, 0x13], space(0, 1), vec![0x14]].concat(), + [space(0, 3), a1()].concat(), + // A newer function: spacing before its name's token is the first argument's. + [vec![0x1E, 1, 0], space(0, 1), vec![0x23, 5, 0, 0, 0], num(1.5), space(0, 1), vec![0x42, 2, 0xFF, 0, 0x03]].concat(), + vec![0x23, 1, 0, 0, 0, 0x17, 1, 0, b'a', 0, 0x42, 2, 0xFF, 0], + // Numbers written out up to 21 characters, scientific past them. + [num(1e20), num(1e21), vec![0x03], num(1e-19), vec![0x03], num(1.5e-19), vec![0x03], num(1234567890123456.0), vec![0x03]].concat(), + ]; + let mut data = row(0); + for (i, rgce) in cells.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, rgce, &[])); + } + // Name 5: the hidden name ISO.CEILING is called through, as Excel writes it. + let mut book = book_with_links(&xti()); + let end = record(132, &[]); + book.truncate(book.len() - end.len()); + book.extend(name(0x0002_000b, "_xlfn.ISO.CEILING")); + book.extend(end); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let got: Vec<_> = (1..=cells.len() as u32).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + let want = [ + "1 + 2", + "SUM( A1, B1 )", + "IF(A1>0,\n 1,\n 2)", + "( 1 + 2 )", + "1+ (2)", + "PI( )", + "SUM(A1:A2 B1:B2)", + "- 1 %", + "A1", + "1+ ISO.CEILING( 1.5)", + "_xlfn.CONCAT(\"a\")", + "100000000000000000000+1E+21+0.0000000000000000001+1.5E-19+1234567890123460", + ]; + assert_eq!(got, want.map(Some)); +} + +#[test] +fn references_to_macro_sheets_and_spans_over_chart_sheets_are_named() { + // Sheets Data, a chart sheet, an XLM macro sheet, Hidden; sheet links Macro1, Data:Hidden + // (over the chart sheet) and Chart1 (no cells). + let mut book = record(131, &[]); + book.extend(record(153, &[[0u8; 8].as_slice(), &wide("")].concat())); + book.extend(record(143, &[])); + for (id, rel, name) in [(1u32, "one", "Data"), (3, "c", "Chart1"), (4, "m", "Macro1"), (2, "two", "Hidden")] { + book.extend(record(156, &[&0u32.to_le_bytes()[..], &id.to_le_bytes(), &wide(rel), &wide(name)].concat())); + } + book.extend(record(144, &[])); + let mut xti = 3u32.to_le_bytes().to_vec(); + for (first, last) in [(2i32, 2i32), (0, 3), (1, 1)] { + xti.extend([0u32.to_le_bytes(), first.to_le_bytes(), last.to_le_bytes()].concat()); + } + book.extend([record(353, &[]), record(357, &[]), record(362, &xti), record(354, &[]), record(132, &[])].concat()); + let rels = RELS.replace( + "", + r#""#, + ); + let ref3d = |ixti: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(0, 0)].concat(); + let data = [row(0), formula_cell(1, &ref3d(0), &[]), formula_cell(2, &ref3d(1), &[]), formula_cell(3, &ref3d(2), &[])].concat(); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, &rels, TYPES)).unwrap(); + let got: Vec<_> = (1..=3).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + assert_eq!(got, [Some("Macro1!$A$1"), Some("Data:Hidden!$A$1"), None]); + assert!(warned(&wb, "references to sheets with no cells"), "{:?}", wb.warnings); +}