Commit 2e5b193b0e

2e5b193b0e55f90ba884240bdf13ed176f3b757d

parent: fb3b538d8b

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 10:08 UTC

Match Calc on vectors without commas, numbers with two points and num errors

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +58 −11
@@ -16,8 +16,10 @@ public enum Calc {
1616 /// An error Calc reports, which a table shows as `#ERROR`.
1717 public struct Failure: Error, Equatable, CustomStringConvertible {
1818 public let reason: String
19 /// Where in the expression Calc reports the error.
20 public let position: Int
1921 public var description: String { reason }
20 init(_ reason: String) { self.reason = reason }
22 init(_ reason: String, position: Int = 0) { (self.reason, self.position) = (reason, position) }
2123 }
2224
2325 public indirect enum Value: Equatable, Sendable {
@@ -67,10 +69,11 @@ public enum Calc {
6769 if numeric {
6870 switch value {
6971 case .int, .float, .frac: break
70 // Calc explains a division by zero or a power it left alone.
71 case .symbolic(let t) where t.contains(where: { ["/", "^"].contains($0) }):
72 throw Unsupported("symbolic arithmetic")
73 default: throw Failure("Number expected")
72 default:
73 // Calc explains the first argument a quotient, power or function
74 // rejected along the way, which isn't tracked here.
75 if tree.mayExplain { throw Unsupported("symbolic arithmetic") }
76 throw Failure("Number expected")
7477 }
7578 }
7679 return try format(value, modes.format)
@@ -929,6 +932,17 @@ public enum Calc {
929932 case binary(Character, Node, Node)
930933 case call(String, [Node])
931934 case variable(String)
935
936 /// Whether the formula has a quotient, a power or a function call.
937 var mayExplain: Bool {
938 switch self {
939 case .number, .variable: false
940 case .call: true
941 case .vector(let items): items.contains { $0.mayExplain }
942 case .unary(_, let a): a.mayExplain
943 case .binary(let op, let a, let b): "/%\\^".contains(op) || a.mayExplain || b.mayExplain
944 }
945 }
932946 }
933947
934948 struct Parser {
@@ -936,6 +950,8 @@ public enum Calc {
936950 var i = 0
937951 /// Inside `[...]`, where Calc reads `x -1` as two elements.
938952 var inVector = false
953 /// Inside `[...]` with no comma, where Calc reads `1 2` as two elements.
954 var spaceSeparated = false
939955
940956 init(_ s: String) { chars = Array(s) }
941957
@@ -1026,6 +1042,9 @@ public enum Calc {
10261042 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
10271043 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
10281044 break
1045 } else if spaceSeparated, chars[i - 1] == " " || chars[i - 1] == "\t" {
1046 // Calc reads `[1 2]` as two elements and `[1 2 * 3]` as one; not reproduced.
1047 throw Unsupported("formula syntax")
10291048 }
10301049 left = .binary("*", left, try unary())
10311050 }
@@ -1086,19 +1105,19 @@ public enum Calc {
10861105 guard let c = peek() else { throw Unsupported("formula syntax") }
10871106 if c == "(" {
10881107 i += 1
1089 let outer = inVector
1090 inVector = false
1108 let outer = (inVector, spaceSeparated)
1109 (inVector, spaceSeparated) = (false, false)
10911110 let inner = try or()
1092 inVector = outer
1111 (inVector, spaceSeparated) = outer
10931112 guard peek() == ")" else { throw Unsupported("formula syntax") }
10941113 i += 1
10951114 return inner
10961115 }
10971116 if c == "[" {
10981117 i += 1
1099 let outer = inVector
1100 inVector = true
1101 defer { inVector = outer }
1118 let outer = (inVector, spaceSeparated)
1119 (inVector, spaceSeparated) = (true, !hasComma())
1120 defer { (inVector, spaceSeparated) = outer }
11021121 var items: [Node] = []
11031122 if peek() != "]" {
11041123 items.append(try or())
@@ -1124,6 +1143,8 @@ public enum Calc {
11241143 name.append(chars[i])
11251144 i += 1
11261145 }
1146 // `[f (x)]` is two elements.
1147 if spaceSeparated, i < chars.count, chars[i] != "(", peek() == "(" { throw Unsupported("formula syntax") }
11271148 guard peek() == "(" else {
11281149 if name == "nan" { return .number(.nan) }
11291150 // Calc's names are letters and digits; `_` is a subscript, and `'` and `#`
@@ -1133,6 +1154,9 @@ public enum Calc {
11331154 return .variable(name)
11341155 }
11351156 i += 1
1157 let outer = (inVector, spaceSeparated)
1158 (inVector, spaceSeparated) = (false, false)
1159 defer { (inVector, spaceSeparated) = outer }
11361160 var args: [Node] = []
11371161 if peek() != ")" {
11381162 args.append(try or())
@@ -1148,6 +1172,18 @@ public enum Calc {
11481172 throw Unsupported("formula syntax")
11491173 }
11501174
1175 /// `math-check-for-commas`: whether a comma follows before the bracket that closes.
1176 func hasComma() -> Bool {
1177 var depth = 0
1178 for c in chars[i...] {
1179 if "[{(".contains(c) { depth += 1 }
1180 if "]})".contains(c) { depth -= 1 }
1181 if depth < 0 { return false }
1182 if c == ",", depth == 0 { return true }
1183 }
1184 return false
1185 }
1186
11511187 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
11521188 /// and `1:2:3`, and integers in a radix, `16#FF`.
11531189 mutating func number() throws -> Value {
@@ -1193,6 +1229,17 @@ public enum Calc {
11931229 i += 1
11941230 }
11951231 fraction = f
1232 // Calc reads digits and points as one number: `21.11.2026` is a bad format.
1233 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1234 while i < chars.count, (chars[i].isASCII && chars[i].isNumber)
1235 || (chars[i] == "." && (i + 1 >= chars.count || chars[i + 1] != ".")) { i += 1 }
1236 // The position is in the string Calc reads, after it rewrites `..` and
1237 // characters such as `²`; an exponent belongs to the number.
1238 let before = String(chars[..<i])
1239 guard before.allSatisfy(\.isASCII), !before.contains(".."),
1240 i >= chars.count || !"eE".contains(chars[i]) else { throw Unsupported("formula syntax") }
1241 throw Failure("Bad format", position: i)
1242 }
11961243 }
11971244 var exponent: Int?
11981245 if i < chars.count, chars[i] == "e" || chars[i] == "E" {
Sources/OrgCore/Compute/CalcSymbolic.swift −8
@@ -654,11 +654,3 @@ extension Calc {
654654 }
655655 }
656656}
657
658extension Calc.Term {
659 /// Whether an operator or function in the formula satisfies `predicate`.
660 func contains(where predicate: (String) -> Bool) -> Bool {
661 guard case .op(let f, let args) = self else { return false }
662 return predicate(f) || args.contains { $0.contains(where: predicate) }
663 }
664}
Sources/OrgCore/Compute/TableFormulas.swift +3 −3
@@ -1,8 +1,8 @@
11import Foundation
22
33// Table formulas (org-table.el, Org 9.8.7): `org-table-recalculate` and
4// `org-table-eval-formula` with Calc and Lisp evaluated natively. Symbolic results, Calc
5// features beyond `Calc` and Lisp beyond `Elisp` throw `Calc.Unsupported`; the caller then
4// `org-table-eval-formula` with Calc and Lisp evaluated natively. Calc features beyond
5// `Calc` and Lisp beyond `Elisp` throw `Calc.Unsupported`; the caller then
66// recalculates the table in Emacs. `remote()` finds tables by name in the file, and by ID
77// here or, through `RemoteTables`, in other files.
88
@@ -626,7 +626,7 @@ extension EmacsBuffer {
626626 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
627627 } catch let failure as Calc.Failure {
628628 // A duration formula takes Calc's error for a string, as org does.
629 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (0 \"\(failure.reason)\")") }
629 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (\(failure.position) \"\(failure.reason)\")") }
630630 (result, fmt) = ("#ERROR", nil)
631631 }
632632 }
Tests/OrgCoreTests/CalcTests.swift +18 −1
@@ -359,6 +359,8 @@ struct CalcTests {
359359 "uinf+1", "inf/0", "uinf/0", "inf^-1", "x/inf", "2^inf", "0.5^inf", "(-2)^inf", "inf^0", "nan*x", "x+nan", "x/nan",
360360 "vsum([x,1,2])", "vmean([x,1])", "vmean([x,2,3])", "vsum([x,y,1])", "vprod([x,2,3])", "vmean([a,b])", "vcount([x,1])",
361361 "vsum([1/0, 2])", "vsum([5 kg,3])", "vsum([2 (3),1])",
362 // No comma: Calc separates elements by spaces, except inside parentheses and arguments.
363 "vsum([1 - 2])", "vsum([x - 1])", "vsum([2x])", "vsum([(1 2)])", "vsum([max(1 2,3)])", "vcount([x])",
362364 ]
363365
364366 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -386,7 +388,9 @@ struct CalcTests {
386388 }
387389
388390 @Test func unsupported() throws {
389 for e in ["sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1",
391 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
392 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
393 "sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1",
390394 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
391395 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
392396 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
@@ -422,6 +426,19 @@ struct CalcTests {
422426 // `calc-eval` with `num`: a formula is an error, unless Calc explains it.
423427 #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) }
424428 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) }
429 // Calc explains what a quotient, power or function rejected, even when it cancels.
430 for e in ["x^2/x", "x*x/x", "inf+(1/0)", "x/2", "abs(x)", "x%2"] {
431 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
432 }
433 for e in ["-x", "x*2", "2 x", "x+2-2", "nan"] {
434 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
435 }
436 #expect(try Calc.evaluate("x/x", numeric: true) == "1")
437 // Digits and points read as one number, at the position Calc gives.
438 for (e, position) in [("21.11.2026+1", 10), ("(21.11.2026)+1", 11), ("1.5.+1", 4), (".5.5", 4), ("3.14.15", 7),
439 ("192.168.1.1", 11), ("1.2.3x", 5), ("1.5.", 4)] {
440 #expect(throws: Calc.Failure("Bad format", position: position), "\(e)") { try Calc.evaluate(e) }
441 }
425442 var symbolic = Calc.Modes()
426443 symbolic.symbolic = true
427444 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] {
Tests/OrgCoreTests/TableFormulaTests.swift +25 −5
@@ -96,11 +96,30 @@ struct TableFormulaTests {
9696 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n",
9797 "| a | b | c | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n",
9898 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n",
99 // Calc rejects a number with two points.
100 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
101 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
102 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x;T\n",
99103 ]
100104
105 /// A range of one field with a space is a vector without commas, which Calc splits at the
106 /// space; a power or quotient left symbolic under a duration flag has Calc's explanation.
107 @Test func refusesWhatCalcReadsOrExplainsDifferently() {
108 for text in [
109 "| a | b | c |\n|---+---+---|\n| 5 kg | | |\n#+TBLFM: $3=vsum($1..$2)\n",
110 "| a | b | c |\n|---+---+---|\n| 1 2 | | |\n#+TBLFM: $3=vsum($1..$2)\n",
111 "| a | b |\n|---+---|\n| N A | |\n| | |\n#+TBLFM: @2$2=vmean(@2$1..@3$1)\n",
112 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x^2/x;T\n",
113 ] {
114 let caret = (text as NSString).range(of: "#+TBLFM").location + 3
115 let failure = Self.recalculate(TableRecalculate(all: true), text, caret: caret).failure ?? ""
116 #expect(failure.hasPrefix("external:"), "\(failure) in\n\(text)")
117 }
118 }
119
101120 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
102121 func textAndBlankFieldsMatchEmacsNatively() throws {
103 try compare(Self.symbolic, fallbacksAllowed: false)
122 try compare(Self.symbolic, fallbacksAllowed: false, headerFallbacksAllowed: false)
104123 }
105124
106125 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -164,7 +183,9 @@ struct TableFormulaTests {
164183 try compare(Self.lisp, fallbacksAllowed: false)
165184 }
166185
167 func compare(_ tables: [String], fallbacksAllowed: Bool) throws {
186 /// With `headerFallbacksAllowed`, a formula Calc would leave symbolic over a header's
187 /// text may go to Emacs even when other fallbacks aren't allowed.
188 func compare(_ tables: [String], fallbacksAllowed: Bool, headerFallbacksAllowed: Bool = true) throws {
168189 var cases: [EmacsOracle.Case] = []
169190 var ours: [(text: String, caret: Int, failure: String?)] = []
170191 for text in tables {
@@ -184,9 +205,8 @@ struct TableFormulaTests {
184205 for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
185206 if let failure = mine.failure, failure.hasPrefix("external:") {
186207 fallbacks += 1
187 // Formulas over a header's text that Calc would leave symbolic in ways not
188 // reproduced go to Emacs.
189 #expect(fallbacksAllowed || failure.contains("symbolic") || failure.contains("of a formula"), "\(failure) in\n\(cases[i].text)")
208 let header = failure.contains("symbolic") || failure.contains("of a formula")
209 #expect(fallbacksAllowed || (headerFallbacksAllowed && header), "\(failure) in\n\(cases[i].text)")
190210 continue
191211 }
192212 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
docs/manual/guide/10-tables.org +4
@@ -234,6 +234,10 @@ and are left out of ranges.
234234A field's text goes into the formula as it is, so a field holding text such as =N/A= or
235235=TBD= becomes Calc variables and the result is a formula: =$1+5= with =N/A= in =$1=
236236gives =N / A + 5=. The =N= flag reads every field as a number instead, with text as 0.
237A field such as =21.11.2026= or =192.168.1.1=, with more than one decimal point, is
238=#ERROR=, as Calc can't read it as a number. A range whose only non-empty field holds
239text with a space, such as =5 kg=, needs Emacs: Calc reads a vector without commas as
240elements separated by spaces.
237241
238242** Names, parameters and constants
239243