| 1 | package xlsx |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | |
| 6 | "amadan.net/oficina/sheets/internal/sheets/calc" |
| 7 | ) |
| 8 | |
| 9 | // formulaClass is what import decides about one workbook formula. |
| 10 | type formulaClass struct { |
| 11 | // Supported is true when the formula is kept as a formula: it |
| 12 | // parses, and every function it calls is one this engine has. |
| 13 | Supported bool |
| 14 | // Volatile is true when a kept formula reads the clock, so its |
| 15 | // saved value was computed at another moment and is not compared. |
| 16 | Volatile bool |
| 17 | // Code says why an unsupported formula is not kept. |
| 18 | Code Code |
| 19 | } |
| 20 | |
| 21 | // classify decides whether formula (excelize's text, no leading "=") |
| 22 | // stays a formula, given the type its <f> element declared. |
| 23 | // |
| 24 | // Order matters only for which reason a report names; any one of them |
| 25 | // is enough to freeze the cell. The textual checks come before the |
| 26 | // parser on purpose: a sheet-qualified or external reference must not |
| 27 | // be kept even if a later parser learned to read one, because only |
| 28 | // the first worksheet comes across and the reference would point at |
| 29 | // nothing. |
| 30 | func classify(formula, fType string) formulaClass { |
| 31 | if fType == "array" || fType == "dataTable" { |
| 32 | return formulaClass{Code: FormulaArray} |
| 33 | } |
| 34 | bare := outsideStrings(formula) |
| 35 | if strings.Contains(strings.ToUpper(bare), "__XLUDF.") { |
| 36 | return formulaClass{Code: FormulaGoogleOnly} |
| 37 | } |
| 38 | if strings.ContainsAny(bare, "![") { |
| 39 | return formulaClass{Code: FormulaOtherSheet} |
| 40 | } |
| 41 | node, err := calc.Parse(formula) |
| 42 | if err != nil { |
| 43 | return formulaClass{Code: FormulaUnsupported} |
| 44 | } |
| 45 | in := calc.Inspect(node) |
| 46 | if in.Unknown { |
| 47 | return formulaClass{Code: FormulaUnsupported} |
| 48 | } |
| 49 | return formulaClass{Supported: true, Volatile: in.Volatile} |
| 50 | } |
| 51 | |
| 52 | // outsideStrings is formula with the contents of its double-quoted |
| 53 | // string constants removed, so text inside a string ("Sheet2!A1" as a |
| 54 | // label) cannot read as a reference. A doubled quote inside a string |
| 55 | // toggles twice and so stays inside it. |
| 56 | func outsideStrings(formula string) string { |
| 57 | var b strings.Builder |
| 58 | in := false |
| 59 | for i := 0; i < len(formula); i++ { |
| 60 | c := formula[i] |
| 61 | if c == '"' { |
| 62 | in = !in |
| 63 | continue |
| 64 | } |
| 65 | if !in { |
| 66 | b.WriteByte(c) |
| 67 | } |
| 68 | } |
| 69 | return b.String() |
| 70 | } |
| 71 | |