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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
|
/* This file is part of the KDE project
Copyright (C) 2003,2004 Ariya Hidayat <ariya@kde.org>
Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "formula.h"
#include "kspread_cell.h"
#include "kspread_sheet.h"
#include "kspread_doc.h"
#include "kspread_util.h"
#include "kspread_value.h"
#include "valuecalc.h"
#include "valueconverter.h"
#include "valueparser.h"
#include "functions.h"
#include <limits.h>
#include <tqregexp.h>
#include <tqstring.h>
#include <tqvaluevector.h>
#include <tqvaluestack.h>
#include <klocale.h>
/*
To understand how this formula engine works, please refer to the documentation
in file DESIGN.html.
Useful references:
- "Principles of Compiler Design", A.V.Aho, J.D.Ullman, Addison Wesley, 1978
- "Writing Interactive Compilers and Interpreters", P.J. Brown,
John Wiley and Sons, 1979.
- "The Theory and Practice of Compiler Writing", J.Tremblay, P.G.Sorenson,
McGraw-Hill, 1985.
- "The Java(TM) Virtual Machine Specification", T.Lindholm, F.Yellin,
Addison-Wesley, 1997.
- "Java Virtual Machine", J.Meyer, T.Downing, O'Reilly, 1997.
*/
/*
TODO - features:
- handle Intersection
- cell reference is made relative (absolute now)
- shared formula (different owner, same data)
- relative internal representation (independent of owner)
- OASIS support
TODO - optimizations:
- handle initial formula marker = (and +)
- reuse constant already in the pool
- reuse references already in the pool
- expression optimization (e.g. 1+2+A1 becomes 3+A1)
*/
namespace KSpread
{
class Opcode
{
public:
enum { Nop = 0, Load, Ref, Cell, Range, Function, Add, Sub, Neg, Mul, Div,
Pow, Concat, Not, Equal, Less, Greater };
unsigned type;
unsigned index;
Opcode(): type(Nop), index(0) {};
Opcode( unsigned t ): type(t), index(0) {};
Opcode( unsigned t, unsigned i ): type(t), index(i) {};
};
class Formula::Private
{
public:
Formula *formula;
Cell *cell;
Sheet *sheet;
bool dirty;
bool valid;
TQString expression;
TQValueVector<Opcode> codes;
TQValueVector<Value> constants;
};
class TokenStack : public TQValueVector<Token>
{
public:
TokenStack();
bool isEmpty() const;
unsigned itemCount() const;
void push( const Token& token );
Token pop();
const Token& top();
const Token& top( unsigned index );
private:
void ensureSpace();
unsigned topIndex;
};
}
using namespace KSpread;
// for null token
const Token Token::null;
// helper function: return operator of given token text
// e.g. "*" yields Operator::Asterisk, and so on
Token::Op KSpread::matchOperator( const TQString& text )
{
Token::Op result = Token::InvalidOp;
if( text.length() == 1 )
{
TQChar p = text[0];
switch( p.unicode() )
{
case '+': result = Token::Plus; break;
case '-': result = Token::Minus; break;
case '*': result = Token::Asterisk; break;
case '/': result = Token::Slash; break;
case '^': result = Token::Caret; break;
case ',': result = Token::Comma; break;
case ';': result = Token::Semicolon; break;
case '(': result = Token::LeftPar; break;
case ')': result = Token::RightPar; break;
case '&': result = Token::Ampersand; break;
case '=': result = Token::Equal; break;
case '<': result = Token::Less; break;
case '>': result = Token::Greater; break;
case '%': result = Token::Percent; break;
default : result = Token::InvalidOp; break;
}
}
if( text.length() == 2 )
{
if( text == "<>" ) result = Token::NotEqual;
if( text == "<=" ) result = Token::LessEqual;
if( text == ">=" ) result = Token::GreaterEqual;
if( text == "==" ) result = Token::Equal;
}
return result;
}
// helper function: give operator precedence
// e.g. "+" is 1 while "*" is 3
static int opPrecedence( Token::Op op )
{
int prec = -1;
switch( op )
{
case Token::Percent : prec = 8; break;
case Token::Caret : prec = 7; break;
case Token::Asterisk : prec = 5; break;
case Token::Slash : prec = 6; break;
case Token::Plus : prec = 3; break;
case Token::Minus : prec = 3; break;
case Token::Ampersand : prec = 2; break;
case Token::Equal : prec = 1; break;
case Token::NotEqual : prec = 1; break;
case Token::Less : prec = 1; break;
case Token::Greater : prec = 1; break;
case Token::LessEqual : prec = 1; break;
case Token::GreaterEqual : prec = 1; break;
case Token::Semicolon : prec = 0; break;
case Token::RightPar : prec = 0; break;
case Token::LeftPar : prec = -1; break;
default: prec = -1; break;
}
return prec;
}
// helper function
static Value tokenAsValue( const Token& token )
{
Value value;
if( token.isBoolean() ) value = Value( token.asBoolean() );
else if( token.isInteger() ) value = Value( token.asInteger() );
else if( token.isFloat() ) value = Value( token.asFloat() );
else if( token.isString() ) value = Value( token.asString() );
return value;
}
/**********************
Token
**********************/
// creates a token
Token::Token( Type type, const TQString& text, int pos )
{
m_type = type;
m_text = text;
m_pos = pos;
}
// copy constructor
Token::Token( const Token& token )
{
m_type = token.m_type;
m_text = token.m_text;
m_pos = token.m_pos;
}
// assignment operator
Token& Token::operator=( const Token& token )
{
m_type = token.m_type;
m_text = token.m_text;
m_pos = token.m_pos;
return *this;
}
bool Token::asBoolean() const
{
if( !isBoolean() ) return false;
return m_text.lower() == "true";
// FIXME check also for i18n version
}
long Token::asInteger() const
{
if( isInteger() ) return m_text.toLong();
else return 0;
}
double Token::asFloat() const
{
if( isFloat() ) return m_text.toDouble();
else return 0.0;
}
TQString Token::asString() const
{
if( isString() ) return m_text.mid( 1, m_text.length()-2 );
else return TQString();
}
Token::Op Token::asOperator() const
{
if( isOperator() ) return matchOperator( m_text );
else return InvalidOp;
}
TQString Token::sheetName() const
{
if( !isCell() && !isRange() ) return TQString();
int i = m_text.find( '!' );
if( i < 0 ) return TQString();
TQString sheet = m_text.left( i );
return sheet;
}
TQString Token::description() const
{
TQString desc;
switch (m_type )
{
case Boolean: desc = "Boolean"; break;
case Integer: desc = "Integer"; break;
case Float: desc = "Float"; break;
case String: desc = "String"; break;
case Identifier: desc = "Identifier"; break;
case Cell: desc = "Cell"; break;
case Range: desc = "Range"; break;
case Operator: desc = "Operator"; break;
default: desc = "Unknown"; break;
}
while( desc.length() < 10 ) desc.prepend( ' ' );
desc.prepend( " " );
desc.prepend( TQString::number( m_pos ) );
desc.append( " : " ).append( m_text );
return desc;
}
/**********************
TokenStack
**********************/
TokenStack::TokenStack(): TQValueVector<Token>()
{
topIndex = 0;
ensureSpace();
}
bool TokenStack::isEmpty() const
{
return topIndex == 0;
}
unsigned TokenStack::itemCount() const
{
return topIndex;
}
void TokenStack::push( const Token& token )
{
ensureSpace();
at( topIndex++ ) = token;
}
Token TokenStack::pop()
{
return (topIndex > 0 ) ? Token( at( --topIndex ) ) : Token();
}
const Token& TokenStack::top()
{
return top( 0 );
}
const Token& TokenStack::top( unsigned index )
{
if( topIndex > index )
return at( topIndex-index-1 );
return Token::null;
}
void TokenStack::ensureSpace()
{
while( topIndex >= size() )
resize( size() + 10 );
}
/**********************
FormulaPrivate
**********************/
// helper function: return true for valid identifier character
bool KSpread::isIdentifier( TQChar ch )
{
return ( ch.unicode() == '_' ) || (ch.unicode() == '$' ) || ( ch.isLetter() );
}
/**********************
Formula
**********************/
// Constructor
Formula::Formula (Sheet *sheet, Cell *cell)
{
d = new Private;
d->cell = cell;
d->sheet = sheet;
clear();
}
Formula::Formula()
{
d = new Private;
d->cell = 0;
d->sheet = 0;
clear();
}
// Destructor
Formula::~Formula()
{
delete d;
}
Cell* Formula::cell() const
{
return d->cell;
}
Sheet* Formula::sheet() const
{
return d->sheet;
}
// Sets a new expression for this formula.
// note that both the real lex and parse processes will happen later on
// when needed (i.e. "lazy parse"), for example during formula evaluation.
void Formula::setExpression( const TQString& expr )
{
d->expression = expr;
d->dirty = true;
d->valid = false;
}
// Returns the expression associated with this formula.
TQString Formula::expression() const
{
return d->expression;
}
// Returns the validity of the formula.
// note: empty formula is always invalid.
bool Formula::isValid() const
{
if( d->dirty )
{
KLocale* locale = d->cell ? d->cell->locale() : 0;
if ((!locale) && d->sheet)
locale = d->sheet->doc()->locale();
Tokens tokens = scan( d->expression, locale );
if( tokens.valid() )
compile( tokens );
else
d->valid = false;
}
return d->valid;
}
// Clears everything, also mark the formula as invalid.
void Formula::clear()
{
d->expression = TQString();
d->dirty = true;
d->valid = false;
d->constants.clear();
d->codes.clear();
}
// Returns list of token for the expression.
// this triggers again the lexical analysis step. it is however preferable
// (even when there's small performance penalty) because otherwise we need to
// store parsed tokens all the time which serves no good purpose.
Tokens Formula::tokens() const
{
KLocale* locale = d->cell ? d->cell->locale() : 0;
if ((!locale) && d->sheet)
locale = d->sheet->doc()->locale();
return scan( d->expression, locale );
}
Tokens Formula::scan( const TQString& expr, KLocale* locale ) const
{
// to hold the result
Tokens tokens;
// parsing state
enum { Start, Finish, Bad, InNumber, InDecimal, InExpIndicator, InExponent,
InString, InIdentifier, InCell, InRange, InSheetOrAreaName } state;
// use locale settings if specified
TQString thousand = locale ? locale->thousandsSeparator() : "";
TQString decimal = locale ? locale->decimalSymbol() : ".";
// initialize variables
state = Start;
unsigned int i = 0;
TQString ex = expr;
TQString tokenText;
int tokenStart = 0;
// first character must be equal sign (=)
if( ex[0] != '=' )
return tokens;
// but the scanner should not see this equal sign
ex.remove( 0, 1 );
// force a terminator
ex.append( TQChar() );
// main loop
while( (state != Bad) && (state != Finish) && (i < ex.length()) )
{
TQChar ch = ex[i];
switch( state )
{
case Start:
tokenStart = i;
// skip any whitespaces
if( ch.isSpace() ) i++;
// check for number
else if( ch.isDigit() )
{
state = InNumber;
}
// a string ?
else if ( ch == '"' )
{
tokenText.append( ex[i++] );
state = InString;
}
// beginning with alphanumeric ?
// could be identifier, cell, range, or function...
else if( isIdentifier( ch ) )
{
state = InIdentifier;
}
// aposthrophe (') marks sheet name for 3-d cell, e.g 'Sales Q3'!A4, or a named range
else if ( ch.unicode() == '\'' )
{
i++;
state = InSheetOrAreaName;
}
// decimal dot ?
else if ( ch == decimal )
{
tokenText.append( ex[i++] );
state = InDecimal;
}
// terminator character
else if ( ch == TQChar::null )
state = Finish;
// look for operator match
else
{
int op;
TQString s;
// check for two-chars operator, such as '<=', '>=', etc
s.append( ch ).append( ex[i+1] );
op = matchOperator( s );
// check for one-char operator, such as '+', ';', etc
if( op == Token::InvalidOp )
{
s = TQString( ch );
op = matchOperator( s );
}
// any matched operator ?
if( op != Token::InvalidOp )
{
int len = s.length();
i += len;
tokens.append( Token( Token::Operator, s.left( len ), tokenStart ) );
}
else state = Bad;
}
break;
case InIdentifier:
// consume as long as alpha, dollar sign, underscore, or digit
if( isIdentifier( ch ) || ch.isDigit() ) tokenText.append( ex[i++] );
// a '!' ? then this must be sheet name, e.g "Sheet4!"
else if( ch == '!' )
{
tokenText.append( ex[i++] );
state = InCell;
}
// a '(' ? then this must be a function identifier
else if( ch == '(' )
{
tokens.append (Token (Token::Identifier, tokenText, tokenStart));
tokenStart = i;
tokenText = "";
state = Start;
}
// we're done with identifier
else
{
// check for cell reference, e.g A1, VV123, ...
TQRegExp exp("(\\$?)([a-zA-Z]+)(\\$?)([0-9]+)$");
int n = exp.search( tokenText );
if( n >= 0 )
state = InCell;
else
{
if ( isNamedArea( tokenText ) )
tokens.append (Token (Token::Range, tokenText, tokenStart));
else
tokens.append (Token (Token::Identifier, tokenText, tokenStart));
tokenStart = i;
tokenText = "";
state = Start;
}
}
break;
case InCell:
// consume as long as alpha, dollar sign, underscore, or digit
if( isIdentifier( ch ) || ch.isDigit() ) tokenText.append( ex[i++] );
// we're done with cell ref, possibly with sheet name (like "Sheet2!B2")
// note that "Sheet2!TotalSales" is also possible, in which "TotalSales" is a named area
else
{
// check if it's a cell ref like A32, not named area
TQString cell;
for( int j = tokenText.length()-1; j>=0; j-- )
if( tokenText[j] == '!' )
break;
else
cell.prepend( tokenText[j] );
TQRegExp exp("(\\$?)([a-zA-Z]+)(\\$?)([0-9]+)$");
if( exp.search( cell ) != 0 )
{
// we're done with named area
// (Tomas) huh? this doesn't seem to check for named areas ...
tokens.append( Token( Token::Range, tokenText, tokenStart ) );
tokenText = "";
state = Start;
}
else
{
// so up to now we've got something like A2 or Sheet2!F4
// check for range reference
if( ch == ':' )
{
tokenText.append( ex[i++] );
state = InRange;
}
else
{
// we're done with cell reference
tokens.append( Token( Token::Cell, tokenText, tokenStart ) );
tokenText = "";
state = Start;
}
}
}
break;
case InRange:
// consume as long as alpha, dollar sign, underscore, or digit
if( isIdentifier( ch ) || ch.isDigit() ) tokenText.append( ex[i++] );
// we're done with range reference
else
{
tokens.append( Token( Token::Range, tokenText, tokenStart ) );
tokenText = "";
state = Start;
}
break;
case InSheetOrAreaName:
// consume until '
if ( ch.unicode() != '\'' )
tokenText.append( ex[i++] );
else
{
// eat the aposthrophe itself
++i;
// must be followed by '!' to be sheet name
if( ex[i] == '!' )
{
tokenText.append( ex[i++] );
state = InCell;
}
else
{
if ( isNamedArea( tokenText ) )
tokens.append (Token (Token::Range, tokenText, tokenStart));
else
tokens.append (Token (Token::Identifier, tokenText, tokenStart));
tokenStart = i;
tokenText = "";
state = Start;
}
}
break;
case InNumber:
// consume as long as it's digit
if( ch.isDigit() ) tokenText.append( ex[i++] );
// skip thousand separator
else if( !thousand.isEmpty() && ( ch ==thousand[0] ) ) i++;
// convert decimal separator to '.', also support '.' directly
// we always support '.' because of bug #98455
else if(( !decimal.isEmpty() && ( ch == decimal[0] ) ) || (ch == '.'))
{
tokenText.append( '.' );
i++;
state = InDecimal;
}
// exponent ?
else if( ch.upper() == 'E' )
{
tokenText.append( 'E' );
i++;
state = InExpIndicator;
}
// reference sheet delimiter?
else if( ch == '!' )
{
tokenText.append( ex[i++] );
state = InCell;
}
// identifier?
else if( isIdentifier( ch ) )
{
// has to be a sheet or area name then
state = InIdentifier;
}
// we're done with integer number
else
{
tokens.append( Token( Token::Integer, tokenText, tokenStart ) );
tokenText = "";
state = Start;
};
break;
case InDecimal:
// consume as long as it's digit
if( ch.isDigit() ) tokenText.append( ex[i++] );
// exponent ?
else if( ch.upper() == 'E' )
{
tokenText.append( 'E' );
i++;
state = InExpIndicator;
}
// we're done with floating-point number
else
{
tokens.append( Token( Token::Float, tokenText, tokenStart ) );
tokenText = "";
state = Start;
};
break;
case InExpIndicator:
// possible + or - right after E, e.g 1.23E+12 or 4.67E-8
if( ( ch == '+' ) || ( ch == '-' ) ) tokenText.append( ex[i++] );
// consume as long as it's digit
else if( ch.isDigit() ) state = InExponent;
// invalid thing here
else state = Bad;
break;
case InExponent:
// consume as long as it's digit
if( ch.isDigit() ) tokenText.append( ex[i++] );
// we're done with floating-point number
else
{
tokens.append( Token( Token::Float, tokenText, tokenStart ) );
tokenText = "";
state = Start;
};
break;
case InString:
// consume until "
if( ch != '"' ) tokenText.append( ex[i++] );
else
{
tokenText.append( ch ); i++;
tokens.append( Token( Token::String, tokenText, tokenStart ) );
tokenText = "";
state = Start;
}
break;
case Bad:
default:
break;
};
};
if( state == Bad )
tokens.setValid( false );
return tokens;
}
// will affect: dirty, valid, codes, constants
void Formula::compile( const Tokens& tokens ) const
{
// initialize variables
d->dirty = false;
d->valid = false;
d->codes.clear();
d->constants.clear();
// sanity check
if( tokens.count() == 0 ) return;
TokenStack syntaxStack;
TQValueStack<int> argStack;
unsigned argCount = 1;
for( unsigned i = 0; i <= tokens.count(); i++ )
{
// helper token: InvalidOp is end-of-formula
Token token = ( i < tokens.count() ) ? tokens[i] : Token( Token::Operator );
Token::Type tokenType = token.type();
// unknown token is invalid
if( tokenType == Token::Unknown ) break;
// for constants, push immediately to stack
// generate code to load from a constant
if ( ( tokenType == Token::Integer ) || ( tokenType == Token::Float ) ||
( tokenType == Token::String ) || ( tokenType == Token::Boolean ) )
{
syntaxStack.push( token );
d->constants.append( tokenAsValue( token ) );
d->codes.append( Opcode( Opcode::Load, d->constants.count()-1 ) );
}
// for cell, range, or identifier, push immediately to stack
// generate code to load from reference
if( ( tokenType == Token::Cell ) || ( tokenType == Token::Range ) ||
( tokenType == Token::Identifier ) )
{
syntaxStack.push( token );
d->constants.append( Value( token.text() ) );
if (tokenType == Token::Cell)
d->codes.append( Opcode( Opcode::Cell, d->constants.count()-1 ) );
else if (tokenType == Token::Range)
d->codes.append( Opcode( Opcode::Range, d->constants.count()-1 ) );
else
d->codes.append( Opcode( Opcode::Ref, d->constants.count()-1 ) );
}
// are we entering a function ?
// if token is operator, and stack already has: id ( arg
if( tokenType == Token::Operator )
if( syntaxStack.itemCount() >= 3 )
{
Token arg = syntaxStack.top();
Token par = syntaxStack.top( 1 );
Token id = syntaxStack.top( 2 );
if( !arg.isOperator() )
if( par.asOperator() == Token::LeftPar )
if( id.isIdentifier() )
{
argStack.push( argCount );
argCount = 1;
}
}
// special case for percentage
if( tokenType == Token::Operator )
if( token.asOperator() == Token::Percent )
if( syntaxStack.itemCount() >= 1 )
if( !syntaxStack.top().isOperator() )
{
d->constants.append( Value( 0.01 ) );
d->codes.append( Opcode( Opcode::Load, d->constants.count()-1 ) );
d->codes.append( Opcode( Opcode::Mul ) );
}
// for any other operator, try to apply all parsing rules
if( tokenType == Token::Operator )
if( token.asOperator() != Token::Percent )
{
// repeat until no more rule applies
for( ; ; )
{
bool ruleFound = false;
// rule for function arguments, if token is ; or )
// id ( arg1 ; arg2 -> id ( arg
if( !ruleFound )
if( syntaxStack.itemCount() >= 5 )
if( ( token.asOperator() == Token::RightPar ) ||
( token.asOperator() == Token::Semicolon ) )
{
Token arg2 = syntaxStack.top();
Token sep = syntaxStack.top( 1 );
Token arg1 = syntaxStack.top( 2 );
Token par = syntaxStack.top( 3 );
Token id = syntaxStack.top( 4 );
if( !arg2.isOperator() )
if( sep.asOperator() == Token::Semicolon )
if( !arg1.isOperator() )
if( par.asOperator() == Token::LeftPar )
if( id.isIdentifier() )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
argCount++;
}
}
// rule for function last argument:
// id ( arg ) -> arg
if( !ruleFound )
if( syntaxStack.itemCount() >= 4 )
{
Token par2 = syntaxStack.top();
Token arg = syntaxStack.top( 1 );
Token par1 = syntaxStack.top( 2 );
Token id = syntaxStack.top( 3 );
if( par2.asOperator() == Token::RightPar )
if( !arg.isOperator() )
if( par1.asOperator() == Token::LeftPar )
if( id.isIdentifier() )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( arg );
d->codes.append( Opcode( Opcode::Function, argCount ) );
argCount = argStack.empty() ? 0 : argStack.pop();
}
}
// rule for function call with parentheses, but without argument
// e.g. "2*PI()"
if( !ruleFound )
if( syntaxStack.itemCount() >= 3 )
{
Token par2 = syntaxStack.top();
Token par1 = syntaxStack.top( 1 );
Token id = syntaxStack.top( 2 );
if( par2.asOperator() == Token::RightPar )
if( par1.asOperator() == Token::LeftPar )
if( id.isIdentifier() )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( Token( Token::Integer ) );
d->codes.append( Opcode( Opcode::Function, 0 ) );
}
}
// rule for parenthesis: ( Y ) -> Y
if( !ruleFound )
if( syntaxStack.itemCount() >= 3 )
{
Token right = syntaxStack.top();
Token y = syntaxStack.top( 1 );
Token left = syntaxStack.top( 2 );
if( right.isOperator() )
if( !y.isOperator() )
if( left.isOperator() )
if( right.asOperator() == Token::RightPar )
if( left.asOperator() == Token::LeftPar )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( y );
}
}
// rule for binary operator: A (op) B -> A
// conditions: precedence of op >= precedence of token
// action: push (op) to result
// e.g. "A * B" becomes "A" if token is operator "+"
// exception: for caret (power operator), if op is another caret
// then the rule doesn't apply, e.g. "2^3^2" is evaluated as "2^(3^2)"
if( !ruleFound )
if( syntaxStack.itemCount() >= 3 )
{
Token b = syntaxStack.top();
Token op = syntaxStack.top( 1 );
Token a = syntaxStack.top( 2 );
if( !a.isOperator() )
if( !b.isOperator() )
if( op.isOperator() )
if( token.asOperator() != Token::LeftPar )
if( token.asOperator() != Token::Caret )
if( opPrecedence( op.asOperator() ) >= opPrecedence( token.asOperator() ) )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( b );
switch( op.asOperator() )
{
// simple binary operations
case Token::Plus: d->codes.append( Opcode::Add ); break;
case Token::Minus: d->codes.append( Opcode::Sub ); break;
case Token::Asterisk: d->codes.append( Opcode::Mul ); break;
case Token::Slash: d->codes.append( Opcode::Div ); break;
case Token::Caret: d->codes.append( Opcode::Pow ); break;
case Token::Ampersand: d->codes.append( Opcode::Concat ); break;
// simple value comparisons
case Token::Equal: d->codes.append( Opcode::Equal ); break;
case Token::Less: d->codes.append( Opcode::Less ); break;
case Token::Greater: d->codes.append( Opcode::Greater ); break;
// NotEqual is Equal, followed by Not
case Token::NotEqual:
d->codes.append( Opcode::Equal );
d->codes.append( Opcode::Not );
break;
// LessOrEqual is Greater, followed by Not
case Token::LessEqual:
d->codes.append( Opcode::Greater );
d->codes.append( Opcode::Not );
break;
// GreaterOrEqual is Less, followed by Not
case Token::GreaterEqual:
d->codes.append( Opcode::Less );
d->codes.append( Opcode::Not );
break;
default: break;
};
}
}
// rule for unary operator: (op1) (op2) X -> (op1) X
// conditions: op2 is unary, token is not '('
// action: push (op2) to result
// e.g. "* - 2" becomes "*"
if( !ruleFound )
if( token.asOperator() != Token::LeftPar )
if( syntaxStack.itemCount() >= 3 )
{
Token x = syntaxStack.top();
Token op2 = syntaxStack.top( 1 );
Token op1 = syntaxStack.top( 2 );
if( !x.isOperator() )
if( op1.isOperator() )
if( op2.isOperator() )
if( ( op2.asOperator() == Token::Plus ) ||
( op2.asOperator() == Token::Minus ) )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( x );
if( op2.asOperator() == Token::Minus )
d->codes.append( Opcode( Opcode::Neg ) );
}
}
// auxilary rule for unary operator: (op) X -> X
// conditions: op is unary, op is first in syntax stack, token is not '('
// action: push (op) to result
if( !ruleFound )
if( token.asOperator() != Token::LeftPar )
if( syntaxStack.itemCount() == 2 )
{
Token x = syntaxStack.top();
Token op = syntaxStack.top( 1 );
if( !x.isOperator() )
if( op.isOperator() )
if( ( op.asOperator() == Token::Plus ) ||
( op.asOperator() == Token::Minus ) )
{
ruleFound = true;
syntaxStack.pop();
syntaxStack.pop();
syntaxStack.push( x );
if( op.asOperator() == Token::Minus )
d->codes.append( Opcode( Opcode::Neg ) );
}
}
if( !ruleFound ) break;
}
// can't apply rules anymore, push the token
if( token.asOperator() != Token::Percent )
syntaxStack.push( token );
}
}
// syntaxStack must left only one operand and end-of-formula (i.e. InvalidOp)
d->valid = false;
if( syntaxStack.itemCount() == 2 )
if( syntaxStack.top().isOperator() )
if( syntaxStack.top().asOperator() == Token::InvalidOp )
if( !syntaxStack.top(1).isOperator() )
d->valid = true;
// bad parsing ? clean-up everything
if( !d->valid )
{
d->constants.clear();
d->codes.clear();
}
}
bool Formula::isNamedArea( const TQString& expr ) const
{
TQString tokenText( expr );
// check for named areas ...
if (d->sheet) {
const TQValueList<Reference> areas = d->sheet->doc()->listArea();
TQValueList<Reference>::const_iterator it;
for (it = areas.begin(); it != areas.end(); ++it) {
if ((*it).ref_name.lower() == tokenText.lower()) {
// we got a named area
return true;
}
}
}
return false;
}
// Evaluates the formula, returns the result.
struct stackEntry {
void reset () { row1 = col1 = row2 = col2 = -1; };
Value val;
int row1, col1, row2, col2;
};
Value Formula::eval() const
{
TQValueStack<stackEntry> stack;
stackEntry entry;
unsigned index;
Value val1, val2;
TQString c;
TQValueVector<Value> args;
Sheet *sheet = 0;
ValueParser* parser = 0;
ValueConverter* converter = 0;
ValueCalc* calc = 0;
if (d->sheet)
{
sheet = d->sheet;
converter = sheet->doc()->converter();
calc = sheet->doc()->calc();
}
else
{
parser = new ValueParser( TDEGlobal::locale() );
converter = new ValueConverter( parser );
calc = new ValueCalc( converter );
}
Function* function;
FuncExtra fe;
fe.mycol = fe.myrow = 0;
if (d->cell) {
fe.mycol = d->cell->column();
fe.myrow = d->cell->row();
}
if( d->dirty )
{
Tokens tokens = scan( d->expression );
d->valid = tokens.valid();
if( tokens.valid() )
compile( tokens );
}
if( !d->valid )
return Value::errorVALUE();
for( unsigned pc = 0; pc < d->codes.count(); pc++ )
{
Value ret; // for the function caller
Opcode& opcode = d->codes[pc];
index = opcode.index;
switch( opcode.type )
{
// no operation
case Opcode::Nop:
break;
// load a constant, push to stack
case Opcode::Load:
entry.reset();
entry.val = d->constants[index];
stack.push (entry);
break;
// unary operation
case Opcode::Neg:
entry.reset();
entry.val = stack.pop().val;
if (!entry.val.isError()) // do nothing if we got an error
entry.val = calc->mul (entry.val, -1);
stack.push (entry);
break;
// binary operation: take two values from stack, do the operation,
// push the result to stack
case Opcode::Add:
entry.reset();
val2 = stack.pop().val;
val1 = stack.pop().val;
val2 = calc->add( val1, val2 );
entry.reset();
entry.val = val2;
stack.push (entry);
break;
case Opcode::Sub:
val2 = stack.pop().val;
val1 = stack.pop().val;
val2 = calc->sub( val1, val2 );
entry.reset();
entry.val = val2;
stack.push (entry);
break;
case Opcode::Mul:
val2 = stack.pop().val;
val1 = stack.pop().val;
val2 = calc->mul( val1, val2 );
entry.reset();
entry.val = val2;
stack.push (entry);
break;
case Opcode::Div:
val2 = stack.pop().val;
val1 = stack.pop().val;
val2 = calc->div( val1, val2 );
entry.reset();
entry.val = val2;
stack.push (entry);
break;
case Opcode::Pow:
val2 = stack.pop().val;
val1 = stack.pop().val;
val2 = calc->pow( val1, val2 );
entry.reset();
entry.val = val2;
stack.push (entry);
break;
// string concatenation
case Opcode::Concat:
val1 = converter->asString (stack.pop().val);
val2 = converter->asString (stack.pop().val);
if (val1.isError() || val2.isError())
val1 = Value::errorVALUE();
else
val1.setValue( val2.asString().append( val1.asString() ) );
entry.reset();
entry.val = val1;
stack.push (entry);
break;
// logical not
case Opcode::Not:
val1 = converter->asBoolean (stack.pop().val);
if( val1.isError() )
val1 = Value::errorVALUE();
else
val1.setValue( !val1.asBoolean() );
entry.reset();
entry.val = val1;
stack.push (entry);
break;
// comparison
case Opcode::Equal:
val1 = stack.pop().val;
val2 = stack.pop().val;
if( !val1.allowComparison( val2 ) )
val1 = Value::errorNA();
else if( val2.compare( val1 ) == 0 )
val1 = Value (true);
else
val1 = Value (false);
entry.reset();
entry.val = val1;
stack.push (entry);
break;
// less than
case Opcode::Less:
val1 = stack.pop().val;
val2 = stack.pop().val;
if( !val1.allowComparison( val2 ) )
val1 = Value::errorNA();
else if( val2.compare( val1 ) < 0 )
val1 = Value (true);
else
val1 = Value (false);
entry.reset();
entry.val = val1;
stack.push (entry);
break;
// greater than
case Opcode::Greater:
val1 = stack.pop().val;
val2 = stack.pop().val;
if( !val1.allowComparison( val2 ) )
val1 = Value::errorNA();
else if( val2.compare( val1 ) > 0 )
val1 = Value (true);
else
val1 = Value (false);
entry.reset();
entry.val = val1;
stack.push (entry);
break;
case Opcode::Cell:
c = d->constants[index].asString();
val1 = Value::empty();
entry.reset();
if (sheet)
{
Point cell (c, sheet->workbook(), sheet);
if (cell.isValid())
{
val1 = cell.sheet()->value (cell.column(), cell.row());
// store the reference, so we can use it within functions
entry.col1 = entry.col2 = cell.column();
entry.row1 = entry.row2 = cell.row();
}
}
entry.val = val1;
stack.push (entry);
break;
case Opcode::Range:
c = d->constants[index].asString();
val1 = Value::empty();
entry.reset();
if (sheet)
{
Range range (c, sheet->workbook(), sheet);
if (range.isValid())
{
val1 = range.sheet()->valueRange (range.startCol(), range.startRow(),
range.endCol(), range.endRow());
// store the reference, so we can use it within functions
entry.col1 = range.startCol();
entry.row1 = range.startRow();
entry.col2 = range.endCol();
entry.row2 = range.endRow();
}
}
entry.val = val1;
stack.push (entry);
break;
case Opcode::Ref:
val1 = d->constants[index];
entry.reset();
entry.val = val1;
stack.push (entry);
break;
// calling function
case Opcode::Function:
if( stack.count() < index )
// (Tomas) umm, how could that be ? I mean, the index value
// is computed from the stack *confused*
return Value::errorVALUE(); // not enough arguments
args.clear();
fe.ranges.clear ();
fe.ranges.reserve (index);
fe.sheet = sheet;
for( ; index; index-- )
{
stackEntry e = stack.pop();
args.insert (args.begin(), e.val);
// TODO: create and fill a FunctionExtra object, if needed
// problem: we don't know if we need it, as we don't have the
// fuction name yet ...
fe.ranges[index - 1].col1 = e.col1;
fe.ranges[index - 1].row1 = e.row1;
fe.ranges[index - 1].col2 = e.col2;
fe.ranges[index - 1].row2 = e.row2;
}
// function name as string value
val1 = converter->asString (stack.pop().val);
if( val1.isError() )
return Value::errorVALUE();
function = FunctionRepository::self()->function ( val1.asString() );
if( !function )
return Value::errorVALUE(); // no such function
ret = function->exec (args, calc, &fe);
entry.reset();
entry.val = ret;
stack.push (entry);
break;
default:
break;
}
}
if (!d->sheet) {
delete parser;
delete converter;
delete calc;
}
// more than one value in stack ? unsuccesful execution...
if( stack.count() != 1 )
return Value::errorVALUE();
return stack.pop().val;
}
// Debugging aid
TQString Formula::dump() const
{
TQString result;
if( d->dirty )
{
Tokens tokens = scan( d->expression );
compile( tokens );
}
result = TQString("Expression: [%1]\n").arg( d->expression );
#if 0
Value value = eval();
result.append( TQString("Result: %1\n").arg(
converter->asString(value).asString() ) );
#endif
result.append(" Constants:\n");
for( unsigned c = 0; c < d->constants.count(); c++ )
{
TQString vtext;
Value val = d->constants[c];
if( val.isString() ) vtext = TQString("[%1]").arg( val.asString() );
else if( val.isNumber() ) vtext = TQString("%1").arg( val.asFloat() );
else if( val.isBoolean() ) vtext = TQString("%1").arg( val.asBoolean() ? "True":"False");
else if( val.isError() ) vtext = "error";
else vtext = "???";
result += TQString(" #%1 = %2\n").arg(c).arg( vtext );
}
result.append("\n");
result.append(" Code:\n");
for( unsigned i = 0; i < d->codes.count(); i++ )
{
TQString ctext;
switch( d->codes[i].type )
{
case Opcode::Load: ctext = TQString("Load #%1").arg( d->codes[i].index ); break;
case Opcode::Ref: ctext = TQString("Ref #%1").arg( d->codes[i].index ); break;
case Opcode::Function: ctext = TQString("Function (%1)").arg( d->codes[i].index ); break;
case Opcode::Add: ctext = "Add"; break;
case Opcode::Sub: ctext = "Sub"; break;
case Opcode::Mul: ctext = "Mul"; break;
case Opcode::Div: ctext = "Div"; break;
case Opcode::Neg: ctext = "Neg"; break;
case Opcode::Concat: ctext = "Concat"; break;
case Opcode::Pow: ctext = "Pow"; break;
case Opcode::Equal: ctext = "Equal"; break;
case Opcode::Not: ctext = "Not"; break;
case Opcode::Less: ctext = "Less"; break;
case Opcode::Greater: ctext = "Greater"; break;
default: ctext = "Unknown"; break;
}
result.append( " " ).append( ctext ).append("\n");
}
return result;
}
TQTextStream& operator<<( TQTextStream& ts, Formula formula )
{
ts << formula.dump();
return ts;
}
|