oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1package calc
2
3import "math"
4
5// fn_ref.go: ROW, COLUMN and INT. ROW and COLUMN report a position, not a
6// value: with a reference argument they read its top-left cell's
7// position straight off the AST (never env.CellValue — the referenced
8// cell's content is irrelevant), and with no argument they need the cell
9// the formula itself lives in, which only the dependency graph knows (see
10// callerEnv). That is why they are nodeFuncs. INT sits here because the
11// positional formulas ROW/COLUMN exist for (week/day grids, "every Nth
12// row") are its usual company.
13
14func init() {
15 registerNode("ROW", fnRow)
16 registerNode("COLUMN", fnColumn)
17 Register("INT", fnInt)
18}
19
20// callerEnv is the optional interface an Env implements when it knows
21// which cell is being evaluated. The graph's per-cell view (cellEnv,
22// graph_recalc.go) does; a bare Env evaluating a free-standing formula
23// does not, and ROW()/COLUMN() with no argument is #VALUE! there.
24type callerEnv interface {
25 Caller() (CellKey, bool)
26}
27
28func fnRow(argNodes []Node, env Env) Value {
29 return positionOf(argNodes, env, true)
30}
31
32func fnColumn(argNodes []Node, env Env) Value {
33 return positionOf(argNodes, env, false)
34}
35
36// positionOf is ROW/COLUMN's shared body: the 1-based row (or column) of
37// the argument's top-left cell, or of the calling cell when there is no
38// argument. A non-reference argument is #VALUE!.
39func positionOf(argNodes []Node, env Env, row bool) Value {
40 var r, c int
41 switch len(argNodes) {
42 case 0:
43 ce, ok := env.(callerEnv)
44 if !ok {
45 return errValue(ErrValue)
46 }
47 k, ok := ce.Caller()
48 if !ok {
49 return errValue(ErrValue)
50 }
51 r, c = int(k.RowID)-1, int(k.ColID)-1
52 case 1:
53 switch a := argNodes[0].(type) {
54 case *Ref:
55 r, c = a.RowPos, a.ColPos
56 case *Range:
57 r, _, c, _ = rangeBounds(a)
58 default:
59 return errValue(ErrValue)
60 }
61 default:
62 return errValue(ErrValue)
63 }
64 if row {
65 return Value{Kind: KindNum, Num: float64(r + 1)}
66 }
67 return Value{Kind: KindNum, Num: float64(c + 1)}
68}
69
70// fnInt implements INT(number): round down to the nearest integer, so
71// negative numbers move away from zero (INT(-1.5) = -2), as in Excel.
72func fnInt(args []Value) Value {
73 if len(args) != 1 {
74 return errValue(ErrValue)
75 }
76 if args[0].Kind == KindErr {
77 return args[0]
78 }
79 x, ek := toNumber(args[0])
80 if ek != ErrNone {
81 return errValue(ek)
82 }
83 return Value{Kind: KindNum, Num: math.Floor(x)}
84}
85