xref: /trunk/odf_docs/openformula-milestone-b-report.md (revision 1354dfcdad4129e7cc561fdcfbb4f6c8958f0428)
1<!--
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements.  See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership.  The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License.  You may obtain a copy of the License at
9
10   http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied.  See the License for the
16 specific language governing permissions and limitations
17 under the License.
18-->
19
20# Apache OpenOffice — OpenFormula Milestone B Report (with B.1 corrections)
21
22## 1. Commit IDs
23
24- Starting commit: `0289c7f917` (end of Milestone A)
25- IFNA (initial): `082ee9a94b` (source + tests)
26- SKEWP (initial): `6a3f45420f` (source + tests)
27- IFNA + SKEWP corrections (B.1): `c9db33542f` (source + tests + report)
28- Branch: `openformula`
29
30## 2. Source-Mining Findings
31
32### IFNA
33
34**Before this milestone, IFNA did not exist in AOO.** The only reference was an
35Excel-filter stub at `main/sc/source/filter/excel/xlformula.cxx:404`:
36`EXC_FUNCENTRY_ODF( ocNoName, 2, 2, 0, "IFNA" )` — an `ocNoName` placeholder
37with no opcode, no interpreter method, no `scfuncs.src` entry, and no
38`core_resource.src` entry.
39
40**IF (ocIf=6)** provides the lazy-evaluation pattern to reuse. IF uses
41jump-based compilation (`FormulaCompiler.cxx:1073-1128`) where the compiler
42generates jump addresses for the value, fallback, and end paths. At runtime,
43`ScInterpreter::ScIfJump()` (`interpr1.cxx:93`) pops the condition and jumps
44to the appropriate path, evaluating only the taken branch. It calls
45`MatrixDoubleRefToMatrix()` first to convert references to matrices, then
46switches on `GetStackType()`.
47
48**IFNA needs the same lazy-evaluation machinery** because `value_if_na` must
49not be evaluated when `value` is not #N/A. Simply evaluating both arguments
50eagerly would be wrong: e.g. `IFNA(5; 1/0)` must return 5, not #DIV/0!.
51
52**Error code:** #N/A = `NOTAVAILABLE` (0x7fff), defined in
53`main/formula/inc/formula/errorcodes.hxx:81`. The interpreter tracks errors
54via `nGlobalError` and `FormulaToken::GetError()` / `GetType() == svError`.
55
56### SKEWP
57
58**Before this milestone, SKEWP did not exist in AOO.** The only reference was
59an Excel-filter stub at `main/sc/source/filter/excel/xlformula.cxx:415`:
60`EXC_FUNCENTRY_ODF( ocNoName, 1, MX, 0, "SKEWP" )`.
61
62**SKEW (ocSchiefe=325)** exists at `interpr3.cxx:3081` (`ScInterpreter::ScSkew`),
63using the helper `CalculateSkew()` (`interpr3.cxx:2969`) for data collection.
64`CalculateSkew` collects numeric values from doubles, single/double references,
65ref lists (via `ScValueIterator`), and matrices — skipping empty cells, text,
66and logical values, propagating errors via `nGlobalError`.
67
68**ScSkew formula** (sample skewness):
69
70```
71mean = sum / N
72stdDev = sqrt( sum((xi-mean)^2) / (N-1) )     // sample, N-1
73result = (xcube * N) / ((N-1) * (N-2))        // sample skewness
74```
75
76**SKEWP formula** (population skewness, ODF 1.4 §6.18.63):
77
78```
79mean = sum / N
80sigma = sqrt( sum((xi-mean)^2) / N )          // population, N
81result = (1/N) * sum( ((xi-mean)/sigma)^3 )
82```
83
84## 3. Defects Found and Corrected (B.1)
85
86### IFNA: reference handling was broken
87
88The initial `ScIfna()` implementation only peeked at `pStack[sp-1]` assuming
89it was an `svError` token. This works for direct `NA()` calls but fails for:
90
91- **Cell references** (`svSingleRef`): a reference token on the stack is not
92  an error token — it must be dereferenced to check the cell's error code.
93- **Range references** (`svDoubleRef`): same issue, needs implicit intersection.
94- **Reference lists** (`svRefList`) and **matrices** (`svMatrix`): not handled.
95
96The initial code also had a stack-safety issue: `--sp` discards the token
97without calling `PopError()`, which is fine for `svError` but would be wrong
98for other types.
99
100### SKEWP: argument semantics inconsistent
101
102`CalculateSkew()` (shared with SKEW) treated direct scalar text (`svString`)
103as `errIllegalParameter` via the `default` case, but skipped text in ranges
104and matrices. This made `SKEWP(1;"text";2)` fail with an error instead of
105returning 0 (skipping text, evaluating `{1, 2}`).
106
107### SKEWP: error propagation lost original error code
108
109When a direct error argument (e.g. `1/0`) was passed, `svError` fell into
110`CalculateSkew()`'s `default` → `SetError(errIllegalParameter)`, replacing
111the original error (e.g. `#DIV/0!`) with a generic "illegal parameter" error.
112
113**Update:** both `CalculateSkew()` changes were taken out again later. Direct text is an
114error, which ODF 1.4 allows, and `SKEW(1/0)` returns `#DIV/0!` without the `svError` case.
115
116## 4. Files Changed and Purpose
117
118| File | Change | Purpose |
119|------|--------|---------|
120| `main/formula/inc/formula/compiler.hrc` | Add `SC_OPCODE_IFNA=409`, `SC_OPCODE_SKEWP=410`; move `SC_OPCODE_STOP_2_PAR` to 411; set `SC_OPCODE_LAST_OPCODE_ID=410` | Allocate opcodes for the two new functions |
121| `main/formula/inc/formula/opcode.hxx` | Add `ocIfna` and `ocSkewP` enum entries | Map opcode constants to C++ names |
122| `main/formula/source/core/api/FormulaCompiler.cxx` | Add `ocIfna` jump-based compilation block (lazy eval); SKEWP handled by existing 2-param branch | Compiler recognition and code generation |
123| `main/formula/source/core/resource/core_resource.src` | Add `IFNA` and `SKEWP` string mappings in all 3 Resource blocks | Function-name recognition (ODFF, English, localized) |
124| `main/sc/source/core/inc/interpre.hxx` | Declare `ScIfna()` and `ScSkewP()` | Interpreter method declarations |
125| `main/sc/source/core/tool/interpr1.cxx` | **Rewrite `ScInterpreter::ScIfna()`**: handle `svError`, `svSingleRef`, `svDoubleRef`, `svRefList`, `svMatrix`, and default cases with proper reference dereferencing via `PopDoubleRefOrSingleRef()` and cell value push via `PushCellResultToken()` | IFNA evaluation with correct reference handling |
126| `main/sc/source/core/tool/interpr3.cxx` | Implement `ScInterpreter::ScSkewP()` (population skewness); add `svString` skip case to `CalculateSkew()` (fixes text handling for both SKEW and SKEWP); add `svError` case to `CalculateSkew()` (preserves original error code) | SKEWP computation + shared bug fixes |
127| `main/sc/source/core/tool/interpr4.cxx` | Add `case ocIfna: ScIfna();` and `case ocSkewp: ScSkewP();` | Interpreter dispatch |
128| `main/sc/source/ui/src/scfuncs.src` | Add `Resource SC_OPCODE_IFNA` and `Resource SC_OPCODE_SKEWP` blocks | Function wizard / metadata / help |
129| `main/sc/source/filter/excel/xlformula.cxx` | Replace `ocNoName` stubs with `ocIfna` and `ocSkewP` | Excel import/export mapping |
130| `test/odf-validate/calcval-cases14.tsv` | Add/correct 22 test cases for IFNA and SKEWP | Regression tests |
131
132No production code outside IFNA/SKEWP was touched. No LibreOffice code was
133copied. No third-party formula engine was introduced. No unrelated refactoring
134was performed.
135
136## 5. IFNA Semantics and Error-Handling Decisions
137
138### Lazy evaluation via jump-based compilation
139
140`FormulaCompiler.cxx` generates code for `IFNA(value; value_if_na)` as:
141
142```
143[value code] [IFNA token(jump[0]=2)] [fallback code]
144                         jump[1]       jump[2]
145```
146
147- `jump[1]` = address where fallback code begins
148- `jump[2]` = address after fallback (end)
149
150At runtime, `ScInterpreter::ScIfna()` (`interpr1.cxx:324`):
151
1521. Switches on `GetStackType()`:
153   - **`svError`**: Peeks at error code. If `NOTAVAILABLE` (#N/A), discards
154     the token (`--sp`) and jumps to `jump[1]` (fallback). Otherwise leaves
155     the error on the stack and jumps to `jump[2]` (end, propagate error).
156   - **`svSingleRef` / `svDoubleRef`**: Pops the reference via
157     `PopDoubleRefOrSingleRef()` (which performs implicit intersection for
158     ranges), gets the cell via `GetCell()`, checks `GetCellErrCode()`:
159     - `#N/A` → jump to fallback (reference already popped, nothing on stack)
160     - Other error → `PushError(nErr)`, jump to end
161     - Value → `PushCellResultToken(true, aAdr, NULL, NULL)`, jump to end
162   - **`svRefList` / `svMatrix`**: Jumps to end, returning the value as-is.
163     IFNA is not an array-forcing function; per-element #N/A substitution is
164     not implemented. This is a documented limitation.
165   - **Default** (double, string, etc.): Jumps to end, keeping the value.
166
1672. `value_if_na` is never compiled/evaluated unless `value` is #N/A — the
168   compiler only emits fallback code after the jump target, so it is simply
169   never reached when value is not #N/A.
170
1713. `value` is evaluated exactly once.
172
1734. Errors other than #N/A are propagated unchanged — `ScIfna` does not clear
174   `nGlobalError` for non-#N/A errors.
175
176### Supported input forms
177
178| Input form | Handling |
179|------------|----------|
180| `NA()` (direct #N/A error) | Recognized as `svError` with `NOTAVAILABLE` → fallback |
181| Cell reference containing #N/A | Dereferenced via `PopSingleRef`, cell error checked → fallback |
182| Cell reference containing other error | Dereferenced, error pushed → propagated |
183| Cell reference containing value | Dereferenced, cell value pushed → returned |
184| Range reference | Implicit intersection via `DoubleRefToPosSingleRef`, first cell checked |
185| Reference list | Returned as-is (documented limitation) |
186| Matrix | Returned as-is (documented limitation) |
187| Direct text/number/logical | Returned unchanged |
188
189### Documented limitation: matrix handling
190
191**Update:** a matrix argument is now substituted per element through a jump matrix, so
192`{=IFNA(A1:A3;0)}` and `{=SUM(IFNA(A1:A3;0))}` work. A plain range outside an array
193formula, e.g. `SUMPRODUCT(IFNA(A1:A3;0))`, still takes the first cell. The text below is the
194original limitation.
195
196IFNA is not an array-forcing function in OpenFormula 1.4. When `value` is a
197matrix, the current implementation returns the matrix as-is without
198per-element #N/A substitution. Implementing full element-wise IFNA would
199require a `ScJumpMatrix`-based approach (as used by `ScIfJump`) to evaluate
200the fallback per element, which is beyond the scope of this milestone.
201
202## 6. SKEWP Formula and Edge-Case Decisions
203
204### Population standard deviation (sigma, denominator N)
205
206```
207sigma = sqrt( sum((xi - mean)^2) / N )
208```
209
210This differs from SKEW's sample standard deviation (denominator N−1).
211
212### Population skewness result
213
214```
215result = (1/N) * sum( ((xi - mean) / sigma)^3 )
216```
217
218### Edge cases
219
220| Case | Behavior | Rationale |
221|------|----------|-----------|
222| N = 0 (no args) | Error | `CalculateSkew` requires ≥1 param |
223| N = 1 | Error | `sigma = 0`, zero variance |
224| Constant data (zero variance) | Error | `sigma = 0`, division by zero |
225| Two observations, non-constant | Valid result | e.g. SKEWP(1;2) = 0 |
226| Error in input | Propagated | Original error code preserved |
227| Text in direct argument | Skipped | Consistent with range/matrix handling |
228| Empty cells | Skipped | `CalculateSkew` skips non-numeric |
229| Matrix / array input | Supported | `CalculateSkew` handles `svMatrix` |
230
231### Numerical stability
232
233Uses the same two-pass approach as SKEW (compute mean first, then squared
234deviations). No unnecessary integer conversions. The `fSigma == 0.0` check
235avoids division by zero for zero-variance data.
236
237### SKEW vs SKEWP difference
238
239For `{1, 1, 2}`:
240
241- SKEWP = 1/√2 ≈ 0.7071067812 (population)
242- SKEW = √3 ≈ 1.7320508076 (sample)
243They differ, confirming the formulas are distinct.
244
245## 7. Function Registration and Documentation
246
247**Opcode allocation:** IFNA=409, SKEWP=410. `SC_OPCODE_LAST_OPCODE_ID`
248updated from 408 to 410. `SC_OPCODE_STOP_2_PAR` moved from 409 to 411 so both
249new functions fall in the 2-parameter range (`START_2_PAR=201` to
250`STOP_2_PAR=411`), which is already handled by the compiler's symbol-table
251construction (`FormulaCompiler.cxx:452-462`) and 2-param compilation branch
252(`FormulaCompiler.cxx:1014`).
253
254**Compiler:** IFNA uses a dedicated jump-based compilation block (modeled on
255ocIf/ocChose at `FormulaCompiler.cxx:1073-1128`). SKEWP uses the existing
2562-parameter function compilation path.
257
258**Interpreter:** `ScIfna` in `interpr1.cxx:324`, `ScSkewP` in
259`interpr3.cxx:3081`. Dispatch in `interpr4.cxx`.
260
261**Resources:** `core_resource.src` entries in all 3 Resource blocks
262(ENGLISH_ODFF, ENGLISH, localized). `scfuncs.src` entries with function group
263(LOGICAL for IFNA, STATISTIC for SKEWP), parameter names/descriptions, and
264HID references.
265
266**Excel import/export:** `xlformula.cxx` stubs updated from `ocNoName` to
267`ocIfna`/`ocSkewP`, so Excel files containing IFNA/SKEWP are mapped to the
268real implementations.
269
270**ODF save/reload:** Function names are written as standard `IFNA`/`SKEWP`
271per `core_resource.src` ODFF mappings, so they survive ODF save/reload.
272
273**Help documentation:** `scfuncs.src` entries include English descriptions
274and parameter documentation. No separate helpcontent2 files were added (the
275existing convention for recently added functions like EASTERSUNDAY also uses
276only `scfuncs.src`).
277
278## 8. Test Cases Added and Corrected
279
280Added 6 cases to `test/odf-validate/calcval-cases14.tsv` in B.1 (total IFNA,
281SKEWP, and SKEW cases now 24):
282
283**IFNA (11 cases):**
284
285| ID | Formula | Expected | Purpose |
286|----|---------|----------|---------|
287| IFNA.num | `=IFNA(5;10)` | 5 | Numeric value returned unchanged |
288| IFNA.text | `=IFNA("hello";"world")` | hello | Text value returned unchanged |
289| IFNA.na.num | `=IFNA(NA();10)` | 10 | #N/A → fallback numeric |
290| IFNA.na.text | `=IFNA(NA();"fallback")` | fallback | #N/A → fallback text |
291| IFNA.otherr | `=IFNA(1/0;10)` | #ERR | Non-#N/A error propagated |
292| IFNA.lazy.ok | `=IFNA(5;1/0)` | 5 | Fallback not evaluated (lazy) |
293| IFNA.lazy.err | `=IFNA(NA();1/0)` | #ERR | Fallback evaluated and errors |
294| IFNA.nested | `=IFNA(IFNA(NA();5);10)` | 5 | Nested IFNA |
295| IFNA.ref | `=IFNA(D1;10)` | 10 | Cell reference containing value (D1=10) |
296| IFNA.ref.text | `=IFNA(A1;10)` | y | Cell reference containing text (A1=y) |
297| IFNA.range | `=IFNA(D1:D3;99)` | 10 | Range reference, implicit intersection takes first cell |
298
299**SKEWP (11 cases):**
300
301| ID | Formula | Expected | Purpose |
302|----|---------|----------|---------|
303| SKEWP.sym | `=SKEWP(1;2;3;4;5)` | 0 | Symmetric → zero skewness |
304| SKEWP.pos | `=SKEWP(1;1;2)` | 0.7071067812 | Positive skew (1/√2) |
305| SKEWP.neg | `=SKEWP(1;2;2)` | -0.7071067812 | Negative skew (−1/√2) |
306| SKEWP.vs.skew | `=SKEWP(1;1;2)` | 0.7071067812 | Population ≠ sample (SKEW gives √3≈1.7321) |
307| SKEWP.one | `=SKEWP(5)` | #ERR | Single observation → zero variance |
308| SKEWP.zero | `=SKEWP(5;5;5)` | #ERR | Constant data → zero variance |
309| SKEWP.two | `=SKEWP(1;2)` | 0 | Two observations, non-constant, zero skew |
310| SKEWP.range | `=SKEWP(D1:D3)` | 0 | Range input (D1:D3=10,20,30, symmetric) |
311| SKEWP.array | `=SKEWP({1;1;2})` | 0.7071067812 | Array/matrix input |
312| SKEWP.mixed | `=SKEWP(1;"text";2)` | 0 | Text skipped, {1,2} symmetric |
313| SKEWP.err | `=SKEWP(1/0)` | #ERR | Error value propagates (original error preserved) |
314
315**SKEW regression (2 cases):**
316
317| ID | Formula | Expected | Purpose |
318|----|---------|----------|---------|
319| SKEW.text | `=SKEW(1;"text";2)` | 0 | Regression: direct scalar text skipped, {1,2} symmetric |
320| SKEW.err | `=SKEW(1/0)` | #ERR | Regression: error argument propagates |
321
322**Independent numerical verification (SKEWP):**
323
324- SKEWP({1,1,2}): mean=4/3, sigma²=2/9, sigma=√2/3
325  standardized³ sum = 3/√2, result = (3/√2)/3 = 1/√2 ≈ 0.7071067812
326- SKEW({1,1,2}): sample stdDev=1/√3, result = √3 ≈ 1.7320508076
327  (differs from SKEWP, confirming distinct formulas)
328- SKEWP({1,2}): mean=1.5, sigma²=0.25, sigma=0.5
329  ((1-1.5)/0.5)³ = -1, ((2-1.5)/0.5)³ = 1, sum=0, result=0/2=0
330
331**Independent numerical verification (IFNA):** All IFNA cases are logical
332operations (return value or fallback), no numerical computation needed.
333
334**Independent numerical verification (SKEW):** SKEW({1,"text",2}) skips text,
335evaluating {1,2}, which is symmetric → 0. SKEW(1/0) propagates #DIV/0!.
336
337## 9. Build and Test Commands Executed
338
339**Environment:** Linux (WSL2) x86_64. `dmake` and `make` are installed, but
340there is **no configured AOO build tree**. The `main/solver/510/` directory
341contains only a partial `xml2cmp` build; the `sc` module is not built. No
342`Module_*.mk` makefiles exist in the source tree (they are generated by AOO's
343gbuild configure step, which has not been run).
344
345**Attempted:** `dmake -C main/sc/source/core/tool interpr1.obj` → prints dmake
346usage only (no makefile present).
347
348**Result:** Build and test execution were **not possible** in this environment.
349The calcval ODF 1.4 tests require a built office and (per `test/odf-validate/`
350README) run on macOS.
351
352**Static verification performed:**
353
354- Brace balance: 0 for all modified C++ files (`interpr1.cxx`, `interpr3.cxx`)
355- Opcode values: IFNA=409, SKEWP=410, LAST_OPCODE_ID=410, STOP_2_PAR=411 —
356  all unique and consistent
357- All identifiers used (`formula::svError`, `NOTAVAILABLE`, `pStack`, `sp`,
358  `aCode`, `pCur`, `PopDoubleRefOrSingleRef`, `PushCellResultToken`,
359  `GetCellErrCode`, `GetCell`, `PopError`, `PopString`) were already present
360  in the respective function scopes
361
362**For validation in a configured build environment:**
363
3641. Configure AOO (run `autogen.sh`/`configure`, then `build.pl --all`)
3652. Build the `sc` module
3663. Run `test/odf-validate/start.sh calcval <port>` and
367   `test/odf-validate/runpy.sh calcval.py <port> calcval-cases14.tsv <out.json>`
368   on macOS, then `python3 -I calcval.py --compare ...`
369
370## 10. Not Verified and Why
371
372- **Real build and runtime tests:** No configured AOO build tree exists in
373  this environment. Static checks (brace balance, opcode uniqueness,
374  identifier scope) are not substitutes for compilation and execution.
375- **ODF save/reload round-trip:** Cannot be tested without a built office.
376- **Excel import/export:** Cannot be tested without a built office.
377- **Function wizard integration:** Cannot be tested without a built office.
378- **Matrix IFNA per-element behavior:** Documented as not implemented;
379  cannot be verified without a built office.
380- **IFNA reference to #N/A cell:** Cannot be tested because the calcval test
381  harness does not write cells containing error values; only fixed data
382  values are pre-populated. The reference-to-#N/A code path (via
383  `GetCellErrCode()`) is implemented but untested at runtime.
384- **Specific error code expectations:** The test harness only supports `#ERR`
385  (any error) and `#N/A`, not specific error codes like `#DIV/0!`. Error
386  tests therefore use `#ERR`, which cannot distinguish the original error
387  from a substituted one.
388
389## 11. Remaining Compatibility and Conformance Concerns
390
391- **IFNA matrix evaluation:** IFNA is not an array-forcing function. When
392  `value` is a matrix or reference list, the current implementation returns
393  the value as-is without per-element #N/A substitution. Per OpenFormula 1.4
394  §6.15.13, IFNA's behavior with array inputs is implementation-defined.
395  Full element-wise support would require `ScJumpMatrix`-based infrastructure
396  (as used by `ScIfJump`).
397- **IFNA range references:** Uses implicit intersection
398  (`DoubleRefToPosSingleRef`) to check the first cell of a range. If the
399  range contains #N/A in a non-intersected cell, it is not detected.
400- **SKEWP text handling change:** `CalculateSkew()` now skips direct scalar
401  text (`svString`) instead of raising `errIllegalParameter`. This changes
402  SKEW behavior identically (both functions share `CalculateSkew()`). The
403  change makes direct-argument text handling consistent with range/matrix
404  handling, which is more consistent with OpenFormula's NumberSequence
405  definition (text excluded). Both SKEW and SKEWP are affected equally.
406- **SKEWP error propagation:** Direct error arguments now preserve the
407  original error code instead of replacing it with `errIllegalParameter`.
408  This changes SKEW behavior identically (both functions share
409  `CalculateSkew()`). Both functions now propagate the original error.
410
411## 12. Normative vs Implementation Choices
412
413| Aspect | ODF 1.4 Normative | AOO Implementation Choice |
414|--------|-------------------|---------------------------|
415| IFNA lazy evaluation | Required (value_if_na only when value is #N/A) | Jump-based compilation (same as IF) |
416| IFNA error propagation | Non-#N/A errors propagated | Propagated via nGlobalError |
417| IFNA matrix/array behavior | Implementation-defined | Return value as-is (documented limitation) |
418| SKEWP formula | Population skewness, denominator N | Implemented exactly as specified |
419| SKEWP zero variance | Not explicitly specified | Returns error (PushIllegalArgument) |
420| SKEWP N=1 | Not explicitly specified | Returns error (sigma=0) |
421| SKEWP text in direct arg | NumberSequence excludes text | Skipped (consistent with ranges) |
422| SKEWP error in direct arg | Error propagated | Original error code preserved |
423