forked from ricklamers/gridstudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
1684 lines (1254 loc) · 43.5 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"fmt"
"log"
"math"
"math/rand"
"regexp"
"strconv"
"strings"
"unicode"
matrix "github.com/skelterjohn/go.matrix"
)
const DynamicValueTypeFormula int8 = 0
const DynamicValueTypeReference int8 = 1
const DynamicValueTypeFloat int8 = 3
const DynamicValueTypeString int8 = 4
const DynamicValueTypeBool int8 = 5
const DynamicValueTypeExplosiveFormula int8 = 6
const DynamicValueTypeOperator int8 = 7
type DynamicValue struct {
ValueType int8
DataFloat float64
DataString string
DataBool bool
DataFormula string
SheetIndex int8
DependIn map[string]bool
DependOut map[string]bool
DependInTemp map[string]bool
DependOutTemp map[string]bool
}
var numberOnlyReg *regexp.Regexp
var numberOnlyFilter *regexp.Regexp
var availableOperators []string
var maxOperatorSize int
var operatorsBroken []map[string]int
var breakChars []string
func makeEmptyDv() *DynamicValue {
dv := DynamicValue{}
dv.DependIn = make(map[string]bool)
dv.DependOut = make(map[string]bool)
return &dv
}
func makeDv(formula string) *DynamicValue {
dv := DynamicValue{ValueType: DynamicValueTypeFormula, DataFormula: formula}
dv.DependIn = make(map[string]bool)
dv.DependOut = make(map[string]bool)
return &dv
}
func parseInit() {
availableOperators = []string{"^", "*", "/", "+", "-", ">", "<", ">=", "<=", "==", "<>", "!="}
breakChars = []string{" ", ")", ",", "*", "/", "+", "-", ">", "<", "=", "^"}
// loop over availableOperators twice: once to find maxOperatorSize to initialize hashmaps, once to fill hashmaps
for _, e := range availableOperators {
if len(e) > maxOperatorSize {
maxOperatorSize = len(e)
}
}
// create empty hashmap array
operatorsBroken = []map[string]int{}
// initialize hashmaps
for i := 0; i < maxOperatorSize; i++ {
operatorsBroken = append(operatorsBroken, make(map[string]int))
}
for _, e := range availableOperators {
// determine target hashmap
index := len(e)
// assign hashmap value
operatorsBroken[index-1][e] = 1
}
numberOnlyReg, _ = regexp.Compile("[^0-9]+")
numberOnlyFilter, _ = regexp.Compile(`^-?[0-9]\d*(\.\d+)?$`)
}
func getData(ref1 DynamicValue, grid *Grid) *DynamicValue {
return (grid.Data)[ref1.DataString]
}
func getDataFromRef(reference Reference, grid *Grid) *DynamicValue {
return grid.Data[getMapIndexFromReference(reference)]
}
func checkDataPresenceFromRef(reference Reference, grid *Grid) bool {
_, ok := grid.Data[getMapIndexFromReference(reference)]
return ok
}
func getReferenceFromString(formula string, sheetIndex int8, grid *Grid) Reference {
if !strings.Contains(formula, "!") {
return Reference{String: formula, SheetIndex: sheetIndex}
} else {
splittedFormula := strings.Split(formula, "!")
sheetName := strings.Replace(splittedFormula[0], "'", "", -1)
return Reference{String: splittedFormula[1], SheetIndex: grid.SheetNames[sheetName]}
}
}
func getRangeReferenceFromString(formula string, sheetIndex int8, grid *Grid) ReferenceRange {
if !strings.Contains(formula, "!") {
return ReferenceRange{String: formula, SheetIndex: sheetIndex}
} else {
splittedFormula := strings.Split(formula, "!")
sheetName := strings.Replace(splittedFormula[0], "'", "", -1)
return ReferenceRange{String: splittedFormula[1], SheetIndex: grid.SheetNames[sheetName]}
}
}
func referenceRangeToRelativeString(referenceRange ReferenceRange, sheetIndex int8, grid *Grid) string {
if referenceRange.SheetIndex == sheetIndex {
return referenceRange.String
} else {
return getPrefixFromSheetName(grid.SheetList[referenceRange.SheetIndex]) + "!" + referenceRange.String
}
}
func referenceToRelativeString(reference Reference, sheetIndex int8, grid *Grid) string {
if reference.SheetIndex == sheetIndex {
return reference.String
} else {
return getPrefixFromSheetName(grid.SheetList[reference.SheetIndex]) + "!" + reference.String
}
}
func getPrefixFromSheetName(sheetName string) string {
if strings.Contains(sheetName, " ") {
return "'" + sheetName + "'"
} else {
return sheetName
}
}
func checkIfRefExists(reference Reference, grid *Grid) bool {
if _, ok := grid.Data[getMapIndexFromReference(reference)]; ok {
return true
}
return false
}
func getDataByNormalRef(ref string, grid *Grid) *DynamicValue {
return grid.Data[ref]
}
func setDataByRef(reference Reference, dv *DynamicValue, grid *Grid) {
dv.SheetIndex = reference.SheetIndex
mapIndex := getMapIndexFromReference(reference)
grid.Data[mapIndex] = dv
}
func findInMap(amap map[int]string, value string) bool {
for _, e := range amap {
if e == value {
return true
}
}
return false
}
func addToReferenceReplaceMap(reference string, incrementAmount int, references *map[string]string) {
// exclude from increment any reference with $ in it
if !strings.Contains(reference, "$") {
referenceRow := getReferenceRowIndex(reference)
referenceColumn := getReferenceColumnIndex(reference)
referenceRow = referenceRow + incrementAmount
newReference := indexToLetters(referenceColumn) + strconv.Itoa(referenceRow)
(*references)[reference] = newReference
}
}
func findReferenceStrings(formula string) []string {
references := []string{}
// loop over string, if double quote is found, ignore input for references,
quoteLevel := 0
singleQuoteLevel := 0
previousChar := ""
var buf bytes.Buffer
for _, c := range formula {
char := string(c)
if char == "\"" && previousChar != "\\" {
if quoteLevel == 0 {
quoteLevel++
} else {
buf.Reset()
quoteLevel--
continue
}
}
if c == '\'' && singleQuoteLevel == 0 {
singleQuoteLevel++
} else if c == '\'' && singleQuoteLevel == 1 {
singleQuoteLevel--
}
if quoteLevel == 0 && singleQuoteLevel == 1 {
buf.WriteString(char)
}
if quoteLevel == 0 && singleQuoteLevel == 0 {
// assume everything not in quotes is a reference
// if we find open brace it must be a function name
if char == "(" {
buf.Reset()
continue
} else if contains(breakChars, char) {
if buf.Len() > 0 {
// found space, previous is references
references = append(references, buf.String())
buf.Reset()
}
// never add break char to reference
continue
}
// edge case for number, if first char of buffer is number, can't be reference
if buf.Len() == 0 {
if unicode.IsDigit(c) || char == "." { // check for both numbers and . character
// found number can't be reference
buf.Reset()
continue
}
}
buf.WriteString(char)
}
previousChar = char
}
// at the end also add as reference
if buf.Len() > 0 {
references = append(references, buf.String())
}
// filter references for known keywords such as TRUE/FALSE
for k, reference := range references {
if len(references) > 0 {
if reference == "TRUE" || reference == "FALSE" {
references = append(references[:k], references[k+1:]...)
}
}
}
return references
}
func findRanges(formula string, sheetIndex int8, grid *Grid) []ReferenceRange {
rangeReferences := []ReferenceRange{}
referenceStrings := findReferenceStrings(formula)
// expand references when necessary
for _, referenceString := range referenceStrings {
if strings.Contains(referenceString, ":") {
rangeReferences = append(rangeReferences, getRangeReferenceFromString(referenceString, sheetIndex, grid))
}
}
return rangeReferences
}
func findReferences(formula string, sheetIndex int8, includeRanges bool, grid *Grid) map[Reference]bool {
referenceStrings := findReferenceStrings(formula)
references := []Reference{}
// expand references when necessary
for _, referenceString := range referenceStrings {
if strings.Contains(referenceString, ":") {
if includeRanges {
references = append(references, cellRangeToCells(getRangeReferenceFromString(referenceString, sheetIndex, grid))...)
}
} else {
references = append(references, getReferenceFromString(referenceString, sheetIndex, grid))
}
}
finalMap := make(map[Reference]bool)
for _, reference := range references {
finalMap[reference] = true
}
return finalMap
}
func referencesToUpperCase(formula string) string {
// loop over string, if double quote is found, ignore input for references,
quoteLevel := 0
previousChar := ""
var buf bytes.Buffer
for k, c := range formula {
char := string(c)
if char == "\"" && previousChar != "\\" {
if quoteLevel == 0 {
quoteLevel++
} else {
buf.Reset()
quoteLevel--
continue
}
}
if quoteLevel == 0 {
// assume everything not in quotes is a reference
// if we find open brace it must be a function name
if char == "(" {
buf.Reset()
continue
} else if contains(breakChars, char) {
if buf.Len() > 0 {
// found space, previous is references
// buf is reference, replace buf with uppercase version
formula = formula[:k-buf.Len()] + strings.ToUpper(buf.String()) + formula[k:]
buf.Reset()
}
// never add break char to reference
continue
}
// edge case for number, if first char of buffer is number, can't be reference
if buf.Len() == 0 {
_, err := strconv.Atoi(char)
if err == nil || char == "." { // check for both numbers and . character
// found number can't be reference
buf.Reset()
continue
}
}
buf.WriteString(char)
}
previousChar = char
}
// at the end also add as reference
if buf.Len() > 0 {
formula = formula[:len(formula)-buf.Len()] + strings.ToUpper(buf.String()) + formula[len(formula):]
}
return formula
}
func cellRangeToCells(referenceRange ReferenceRange) []Reference {
references := []Reference{}
cell1Row, cell1Column, cell2Row, cell2Column := cellRangeBoundaries(referenceRange.String)
// illegal argument, cell1Row should always be lower
if cell1Row > cell2Row {
return references
}
// illegal argument, cell1Column should always be lower
if cell1Column > cell2Column {
return references
}
// all equals means just one cell, example: A1:A2
// if cell1Row == cell2Row && cell1Column == cell2Column {
// references = append(references, indexToLetters(cell1Column)+strconv.Itoa(cell1Row))
// return references
// }
for x := cell1Column; x <= cell2Column; x++ {
for y := cell1Row; y <= cell2Row; y++ {
references = append(references, Reference{String: indexToLetters(x) + strconv.Itoa(y), SheetIndex: referenceRange.SheetIndex})
}
}
return references
}
func setDependencies(reference Reference, dv *DynamicValue, grid *Grid) *DynamicValue {
standardIndex := getMapIndexFromReference(reference)
var references map[Reference]bool
// explosiveFormulas never have dependencies
if dv.ValueType == DynamicValueTypeExplosiveFormula {
references = make(map[Reference]bool)
} else {
references = findReferences(dv.DataFormula, reference.SheetIndex, true, grid)
}
// every cell that this depended on needs to get removed
referenceDv := getDataFromRef(reference, grid)
for ref := range referenceDv.DependIn {
delete(getDataByNormalRef(ref, grid).DependOut, standardIndex)
}
// always clear incoming references, if they still exist
dv.DependIn = make(map[string]bool)
for thisRef, inSet := range references {
// when findReferences is called and a reference is not in grid.Data[] the reference is invalid
if checkIfRefExists(thisRef, grid) {
thisDv := getDataFromRef(thisRef, grid)
// for dependency checking get rid of dollar signs in references
thisDvStandardRef := getMapIndexFromReference(thisRef)
if inSet {
// if thisRef == reference {
// // cell is dependent on self
// fmt.Println("Circular reference error!")
// dv.ValueType = DynamicValueTypeString
// dv.DataFormula = "\"#Error, circular reference: " + dv.DataFormula + "\""
// } else {
// }
dv.DependIn[thisDvStandardRef] = true
thisDv.DependOut[standardIndex] = true
// copy
// copyToDirty(thisDvStandardRef, grid)
}
} else {
dv.DataFormula = "\"#REF: " + referenceToRelativeString(thisRef, reference.SheetIndex, grid) + "\""
}
}
// always add self to dirty (after setting references DependIn for self - loop above)
copyToDirty(standardIndex, grid)
// // mark all cells dirty that depend on this cell
// for ref, inSet := range dv.DependOut {
// if inSet {
// dv := (grid.Data)[ref]
// copyToDirty(dv, ref, grid)
// }
// }
return dv
}
func containsReferences(s []Reference, e Reference) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func copyDv(dv *DynamicValue) *DynamicValue {
newDv := DynamicValue{}
newDv.DataBool = dv.DataBool
newDv.DataFloat = dv.DataFloat
newDv.DataString = dv.DataString
newDv.DataFormula = dv.DataFormula
newDv.SheetIndex = dv.SheetIndex
newDv.ValueType = dv.ValueType
return &newDv
}
// func copyToDv(sourceDv *DynamicValue, targetDv *DynamicValue) {
// // note: DependOut and DependIn are unmodified - need to be done by setDependencies
// targetDv.DataBool = sourceDv.DataBool
// targetDv.DataFloat = sourceDv.DataFloat
// targetDv.DataString = sourceDv.DataString
// targetDv.DataFormula = sourceDv.DataFormula
// targetDv.SheetIndex = sourceDv.SheetIndex
// targetDv.ValueType = sourceDv.ValueType
// }
func parse(formula *DynamicValue, grid *Grid, targetRef Reference) *DynamicValue {
if formula.ValueType == DynamicValueTypeFloat {
return formula
}
if formula.ValueType == DynamicValueTypeFormula && len(formula.DataFormula) == 0 {
formula.DataString = ""
formula.ValueType = DynamicValueTypeString
return formula
}
elements := []*DynamicValue{}
operatorsFound := []string{}
parenDepth := 0
quoteDepth := 0
previousChar := ""
var buffer bytes.Buffer
// TODO: instead of writing to buffer keep track of indexes for efficiency
skipCharacters := 0
for k, r := range formula.DataFormula {
c := string(r)
if skipCharacters > 0 {
skipCharacters--
continue
} else {
// check for quotes
if c == "\"" && quoteDepth == 0 && previousChar != "\\" {
quoteDepth++
} else if c == "\"" && quoteDepth == 1 && previousChar != "\\" {
quoteDepth--
}
if quoteDepth == 0 {
if c == "(" {
parenDepth++
} else if c == ")" {
parenDepth--
if parenDepth < 0 {
log.Fatal("Invalid input string")
}
} else if parenDepth == 0 {
identifiedOperator := ""
// never check first operator (could be minus sign)
currentTrimmedBuffer := strings.TrimSpace(buffer.String())
// first char and equals - or previous element is operator and this is minus
// first check is for first character equals minus sign,
// second check is for a minus sign directly after an operator to indicate that the following term is negative
if !((k == 0 && c == "-") ||
(c == "-" && len(elements) > 0 &&
elements[len(elements)-1].ValueType == DynamicValueTypeOperator &&
len(currentTrimmedBuffer) == 0)) {
for i := 0; i < maxOperatorSize; i++ {
// condition 1: never check beyond length of original formula
// condition 2: identfy whether operator is in hashmapped operator data structure for high performance
// first check for operators of size 1, then for operators of size 2, etc
if (k+i+1) <= len(formula.DataFormula)-1 && operatorsBroken[i][formula.DataFormula[k:k+i+1]] == 1 {
identifiedOperator = formula.DataFormula[k : k+i+1]
}
}
if len(identifiedOperator) > 0 {
// add to elements everything in buffer before operator
newDv := DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeFormula, DataFormula: strings.TrimSpace(buffer.String())}
elements = append(elements, &newDv)
newDv2 := DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeOperator, DataFormula: identifiedOperator}
// add operator to elements
elements = append(elements, &newDv2)
skipCharacters = len(identifiedOperator) - 1
// append operator to found operators, if not already in there
if !contains(operatorsFound, identifiedOperator) {
operatorsFound = append(operatorsFound, identifiedOperator)
}
// reset buffer
buffer.Reset()
continue
}
}
}
}
buffer.WriteString(c)
}
previousChar = c
}
newDv := DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeFormula, DataFormula: strings.TrimSpace(buffer.String())}
elements = append(elements, &newDv)
// if first and last element in elements are parens, remove parens
for k, e := range elements {
if e.ValueType == DynamicValueTypeFormula {
if len(e.DataFormula) > 0 {
if e.DataFormula[0:1] == "(" && e.DataFormula[len(e.DataFormula)-1:len(e.DataFormula)] == ")" {
e.DataFormula = e.DataFormula[1 : len(e.DataFormula)-1]
elements[k] = e
// after remove braces, parse this element
elements[k] = parse(e, grid, targetRef)
// for single elements return at this point
if len(elements) == 1 {
return elements[k]
}
}
}
}
}
if len(elements) == 1 {
singleElement := elements[0]
if isFunction(singleElement.DataFormula) {
parenIndex := strings.Index(singleElement.DataFormula, "(")
command := singleElement.DataFormula[0:parenIndex]
// modify arguments function
argumentString := singleElement.DataFormula[parenIndex+1 : len(singleElement.DataFormula)-1]
var arguments []string
level := 0
quoteLevel := 0
var buffer bytes.Buffer
for _, r := range argumentString {
c := string(r)
// valid delimeters
// go down level: " (
// go up level: " )
if c == "(" {
level++
} else if c == ")" {
level--
} else if c == "\"" && quoteLevel == 0 {
level++
quoteLevel++
} else if c == "\"" && quoteLevel == 1 {
level--
quoteLevel--
}
if level == 0 {
if c == "," {
arguments = append(arguments, strings.TrimSpace(buffer.String()))
buffer.Reset()
continue
}
}
buffer.WriteString(c)
}
bufferRemainder := strings.TrimSpace(buffer.String())
if len(bufferRemainder) > 0 {
arguments = append(arguments, bufferRemainder)
}
argumentFormulas := []*DynamicValue{}
for _, e := range arguments {
newDv := DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeFormula, DataFormula: e}
argumentFormulas = append(argumentFormulas, parse(&newDv, grid, targetRef))
}
return executeCommand(command, argumentFormulas, grid, targetRef)
} else {
if singleElement.DataFormula[0:1] == "\"" && singleElement.DataFormula[len(singleElement.DataFormula)-1:len(singleElement.DataFormula)] == "\"" {
stringValue := singleElement.DataFormula[1 : len(singleElement.DataFormula)-1]
// unescape double quote
stringValue = strings.Replace(stringValue, "\\\"", "\"", -1)
return &DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeString, DataString: stringValue}
} else if strings.Index(singleElement.DataFormula, ":") != -1 {
cells := strings.Split(singleElement.DataFormula, ":")
if !((numberOnlyFilter.MatchString(cells[0]) && numberOnlyFilter.MatchString(cells[1])) ||
(!numberOnlyFilter.MatchString(cells[0]) && !numberOnlyFilter.MatchString(cells[1]))) {
log.Fatal("Wrong reference specifier")
} else {
return &DynamicValue{ValueType: DynamicValueTypeReference, SheetIndex: targetRef.SheetIndex, DataString: singleElement.DataFormula}
}
} else if numberOnlyFilter.MatchString(singleElement.DataFormula) {
floatValue, err := strconv.ParseFloat(singleElement.DataFormula, 64)
if err != nil {
log.Fatal(err)
}
return &DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeFloat, DataFloat: float64(floatValue)}
} else if singleElement.DataFormula == "FALSE" || singleElement.DataFormula == "TRUE" {
newDv := DynamicValue{SheetIndex: targetRef.SheetIndex, ValueType: DynamicValueTypeBool, DataBool: false}
if singleElement.DataFormula == "TRUE" {
newDv.DataBool = true
}
return &newDv
} else {
// when references contain dollar signs, remove them here
newDv := copyDv(getDataFromRef(getReferenceFromString(singleElement.DataFormula, targetRef.SheetIndex, grid), grid))
return newDv
}
}
} else {
// parse operators until top elements per formula reduced to 1
var operatorSets [][]string
operatorSets = [][]string{{"^"}, {"*", "/"}, {"+", "-"}, {">", "<", ">=", "<=", "==", "<>", "!="}}
for _, operatorSet := range operatorSets {
// more efficient would be to compare each element in operatorsFound to elements in operatorSet
operatorInSet := anyOperatorsInOperatorSet(operatorSet, operatorsFound)
if operatorInSet {
operatorLocation := findFirstOperatorOccurence(elements, operatorSet)
if operatorLocation == 0 {
log.Fatal("Operator can never be the first input in an array")
}
for operatorLocation != -1 {
LHS := parse(elements[operatorLocation-1], grid, targetRef)
RHS := parse(elements[operatorLocation+1], grid, targetRef)
var result DynamicValue
// todo implement operators for all possible data type combinations
// for now implement int and float as all float (* might actually be necessary for good performance (should compare int and float multiplication for large n in Golang))
operator := elements[operatorLocation].DataFormula
// if boolean operatorSet run boolean_compare
if contains(operatorSet, "<") {
result = booleanCompare(LHS, RHS, elements[operatorLocation].DataFormula)
} else {
// otherwise run numeric operator evaluation
if LHS.ValueType == DynamicValueTypeFloat && RHS.ValueType == DynamicValueTypeFloat {
// convert LHS and RHS to float
LHS = convertToFloat(LHS)
RHS = convertToFloat(RHS)
result = DynamicValue{ValueType: DynamicValueTypeFloat}
switch operator {
case "*":
result.DataFloat = LHS.DataFloat * RHS.DataFloat
case "/":
result.DataFloat = LHS.DataFloat / RHS.DataFloat
case "+":
result.DataFloat = LHS.DataFloat + RHS.DataFloat
case "-":
result.DataFloat = LHS.DataFloat - RHS.DataFloat
case "^":
result.DataFloat = float64(math.Pow(float64(LHS.DataFloat), float64(RHS.DataFloat)))
}
}
}
arrayEnd := elements[operatorLocation+2:]
elements = append(elements[:operatorLocation-1], &result)
elements = append(elements, arrayEnd...)
operatorLocation = findFirstOperatorOccurence(elements, operatorSet)
}
}
}
if len(elements) != 1 {
log.Fatal("Elements should be fully merged to 1 element")
}
return elements[0]
}
return formula
}
func anyOperatorsInOperatorSet(operatorSet []string, operatorsFound []string) bool {
// if no operators were found it can never be in the set
if len(operatorsFound) == 0 {
return false
}
for _, operatorInSet := range operatorSet {
for _, operatorFound := range operatorsFound {
if operatorInSet == operatorFound {
return true
}
}
}
return false
}
func dynamicToBool(A DynamicValue) bool {
if A.ValueType == DynamicValueTypeBool {
return A.DataBool
} else if A.ValueType == DynamicValueTypeFloat {
return A.DataFloat > 0
} else if A.ValueType == DynamicValueTypeString {
return len(A.DataString) > 0
} else {
return false
}
}
func booleanCompare(LHS *DynamicValue, RHS *DynamicValue, operator string) DynamicValue {
// for now, cast all values to float for comparison
var result DynamicValue
result.ValueType = DynamicValueTypeBool
// var A float64
// var B float64
// // boolean operators
// if LHS.ValueType == DynamicValueTypeBool {
// A = 0
// if LHS.DataBool {
// A = 1
// }
// }
// if LHS.ValueType == DynamicValueTypeFloat {
// A = LHS.DataFloat
// }
// if LHS.ValueType == DynamicValueTypeInteger {
// A = float64(LHS.DataInteger)
// }
// // parse RHS dynamically
// if RHS.ValueType == DynamicValueTypeBool {
// B = 0
// if RHS.DataBool {
// B = 1
// }
// }
// if RHS.ValueType == DynamicValueTypeFloat {
// B = RHS.DataFloat
// }
// if RHS.ValueType == DynamicValueTypeInteger {
// B = float64(RHS.DataInteger)
// }
switch operator {
case ">":
result.DataBool = compareDvsBigger(LHS, RHS)
case "<":
result.DataBool = compareDvsSmaller(LHS, RHS)
case ">=":
result.DataBool = compareDvsBigger(LHS, RHS) || (!compareDvsSmaller(LHS, RHS) && !compareDvsBigger(LHS, RHS))
case "<=":
result.DataBool = compareDvsSmaller(LHS, RHS) || (!compareDvsSmaller(LHS, RHS) && !compareDvsBigger(LHS, RHS))
case "==":
result.DataBool = (!compareDvsSmaller(LHS, RHS) && !compareDvsBigger(LHS, RHS))
case "!=":
result.DataBool = compareDvsSmaller(LHS, RHS) || compareDvsBigger(LHS, RHS)
case "<>":
result.DataBool = compareDvsSmaller(LHS, RHS) || compareDvsBigger(LHS, RHS)
}
return result
}
func filter(src []string) (res []string) {
for _, s := range src {
newStr := strings.Join(res, " ")
if !strings.Contains(newStr, s) {
res = append(res, s)
}
}
return
}
func intersections(section1, section2 []string) (intersection []string) {
str1 := strings.Join(filter(section1), " ")
for _, s := range filter(section2) {
if strings.Contains(str1, s) {
intersection = append(intersection, s)
}
}
return
}
func indexOfOperator(ds []*DynamicValue, s string) int {
for k, e := range ds {
if e.DataFormula == s {
return k
}
}
return -1
}
func findFirstOperatorOccurence(elements []*DynamicValue, operatorSet []string) int {
operatorLocation := math.MaxInt32
for d := 0; d < len(operatorSet); d++ {
index := indexOfOperator(elements, operatorSet[d])
if index != -1 && index < operatorLocation {
operatorLocation = index
}
}
if operatorLocation == math.MaxInt32 {
return -1