zhao
2021-07-19 8347f2fbddbd25369359dcb2da1233ac48a19fdc
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
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
/* ====================================================================
   Licensed To the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for Additional information regarding copyright ownership.
   The ASF licenses this file To You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed To in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */
 
namespace HH.WMS.Utils.NPOI.SS.Formula
{
 
    using System;
    using System.Text;
    using System.Collections;
    using System.Text.RegularExpressions;
 
    using HH.WMS.Utils.NPOI.HSSF.Record;
    using HH.WMS.Utils.NPOI.SS.Formula;
    using HH.WMS.Utils.NPOI.SS.Formula.Function;
 
    using HH.WMS.Utils.NPOI.SS.Util;
    using HH.WMS.Utils.NPOI.HSSF.UserModel;
    using System.Collections.Generic;
    using HH.WMS.Utils.NPOI.SS.Formula.PTG;
    using HH.WMS.Utils.NPOI.SS.Formula.Constant;
    using System.Globalization;
 
    /// <summary>
    /// Specific exception thrown when a supplied formula does not Parse properly.
    ///  Primarily used by test cases when testing for specific parsing exceptions.
    /// </summary>
    [Serializable]
    public class FormulaParseException : Exception
    {
        /// <summary>
        ///This class was given package scope until it would become Clear that it is useful to general client code.
        /// </summary>
        /// <param name="msg"></param>
        public FormulaParseException(String msg)
            : base(msg)
        {
 
        }
    }
    /*
     * This class Parses a formula string into a List of Tokens in RPN order.
     * Inspired by
     *           Lets Build a Compiler, by Jack Crenshaw
     * BNF for the formula expression is :
     * <expression> ::= <term> [<addop> <term>]*
     * <term> ::= <factor>  [ <mulop> <factor> ]*
     * <factor> ::= <number> | (<expression>) | <cellRef> | <function>
     * <function> ::= <functionName> ([expression [, expression]*])
     *
     *  @author Avik Sengupta (avik at apache dot org)
     *  @author Andrew C. oliver (acoliver at apache dot org)
     *  @author Eric Ladner (eladner at goldinc dot com)
     *  @author Cameron Riley (criley at ekmail.com)
     *  @author Peter M. Murray (pete at quantrix dot com)
     *  @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
     *  @author Josh Micich
     */
    public class FormulaParser
    {
        private class Identifier
        {
            private String _name;
            private bool _isQuoted;
 
            public Identifier(String name, bool IsQuoted)
            {
                _name = name;
                _isQuoted = IsQuoted;
            }
            public String Name
            {
                get
                {
                    return _name;
                }
            }
            public bool IsQuoted
            {
                get
                {
                    return _isQuoted;
                }
            }
            public override String ToString()
            {
                StringBuilder sb = new StringBuilder(64);
                sb.Append(GetType().Name);
                sb.Append(" [");
                if (_isQuoted)
                {
                    sb.Append("'").Append(_name).Append("'");
                }
                else
                {
                    sb.Append(_name);
                }
                sb.Append("]");
                return sb.ToString();
            }
        }
        private class SheetIdentifier
        {
 
 
            private String _bookName;
            private Identifier _sheetIdentifier;
            public SheetIdentifier(String bookName, Identifier sheetIdentifier)
            {
                _bookName = bookName;
                _sheetIdentifier = sheetIdentifier;
            }
            public String BookName
            {
                get
                {
                    return _bookName;
                }
            }
            public Identifier SheetID
            {
                get
                {
                    return _sheetIdentifier;
                }
            }
            public override String ToString()
            {
                StringBuilder sb = new StringBuilder(64);
                sb.Append(this.GetType().Name);
                sb.Append(" [");
                if (_bookName != null)
                {
                    sb.Append(" [").Append(_sheetIdentifier.Name).Append("]");
                }
                if (_sheetIdentifier.IsQuoted)
                {
                    sb.Append("'").Append(_sheetIdentifier.Name).Append("'");
                }
                else
                {
                    sb.Append(_sheetIdentifier.Name);
                }
                sb.Append("]");
                return sb.ToString();
            }
        }
 
 
 
 
        private String formulaString;
        private int formulaLength;
        private int pointer;
        private static SpreadsheetVersion _ssVersion;
 
        private ParseNode _rootNode;
 
        private static char TAB = '\t';
 
        /**
         * Lookahead Character.
         * Gets value '\0' when the input string is exhausted
         */
        private char look;
 
        private IFormulaParsingWorkbook _book;
 
        private int _sheetIndex;
 
        /**
         * Create the formula Parser, with the string that is To be
         *  Parsed against the supplied workbook.
         * A later call the Parse() method To return ptg list in
         *  rpn order, then call the GetRPNPtg() To retrive the
         *  Parse results.
         * This class is recommended only for single threaded use.
         *
         * If you only have a usermodel.HSSFWorkbook, and not a
         *  model.Workbook, then use the convenience method on
         *  usermodel.HSSFFormulaEvaluator
         */
        public FormulaParser(String formula, IFormulaParsingWorkbook book, int sheetIndex)
        {
            formulaString = formula;
            pointer = 0;
            this._book = book;
 
            _ssVersion = book == null ? SpreadsheetVersion.EXCEL97 : book.GetSpreadsheetVersion();
            formulaLength = formulaString.Length;
            _sheetIndex = sheetIndex;
        }
 
        public static Ptg[] Parse(String formula, IFormulaParsingWorkbook book)
        {
            return Parse(formula, book, FormulaType.CELL);
        }
 
 
        /**
         * Parse a formula into a array of tokens
         *
         * @param formula     the formula to parse
         * @param workbook    the parent workbook
         * @param formulaType the type of the formula, see {@link FormulaType}
         * @param sheetIndex  the 0-based index of the sheet this formula belongs to.
         * The sheet index is required to resolve sheet-level names. <code>-1</code> means that
         * the scope of the name will be ignored and  the parser will match names only by name
         *
         * @return array of parsed tokens
         * @throws FormulaParseException if the formula is unparsable
         */
        public static Ptg[] Parse(String formula, IFormulaParsingWorkbook workbook, FormulaType formulaType, int sheetIndex)
        {
            FormulaParser fp = new FormulaParser(formula, workbook, sheetIndex);
            fp.Parse();
            return fp.GetRPNPtg(formulaType);
        }
 
        public static Ptg[] Parse(String formula, IFormulaParsingWorkbook workbook, FormulaType formulaType)
        {
            return Parse(formula, workbook, formulaType, -1);
        }
 
        /** Read New Character From Input Stream */
        private void GetChar()
        {
            // Check To see if we've walked off the end of the string.
            if (pointer > formulaLength)
            {
                throw new Exception("too far");
            }
            if (pointer < formulaLength)
            {
                look = formulaString[pointer];
            }
            else
            {
                // Just return if so and reset 'look' To something To keep
                // SkipWhitespace from spinning
                look = (char)0;
            }
            pointer++;
            //Console.WriteLine("Got char: "+ look);
        }
 
        /** Report What Was Expected */
        private Exception expected(String s)
        {
            String msg;
 
            if (look == '=' && formulaString.Substring(0, pointer - 1).Trim().Length < 1)
            {
                msg = "The specified formula '" + formulaString
                    + "' starts with an equals sign which is not allowed.";
            }
            else
            {
                msg = "Parse error near char " + (pointer - 1) + " '" + look + "'"
                    + " in specified formula '" + formulaString + "'. Expected "
                    + s;
            }
            return new FormulaParseException(msg);
        }
 
        /** Recognize an Alpha Character */
        private static bool IsAlpha(char c)
        {
            return Char.IsLetter(c) || c == '$' || c == '_';
        }
 
        /** Recognize a Decimal Digit */
        private static bool IsDigit(char c)
        {
            return Char.IsDigit(c);
        }
 
        /** Recognize an Alphanumeric */
        private static bool IsAlNum(char c)
        {
            return IsAlpha(c) || IsDigit(c);
        }
 
        /** Recognize White Space */
        private static bool IsWhite(char c)
        {
            return c == ' ' || c == TAB;
        }
 
        /** Skip Over Leading White Space */
        private void SkipWhite()
        {
            while (IsWhite(look))
            {
                GetChar();
            }
        }
 
        /**
         *  Consumes the next input character if it is equal To the one specified otherwise throws an
         *  unchecked exception. This method does <b>not</b> consume whitespace (before or after the
         *  matched character).
         */
        private void Match(char x)
        {
            if (look != x)
            {
                throw expected("'" + x + "'");
            }
            GetChar();
        }
        private String ParseUnquotedIdentifier()
        {
            if (look == '\'')
            {
                throw expected("unquoted identifier");
            }
            StringBuilder sb = new StringBuilder();
            while (Char.IsLetterOrDigit(look) || look == '.')
            {
                sb.Append(look);
                GetChar();
            }
            if (sb.Length < 1)
            {
                return null;
            }
 
            return sb.ToString();
        }
        /** Get a Number */
        private String GetNum()
        {
            StringBuilder value = new StringBuilder();
 
            while (IsDigit(this.look))
            {
                value.Append(this.look);
                GetChar();
            }
            return value.Length == 0 ? null : value.ToString();
        }
 
        private ParseNode ParseRangeExpression()
        {
            ParseNode result = ParseRangeable();
            bool hasRange = false;
            while (look == ':')
            {
                int pos = pointer;
                GetChar();
                ParseNode nextPart = ParseRangeable();
                // Note - no range simplification here. An expr like "A1:B2:C3:D4:E5" should be
                // grouped into area ref pairs like: "(A1:B2):(C3:D4):E5"
                // Furthermore, Excel doesn't seem to simplify
                // expressions like "Sheet1!A1:Sheet1:B2" into "Sheet1!A1:B2"
 
                CheckValidRangeOperand("LHS", pos, result);
                CheckValidRangeOperand("RHS", pos, nextPart);
 
                ParseNode[] children = { result, nextPart, };
                result = new ParseNode(RangePtg.instance, children);
                hasRange = true;
            }
            if (hasRange)
            {
                return AugmentWithMemPtg(result);
            }
            return result;
        }
        private static ParseNode AugmentWithMemPtg(ParseNode root)
        {
            Ptg memPtg;
            if (NeedsMemFunc(root))
            {
                memPtg = new MemFuncPtg(root.EncodedSize);
            }
            else
            {
                memPtg = new MemAreaPtg(root.EncodedSize);
            }
            return new ParseNode(memPtg, root);
        }
        /**
 * From OOO doc: "Whenever one operand of the reference subexpression is a function,
 *  a defined name, a 3D reference, or an external reference (and no error occurs),
 *  a tMemFunc token is used"
 *
 */
        private static bool NeedsMemFunc(ParseNode root)
        {
            Ptg token = root.GetToken();
            if (token is AbstractFunctionPtg)
            {
                return true;
            }
            if (token is IExternSheetReferenceToken)
            { // 3D refs
                return true;
            }
            if (token is NamePtg || token is NameXPtg)
            { // 3D refs
                return true;
            }
 
            if (token is OperationPtg || token is ParenthesisPtg)
            {
                // expect RangePtg, but perhaps also UnionPtg, IntersectionPtg etc
                foreach (ParseNode child in root.GetChildren())
                {
                    if (NeedsMemFunc(child))
                    {
                        return true;
                    }
                }
                return false;
            }
            if (token is OperandPtg)
            {
                return false;
            }
            if (token is OperationPtg)
            {
                return true;
            }
 
            return false;
        }
 
 
 
 
        /**
 *
 * @return <c>true</c> if the specified character may be used in a defined name
 */
        private static bool IsValidDefinedNameChar(char ch)
        {
            if (Char.IsLetterOrDigit(ch))
            {
                return true;
            }
            switch (ch)
            {
                case '.':
                case '_':
                case '?':
                case '\\': // of all things
                    return true;
            }
            return false;
        }
        /**
 * @param currentParsePosition used to format a potential error message
 */
        private void CheckValidRangeOperand(String sideName, int currentParsePosition, ParseNode pn)
        {
            if (!IsValidRangeOperand(pn))
            {
                throw new FormulaParseException("The " + sideName
                        + " of the range operator ':' at position "
                        + currentParsePosition + " is not a proper reference.");
            }
        }
        /**
          * @return false if sub-expression represented the specified ParseNode definitely
          * cannot appear on either side of the range (':') operator
          */
        private bool IsValidRangeOperand(ParseNode a)
        {
            Ptg tkn = a.GetToken();
            // Note - order is important for these instance-of checks
            if (tkn is OperandPtg)
            {
                // notably cell refs and area refs
                return true;
            }
 
            // next 2 are special cases of OperationPtg
            if (tkn is AbstractFunctionPtg)
            {
                AbstractFunctionPtg afp = (AbstractFunctionPtg)tkn;
                byte returnClass = afp.DefaultOperandClass;
                return Ptg.CLASS_REF == returnClass;
            }
            if (tkn is ValueOperatorPtg)
            {
                return false;
            }
            if (tkn is OperationPtg)
            {
                return true;
            }
 
            // one special case of ControlPtg
            if (tkn is ParenthesisPtg)
            {
                // parenthesis Ptg should have only one child
                return IsValidRangeOperand(a.GetChildren()[0]);
            }
 
            // one special case of ScalarConstantPtg
            if (tkn == ErrPtg.REF_INVALID)
            {
                return true;
            }
 
            // All other ControlPtgs and ScalarConstantPtgs cannot be used with ':'
            return false;
        }
 
 
 
 
        /**
 * Parses area refs (things which could be the operand of ':') and simple factors
 * Examples
 * <pre>
 *   A$1
 *   $A$1 :  $B1
 *   A1 .......    C2
 *   Sheet1 !$A1
 *   a..b!A1
 *   'my sheet'!A1
 *   .my.sheet!A1
 *   my.named..range.
 *   foo.bar(123.456, "abc")
 *   123.456
 *   "abc"
 *   true
 * </pre>
 *
 */
        private ParseNode ParseRangeable()
        {
            SkipWhite();
            int savePointer = pointer;
            SheetIdentifier sheetIden = ParseSheetName();
            if (sheetIden == null)
            {
                ResetPointer(savePointer);
            }
            else
            {
                SkipWhite();
                savePointer = pointer;
            }
 
            SimpleRangePart part1 = ParseSimpleRangePart();
 
            if (part1 == null)
            {
                if (sheetIden != null)
                {
                    if (look == '#')
                    {  // error ref like MySheet!#REF!
                        return new ParseNode(ErrPtg.ValueOf(ParseErrorLiteral()));
                    }
                    else
                    {
                        throw new FormulaParseException("Cell reference expected after sheet name at index "
                                + pointer + ".");
                    }
                }
                return ParseNonRange(savePointer);
            }
 
 
 
 
 
            bool whiteAfterPart1 = IsWhite(look);
            if (whiteAfterPart1)
            {
                SkipWhite();
            }
 
            if (look == ':')
            {
                int colonPos = pointer;
                GetChar();
                SkipWhite();
                SimpleRangePart part2 = ParseSimpleRangePart();
                if (part2 != null && !part1.IsCompatibleForArea(part2))
                {
                    // second part is not compatible with an area ref e.g. S!A1:S!B2
                    // where S might be a sheet name (that looks like a column name)
 
                    part2 = null;
                }
                if (part2 == null)
                {
                    // second part is not compatible with an area ref e.g. A1:OFFSET(B2, 1, 2)
                    // reset and let caller use explicit range operator
                    ResetPointer(colonPos);
                    if (!part1.IsCell)
                    {
                        String prefix;
                        if (sheetIden == null)
                        {
                            prefix = "";
                        }
                        else
                        {
                            prefix = "'" + sheetIden.SheetID.Name + '!';
                        }
                        throw new FormulaParseException(prefix + part1.Rep + "' is not a proper reference.");
                    }
                    return CreateAreaRefParseNode(sheetIden, part1, part2);
                }
                return CreateAreaRefParseNode(sheetIden, part1, part2);
            }
 
            if (look == '.')
            {
                GetChar();
                int dotCount = 1;
                while (look == '.')
                {
                    dotCount++;
                    GetChar();
                }
                bool whiteBeforePart2 = IsWhite(look);
 
                SkipWhite();
                SimpleRangePart part2 = ParseSimpleRangePart();
                String part1And2 = formulaString.Substring(savePointer - 1, pointer - savePointer);
                if (part2 == null)
                {
                    if (sheetIden != null)
                    {
                        throw new FormulaParseException("Complete area reference expected after sheet name at index "
                                + pointer + ".");
                    }
                    return ParseNonRange(savePointer);
                }
 
 
                if (whiteAfterPart1 || whiteBeforePart2)
                {
                    if (part1.IsRowOrColumn || part2.IsRowOrColumn)
                    {
                        // "A .. B" not valid syntax for "A:B"
                        // and there's no other valid expression that fits this grammar
                        throw new FormulaParseException("Dotted range (full row or column) expression '"
                                + part1And2 + "' must not contain whitespace.");
                    }
                    return CreateAreaRefParseNode(sheetIden, part1, part2);
                }
 
                if (dotCount == 1 && part1.IsRow && part2.IsRow)
                {
                    // actually, this is looking more like a number
                    return ParseNonRange(savePointer);
                }
 
                if (part1.IsRowOrColumn || part2.IsRowOrColumn)
                {
                    if (dotCount != 2)
                    {
                        throw new FormulaParseException("Dotted range (full row or column) expression '" + part1And2
                                + "' must have exactly 2 dots.");
                    }
                }
                return CreateAreaRefParseNode(sheetIden, part1, part2);
            }
            if (part1.IsCell && IsValidCellReference(part1.Rep))
            {
                return CreateAreaRefParseNode(sheetIden, part1, null);
            }
            if (sheetIden != null)
            {
                throw new FormulaParseException("Second part of cell reference expected after sheet name at index "
                        + pointer + ".");
            }
 
            return ParseNonRange(savePointer);
        }
 
        /**
  * Parses simple factors that are not primitive ranges or range components
  * i.e. '!', ':'(and equiv '...') do not appear
  * Examples
  * <pre>
  *   my.named...range.
  *   foo.bar(123.456, "abc")
  *   123.456
  *   "abc"
  *   true
  * </pre>
  */
        private ParseNode ParseNonRange(int savePointer)
        {
            ResetPointer(savePointer);
 
            if (Char.IsDigit(look))
            {
                return new ParseNode(ParseNumber());
            }
            if (look == '"')
            {
                return new ParseNode(new StringPtg(ParseStringLiteral()));
            }
            // from now on we can only be dealing with non-quoted identifiers
            // which will either be named ranges or functions
            StringBuilder sb = new StringBuilder();
 
            if (!Char.IsLetter(look) && look != '_')
            {
                throw expected("number, string, or defined name");
            }
            while (IsValidDefinedNameChar(look))
            {
                sb.Append(look);
                GetChar();
            }
            SkipWhite();
            String name = sb.ToString();
            if (look == '(')
            {
                return Function(name);
            }
            if (name.Equals("TRUE", StringComparison.OrdinalIgnoreCase) || name.Equals("FALSE", StringComparison.OrdinalIgnoreCase))
            {
                return new ParseNode(new BoolPtg(name.ToUpper()));
            }
            if (_book == null)
            {
                // Only test cases omit the book (expecting it not to be needed)
                throw new InvalidOperationException("Need book to evaluate name '" + name + "'");
            }
            IEvaluationName evalName = _book.GetName(name, _sheetIndex);
            if (evalName == null)
            {
                throw new FormulaParseException("Specified named range '"
                        + name + "' does not exist in the current workbook.");
            }
            if (evalName.IsRange)
            {
                return new ParseNode(evalName.CreatePtg());
            }
            // TODO - what about NameX ?
            throw new FormulaParseException("Specified name '"
                    + name + "' is not a range as expected.");
        }
 
        /**
 *
 * @param sheetIden may be <code>null</code>
 * @param part1
 * @param part2 may be <code>null</code>
 */
        private ParseNode CreateAreaRefParseNode(SheetIdentifier sheetIden, SimpleRangePart part1,
                SimpleRangePart part2)
        {
 
            int extIx;
            if (sheetIden == null)
            {
                extIx = Int32.MinValue;
            }
            else
            {
                String sName = sheetIden.SheetID.Name;
                if (sheetIden.BookName == null)
                {
                    extIx = _book.GetExternalSheetIndex(sName);
                }
                else
                {
                    extIx = _book.GetExternalSheetIndex(sheetIden.BookName, sName);
                }
            }
            Ptg ptg;
            if (part2 == null)
            {
                CellReference cr = part1.getCellReference();
                if (sheetIden == null)
                {
                    ptg = new RefPtg(cr);
                }
                else
                {
                    ptg = new Ref3DPtg(cr, extIx);
                }
            }
            else
            {
                AreaReference areaRef = CreateAreaRef(part1, part2);
 
                if (sheetIden == null)
                {
                    ptg = new AreaPtg(areaRef);
                }
                else
                {
                    ptg = new Area3DPtg(areaRef, extIx);
                }
            }
            return new ParseNode(ptg);
        }
        private static AreaReference CreateAreaRef(SimpleRangePart part1, SimpleRangePart part2)
        {
            if (!part1.IsCompatibleForArea(part2))
            {
                throw new FormulaParseException("has incompatible parts: '"
                        + part1.Rep + "' and '" + part2.Rep + "'.");
            }
            if (part1.IsRow)
            {
                return AreaReference.GetWholeRow(part1.Rep, part2.Rep);
            }
            if (part1.IsColumn)
            {
                return AreaReference.GetWholeColumn(part1.Rep, part2.Rep);
            }
            return new AreaReference(part1.getCellReference(), part2.getCellReference());
        }
        private string CELL_REF_PATTERN = "(\\$?[A-Za-z]+)?(\\$?[0-9]+)?";
 
 
 
 
        /**
  * Parses out a potential LHS or RHS of a ':' intended to produce a plain AreaRef.  Normally these are
  * proper cell references but they could also be row or column refs like "$AC" or "10"
  * @return <code>null</code> (and leaves {@link #_pointer} unchanged if a proper range part does not parse out
  */
        private SimpleRangePart ParseSimpleRangePart()
        {
            int ptr = pointer - 1; // TODO avoid StringIndexOutOfBounds
            bool hasDigits = false;
            bool hasLetters = false;
            while (ptr < formulaLength)
            {
                char ch = formulaString[ptr];
                if (Char.IsDigit(ch))
                {
                    hasDigits = true;
                }
                else if (Char.IsLetter(ch))
                {
                    hasLetters = true;
                }
                else if (ch == '$' || ch == '_')    //fix poi bug 49725
                {
                    //do nothing
                }
                else
                {
                    break;
                }
                ptr++;
            }
            if (ptr <= pointer - 1)
            {
                return null;
            }
            String rep = formulaString.Substring(pointer - 1, ptr - pointer + 1);
 
            Regex pattern = new Regex(CELL_REF_PATTERN);
 
            if (!pattern.IsMatch(rep))
            {
                return null;
            }
            // Check range bounds against grid max
            if (hasLetters && hasDigits)
            {
                if (!IsValidCellReference(rep))
                {
                    return null;
                }
            }
            else if (hasLetters)
            {
                if (!CellReference.IsColumnWithnRange(rep.Replace("$", ""), _ssVersion))
                {
                    return null;
                }
            }
            else if (hasDigits)
            {
                int i;
                try
                {
                    i = Int32.Parse(rep.Replace("$", ""), CultureInfo.InvariantCulture);
                }
                catch (Exception)
                {
                    return null;
                }
                if (i < 1 || i > 65536)
                {
                    return null;
                }
            }
            else
            {
                // just dollars ? can this happen?
                return null;
            }
 
 
            ResetPointer(ptr + 1); // stepping forward
            return new SimpleRangePart(rep, hasLetters, hasDigits);
        }
 
 
 
        /**
         * 
         * "A1", "B3" -> "A1:B3"   
         * "sheet1!A1", "B3" -> "sheet1!A1:B3"
         * 
         * @return <c>null</c> if the range expression cannot / shouldn't be reduced.
         */
        private static Ptg ReduceRangeExpression(Ptg ptgA, Ptg ptgB)
        {
            if (!(ptgB is RefPtg))
            {
                // only when second ref is simple 2-D ref can the range 
                // expression be converted To an area ref
                return null;
            }
            RefPtg refB = (RefPtg)ptgB;
 
            if (ptgA is RefPtg)
            {
                RefPtg refA = (RefPtg)ptgA;
                return new AreaPtg(refA.Row, refB.Row, refA.Column, refB.Column,
                        refA.IsRowRelative, refB.IsRowRelative, refA.IsColRelative, refB.IsColRelative);
            }
            if (ptgA is Ref3DPtg)
            {
                Ref3DPtg refA = (Ref3DPtg)ptgA;
                return new Area3DPtg(refA.Row, refB.Row, refA.Column, refB.Column,
                        refA.IsRowRelative, refB.IsRowRelative, refA.IsColRelative, refB.IsColRelative,
                        refA.ExternSheetIndex);
            }
            // Note - other operand types (like AreaPtg) which probably can't evaluate 
            // do not cause validation errors at Parse time
            return null;
        }
        /**
     * A1, $A1, A$1, $A$1, A, 1
     */
        private class SimpleRangePart
        {
            public enum PartType
            {
                CELL, ROW, COLUMN
            }
 
            public static PartType Get(bool hasLetters, bool hasDigits)
            {
                if (hasLetters)
                {
                    return hasDigits ? PartType.CELL : PartType.COLUMN;
                }
                if (!hasDigits)
                {
                    throw new ArgumentException("must have either letters or numbers");
                }
                return PartType.ROW;
            }
 
            private PartType _type;
            private String _rep;
 
            public SimpleRangePart(String rep, bool hasLetters, bool hasNumbers)
            {
                _rep = rep;
                _type = Get(hasLetters, hasNumbers);
            }
 
            public bool IsCell
            {
                get
                {
                    return _type == PartType.CELL;
                }
            }
 
            public bool IsRowOrColumn
            {
                get
                {
                    return _type != PartType.CELL;
                }
            }
 
 
            public CellReference getCellReference()
            {
                if (_type != PartType.CELL)
                {
                    throw new InvalidOperationException("Not applicable to this type");
                }
                return new CellReference(_rep);
            }
 
            public bool IsColumn
            {
                get
                {
                    return _type == PartType.COLUMN;
                }
            }
 
            public bool IsRow
            {
                get
                {
                    return _type == PartType.ROW;
                }
            }
 
            public String Rep
            {
                get
                {
                    return _rep;
                }
            }
 
            /**
             * @return <c>true</c> if the two range parts can be combined in an
             * {@link AreaPtg} ( Note - the explicit range operator (:) may still be valid
             * when this method returns <c>false</c> )
             */
            public bool IsCompatibleForArea(SimpleRangePart part2)
            {
                return _type == part2._type;
            }
 
            public override String ToString()
            {
                StringBuilder sb = new StringBuilder(64);
                sb.Append(this.GetType().Name).Append(" [");
                sb.Append(_rep);
                sb.Append("]");
                return sb.ToString();
            }
        }
        /**
 * Note - caller should reset {@link #_pointer} upon <code>null</code> result
 * @return The sheet name as an identifier <code>null</code> if '!' is not found in the right place
 */
        private SheetIdentifier ParseSheetName()
        {
 
            String bookName;
            if (look == '[')
            {
                StringBuilder sb = new StringBuilder();
                GetChar();
                while (look != ']')
                {
                    sb.Append(look);
                    GetChar();
                }
                GetChar();
                bookName = sb.ToString();
            }
            else
            {
                bookName = null;
            }
 
            if (look == '\'')
            {
                StringBuilder sb = new StringBuilder();
 
                Match('\'');
                bool done = look == '\'';
                while (!done)
                {
                    sb.Append(look);
                    GetChar();
                    if (look == '\'')
                    {
                        Match('\'');
                        done = look != '\'';
                    }
                }
 
                Identifier iden = new Identifier(sb.ToString(), true);
                // quoted identifier - can't concatenate anything more
                SkipWhite();
                if (look == '!')
                {
                    GetChar();
                    return new SheetIdentifier(bookName, iden);
                }
                return null;
            }
 
            // unquoted sheet names must start with underscore or a letter
            if (look == '_' || Char.IsLetter(look))
            {
                StringBuilder sb = new StringBuilder();
                // can concatenate idens with dots
                while (IsUnquotedSheetNameChar(look))
                {
                    sb.Append(look);
                    GetChar();
                }
                SkipWhite();
                if (look == '!')
                {
                    GetChar();
                    return new SheetIdentifier(bookName, new Identifier(sb.ToString(), false));
                }
                return null;
            }
            return null;
        }
        /**
  * very similar to {@link SheetNameFormatter#isSpecialChar(char)}
  */
        private bool IsUnquotedSheetNameChar(char ch)
        {
            if (Char.IsLetterOrDigit(ch))
            {
                return true;
            }
            switch (ch)
            {
                case '.': // dot is OK
                case '_': // underscore is OK
                    return true;
            }
            return false;
        }
        private void ResetPointer(int ptr)
        {
            pointer = ptr;
            if (pointer <= formulaLength)
            {
                look = formulaString[pointer - 1];
            }
            else
            {
                // Just return if so and reset 'look' to something to keep
                // SkipWhitespace from spinning
                look = (char)0;
            }
        }
 
        /**
         * @return <c>true</c> if the specified name is a valid cell reference
         */
        private bool IsValidCellReference(String str)
        {
            //check range bounds against grid max
            bool result = CellReference.ClassifyCellReference(str, _ssVersion) == NameType.CELL;
            if (result)
            {
                /*
                 * Check if the argument is a function. Certain names can be either a cell reference or a function name
                 * depending on the contenxt. Compare the following examples in Excel 2007:
                 * (a) LOG10(100) + 1
                 * (b) LOG10 + 1
                 * In (a) LOG10 is a name of a built-in function. In (b) LOG10 is a cell reference
                 */
                bool isFunc = FunctionMetadataRegistry.GetFunctionByName(str.ToUpper()) != null;
                if (isFunc)
                {
                    int savePointer = pointer;
                    ResetPointer(pointer + str.Length);
                    SkipWhite();
                    // open bracket indicates that the argument is a function,
                    // the returning value should be false, i.e. "not a valid cell reference"
                    result = look != '(';
                    ResetPointer(savePointer);
                }
            }
            return result;
        }
 
 
        /**
         * Note - Excel Function names are 'case aware but not case sensitive'.  This method may end
         * up creating a defined name record in the workbook if the specified name is not an internal
         * Excel Function, and Has not been encountered before.
         *
         * @param name case preserved Function name (as it was entered/appeared in the formula).
         */
        private ParseNode Function(String name)
        {
            Ptg nameToken = null;
            if (!AbstractFunctionPtg.IsBuiltInFunctionName(name))
            {
                // user defined Function
                // in the Token tree, the name is more or less the first argument
 
                if (_book == null)
                {
                    // Only test cases omit the book (expecting it not to be needed)
                    throw new InvalidOperationException("Need book to evaluate name '" + name + "'");
                }
 
                IEvaluationName hName = _book.GetName(name, _sheetIndex);
                if (hName == null)
                {
 
                    nameToken = _book.GetNameXPtg(name);
                    if (nameToken == null)
                    {
                        throw new FormulaParseException("Name '" + name
                                + "' is completely unknown in the current workbook");
                    }
                }
                else
                {
                    if (!hName.IsFunctionName)
                    {
                        throw new FormulaParseException("Attempt To use name '" + name
                                + "' as a Function, but defined name in workbook does not refer To a Function");
                    }
 
                    // calls To user-defined Functions within the workbook
                    // Get a Name Token which points To a defined name record
                    nameToken = hName.CreatePtg();
                }
            }
 
            Match('(');
            ParseNode[] args = Arguments();
            Match(')');
 
            return GetFunction(name, nameToken, args);
        }
 
        /**
         * Generates the variable Function ptg for the formula.
         * 
         * For IF Formulas, Additional PTGs are Added To the Tokens
     * @param name a {@link NamePtg} or {@link NameXPtg} or <code>null</code>
         * @return Ptg a null is returned if we're in an IF formula, it needs extreme manipulation and is handled in this Function
         */
        private ParseNode GetFunction(String name, Ptg namePtg, ParseNode[] args)
        {
 
            FunctionMetadata fm = FunctionMetadataRegistry.GetFunctionByName(name.ToUpper());
            int numArgs = args.Length;
            if (fm == null)
            {
                if (namePtg == null)
                {
                    throw new InvalidOperationException("NamePtg must be supplied for external Functions");
                }
                // must be external Function
                ParseNode[] allArgs = new ParseNode[numArgs + 1];
                allArgs[0] = new ParseNode(namePtg);
                System.Array.Copy(args, 0, allArgs, 1, numArgs);
                return new ParseNode(FuncVarPtg.Create(name, (byte)(numArgs + 1)), allArgs);
            }
 
            if (namePtg != null)
            {
                throw new InvalidOperationException("NamePtg no applicable To internal Functions");
            }
            bool IsVarArgs = !fm.HasFixedArgsLength;
            int funcIx = fm.Index;
        if (funcIx == FunctionMetadataRegistry.FUNCTION_INDEX_SUM && args.Length == 1) {
            // Excel encodes the sum of a single argument as tAttrSum
            // POI does the same for consistency, but this is not critical
            return new ParseNode(AttrPtg.GetSumSingle(), args);
            // The code below would encode tFuncVar(SUM) which seems to do no harm
        }
            ValidateNumArgs(args.Length, fm);
 
            AbstractFunctionPtg retval;
            if (IsVarArgs)
            {
                retval = FuncVarPtg.Create(name, (byte)numArgs);
            }
            else
            {
                retval = FuncPtg.Create(funcIx);
            }
            return new ParseNode(retval, args);
        }
 
        private void ValidateNumArgs(int numArgs, FunctionMetadata fm)
        {
            if (numArgs < fm.MinParams)
            {
                String msg = "Too few arguments to function '" + fm.Name + "'. ";
                if (fm.HasFixedArgsLength)
                {
                    msg += "Expected " + fm.MinParams;
                }
                else
                {
                    msg += "At least " + fm.MinParams + " were expected";
                }
                msg += " but got " + numArgs + ".";
                throw new FormulaParseException(msg);
            }
            if (numArgs > fm.MaxParams)
            {
                String msg = "Too many arguments to function '" + fm.Name + "'. ";
                if (fm.HasFixedArgsLength)
                {
                    msg += "Expected " + fm.MaxParams;
                }
                else
                {
                    msg += "At most " + fm.MaxParams + " were expected";
                }
                msg += " but got " + numArgs + ".";
                throw new FormulaParseException(msg);
            }
        }
 
        private static bool IsArgumentDelimiter(char ch)
        {
            return ch == ',' || ch == ')';
        }
 
        /** Get arguments To a Function */
        private ParseNode[] Arguments()
        {
            //average 2 args per Function
            ArrayList temp = new ArrayList(2);
            SkipWhite();
            if (look == ')')
            {
                return ParseNode.EMPTY_ARRAY;
            }
 
            bool missedPrevArg = true;
            int numArgs = 0;
            while (true)
            {
                SkipWhite();
                if (IsArgumentDelimiter(look))
                {
                    if (missedPrevArg)
                    {
                        temp.Add(new ParseNode(MissingArgPtg.instance));
                        numArgs++;
                    }
                    if (look == ')')
                    {
                        break;
                    }
                    Match(',');
                    missedPrevArg = true;
                    continue;
                }
                temp.Add(ComparisonExpression());
                numArgs++;
                missedPrevArg = false;
                SkipWhite();
                if (!IsArgumentDelimiter(look))
                {
                    throw expected("',' or ')'");
                }
            }
            ParseNode[] result = (ParseNode[])temp.ToArray(typeof(ParseNode));
            return result;
        }
 
        /** Parse and Translate a Math Factor  */
        private ParseNode PowerFactor()
        {
            ParseNode result = PercentFactor();
            while (true)
            {
                SkipWhite();
                if (look != '^')
                {
                    return result;
                }
                Match('^');
                ParseNode other = PercentFactor();
                result = new ParseNode(PowerPtg.instance, result, other);
            }
        }
 
        private ParseNode PercentFactor()
        {
            ParseNode result = ParseSimpleFactor();
            while (true)
            {
                SkipWhite();
                if (look != '%')
                {
                    return result;
                }
                Match('%');
                result = new ParseNode(PercentPtg.instance, result);
            }
        }
 
 
 
        /**
         * factors (without ^ or % )
         */
        private ParseNode ParseSimpleFactor()
        {
            SkipWhite();
            switch (look)
            {
                case '#':
                    return new ParseNode(ErrPtg.ValueOf(ParseErrorLiteral()));
                case '-':
                    Match('-');
                    return ParseUnary(false);
                case '+':
                    Match('+');
                    return ParseUnary(true);
                case '(':
                    Match('(');
                    ParseNode inside = ComparisonExpression();
                    Match(')');
                    return new ParseNode(ParenthesisPtg.instance, inside);
                case '"':
                    return new ParseNode(new StringPtg(ParseStringLiteral()));
                case '{':
                    Match('{');
                    ParseNode arrayNode = ParseArray();
                    Match('}');
                    return arrayNode;
            }
            if (IsAlpha(look) || Char.IsDigit(look) || look == '\'' || look == '[')
            {
                return ParseRangeExpression();
            }
            if (look == '.')
            {
                return new ParseNode(ParseNumber());
            }
            throw expected("cell ref or constant literal");
        }
        private ParseNode ParseUnary(bool isPlus)
        {
 
            bool numberFollows = IsDigit(look) || look == '.';
            ParseNode factor = PowerFactor();
 
            if (numberFollows)
            {
                // + or - directly next to a number is parsed with the number
 
                Ptg token = factor.GetToken();
                if (token is NumberPtg)
                {
                    if (isPlus)
                    {
                        return factor;
                    }
                    token = new NumberPtg(-((NumberPtg)token).Value);
                    return new ParseNode(token);
                }
                if (token is IntPtg)
                {
                    if (isPlus)
                    {
                        return factor;
                    }
                    int intVal = ((IntPtg)token).Value;
                    // note - cannot use IntPtg for negatives
                    token = new NumberPtg(-intVal);
                    return new ParseNode(token);
                }
            }
            return new ParseNode(isPlus ? UnaryPlusPtg.instance : UnaryMinusPtg.instance, factor);
        }
 
        private ParseNode ParseArray()
        {
            List<Object[]> rowsData = new List<Object[]>();
            while (true)
            {
                Object[] singleRowData = ParseArrayRow();
                rowsData.Add(singleRowData);
                if (look == '}')
                {
                    break;
                }
                if (look != ';')
                {
                    throw expected("'}' or ';'");
                }
                Match(';');
            }
            int nRows = rowsData.Count;
            Object[][] values2d = new Object[nRows][];
            values2d = (Object[][])rowsData.ToArray();
            int nColumns = values2d[0].Length;
            CheckRowLengths(values2d, nColumns);
 
            return new ParseNode(new ArrayPtg(values2d));
        }
        private void CheckRowLengths(Object[][] values2d, int nColumns)
        {
            for (int i = 0; i < values2d.Length; i++)
            {
                int rowLen = values2d[i].Length;
                if (rowLen != nColumns)
                {
                    throw new FormulaParseException("Array row " + i + " Has length " + rowLen
                            + " but row 0 Has length " + nColumns);
                }
            }
        }
 
        private Object[] ParseArrayRow()
        {
            ArrayList temp = new ArrayList();
            while (true)
            {
                temp.Add(ParseArrayItem());
                SkipWhite();
                switch (look)
                {
                    case '}':
                    case ';':
                        break;
                    case ',':
                        Match(',');
                        continue;
                    default:
                        throw expected("'}' or ','");
 
                }
                break;
            }
 
            Object[] result = new Object[temp.Count];
            result = temp.ToArray();
            return result;
        }
 
        private Object ParseArrayItem()
        {
            SkipWhite();
            switch (look)
            {
                case '"': return ParseStringLiteral();
                case '#': return ErrorConstant.ValueOf(ParseErrorLiteral());
                case 'F':
                case 'f':
                case 'T':
                case 't':
                    return ParseBooleanLiteral();
                case '-':
                    Match('-');
                    SkipWhite();
                    return ConvertArrayNumber(ParseNumber(), false);
            }
            // else assume number
            return ConvertArrayNumber(ParseNumber(), true);
        }
 
        private Boolean ParseBooleanLiteral()
        {
            String iden = ParseUnquotedIdentifier();
            if ("TRUE".Equals(iden, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
            if ("FALSE".Equals(iden, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
            throw expected("'TRUE' or 'FALSE'");
        }
 
        private static Double ConvertArrayNumber(Ptg ptg, bool isPositive)
        {
            double value;
            if (ptg is IntPtg)
            {
                value = ((IntPtg)ptg).Value;
            }
            else if (ptg is NumberPtg)
            {
                value = ((NumberPtg)ptg).Value;
            }
            else
            {
                throw new Exception("Unexpected ptg (" + ptg.GetType().Name + ")");
            }
            if (!isPositive)
            {
                value = -value;
            }
            return value;
        }
 
        private Ptg ParseNumber()
        {
            String number2 = null;
            String exponent = null;
            String number1 = GetNum();
 
            if (look == '.')
            {
                GetChar();
                number2 = GetNum();
            }
 
            if (look == 'E')
            {
                GetChar();
 
                String sign = "";
                if (look == '+')
                {
                    GetChar();
                }
                else if (look == '-')
                {
                    GetChar();
                    sign = "-";
                }
 
                String number = GetNum();
                if (number == null)
                {
                    throw expected("int");
                }
                exponent = sign + number;
            }
 
            if (number1 == null && number2 == null)
            {
                throw expected("int");
            }
 
            return GetNumberPtgFromString(number1, number2, exponent);
        }
 
 
        private int ParseErrorLiteral()
        {
            Match('#');
            String part1 = ParseUnquotedIdentifier().ToUpper();
 
            switch (part1[0])
            {
                case 'V':
                    if (part1.Equals("VALUE"))
                    {
                        Match('!');
                        return HSSFErrorConstants.ERROR_VALUE;
                    }
                    throw expected("#VALUE!");
                case 'R':
                    if (part1.Equals("REF"))
                    {
                        Match('!');
                        return HSSFErrorConstants.ERROR_REF;
                    }
                    throw expected("#REF!");
                case 'D':
                    if (part1.Equals("DIV"))
                    {
                        Match('/');
                        Match('0');
                        Match('!');
                        return HSSFErrorConstants.ERROR_DIV_0;
                    }
                    throw expected("#DIV/0!");
                case 'N':
                    if (part1.Equals("NAME"))
                    {
                        Match('?');  // only one that ends in '?'
                        return HSSFErrorConstants.ERROR_NAME;
                    }
                    if (part1.Equals("NUM"))
                    {
                        Match('!');
                        return HSSFErrorConstants.ERROR_NUM;
                    }
                    if (part1.Equals("NULL"))
                    {
                        Match('!');
                        return HSSFErrorConstants.ERROR_NULL;
                    }
                    if (part1.Equals("N"))
                    {
                        Match('/');
                        if (look != 'A' && look != 'a')
                        {
                            throw expected("#N/A");
                        }
                        Match(look);
                        // Note - no '!' or '?' suffix
                        return HSSFErrorConstants.ERROR_NA;
                    }
                    throw expected("#NAME?, #NUM!, #NULL! or #N/A");
 
            }
            throw expected("#VALUE!, #REF!, #DIV/0!, #NAME?, #NUM!, #NULL! or #N/A");
        }
 
 
        /**
         * Get a PTG for an integer from its string representation.
         * return Int or Number Ptg based on size of input
         */
        private static Ptg GetNumberPtgFromString(String number1, String number2, String exponent)
        {
            StringBuilder number = new StringBuilder();
 
            if (number2 == null)
            {
                number.Append(number1);
 
                if (exponent != null)
                {
                    number.Append('E');
                    number.Append(exponent);
                }
 
                String numberStr = number.ToString();
                int intVal;
                try
                {
                    intVal = int.Parse(numberStr, CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                    return new NumberPtg(numberStr);
                }
                catch (OverflowException)
                {
                    return new NumberPtg(numberStr);
                }
                if (IntPtg.IsInRange(intVal))
                {
                    return new IntPtg(intVal);
                }
                return new NumberPtg(numberStr);
            }
 
            if (number1 != null)
            {
                number.Append(number1);
            }
 
            number.Append('.');
            number.Append(number2);
 
            if (exponent != null)
            {
                number.Append('E');
                number.Append(exponent);
            }
 
            return new NumberPtg(number.ToString());
        }
 
 
        private String ParseStringLiteral()
        {
            Match('"');
 
            StringBuilder Token = new StringBuilder();
            while (true)
            {
                if (look == '"')
                {
                    GetChar();
                    if (look != '"')
                    {
                        break;
                    }
                }
                Token.Append(look);
                GetChar();
            }
            return Token.ToString();
        }
 
        /** Parse and Translate a Math Term */
        private ParseNode Term()
        {
            ParseNode result = PowerFactor();
            while (true)
            {
                SkipWhite();
                Ptg operator1;
                switch (look)
                {
                    case '*':
                        Match('*');
                        operator1 = MultiplyPtg.instance;
                        break;
                    case '/':
                        Match('/');
                        operator1 = DividePtg.instance;
                        break;
                    default:
                        return result; // finished with Term
                }
                ParseNode other = PowerFactor();
                result = new ParseNode(operator1, result, other);
            }
        }
 
        private ParseNode ComparisonExpression()
        {
            ParseNode result = ConcatExpression();
            while (true)
            {
                SkipWhite();
                switch (look)
                {
                    case '=':
                    case '>':
                    case '<':
                        Ptg comparisonToken = GetComparisonToken();
                        ParseNode other = ConcatExpression();
                        result = new ParseNode(comparisonToken, result, other);
                        continue;
                }
                return result; // finished with predicate expression
            }
        }
 
        private Ptg GetComparisonToken()
        {
            if (look == '=')
            {
                Match(look);
                return EqualPtg.instance;
            }
            bool IsGreater = look == '>';
            Match(look);
            if (IsGreater)
            {
                if (look == '=')
                {
                    Match('=');
                    return GreaterEqualPtg.instance;
                }
                return GreaterThanPtg.instance;
            }
            switch (look)
            {
                case '=':
                    Match('=');
                    return LessEqualPtg.instance;
                case '>':
                    Match('>');
                    return NotEqualPtg.instance;
            }
            return LessThanPtg.instance;
        }
 
 
        private ParseNode ConcatExpression()
        {
            ParseNode result = AdditiveExpression();
            while (true)
            {
                SkipWhite();
                if (look != '&')
                {
                    break; // finished with concat expression
                }
                Match('&');
                ParseNode other = AdditiveExpression();
                result = new ParseNode(ConcatPtg.instance, result, other);
            }
            return result;
        }
 
 
        /** Parse and Translate an Expression */
        private ParseNode AdditiveExpression()
        {
            ParseNode result = Term();
            while (true)
            {
                SkipWhite();
                Ptg operator1;
                switch (look)
                {
                    case '+':
                        Match('+');
                        operator1 = AddPtg.instance;
                        break;
                    case '-':
                        Match('-');
                        operator1 = SubtractPtg.instance;
                        break;
                    default:
                        return result; // finished with Additive expression
                }
                ParseNode other = Term();
                result = new ParseNode(operator1, result, other);
            }
        }
 
        //{--------------------------------------------------------------}
        //{ Parse and Translate an Assignment Statement }
        /*
    procedure Assignment;
    var Name: string[8];
    begin
       Name := GetName;
       Match('=');
       Expression;
 
    end;
         **/
 
 
        /**
         *  API call To execute the parsing of the formula
         * 
         */
        private void Parse()
        {
            pointer = 0;
            GetChar();
            _rootNode = UnionExpression();
 
            if (pointer <= formulaLength)
            {
                String msg = "Unused input [" + formulaString.Substring(pointer - 1)
                    + "] after attempting To Parse the formula [" + formulaString + "]";
                throw new FormulaParseException(msg);
            }
        }
        private ParseNode UnionExpression()
        {
            ParseNode result = ComparisonExpression();
            bool hasUnions = false;
            while (true)
            {
                SkipWhite();
                switch (look)
                {
                    case ',':
                        GetChar();
                        hasUnions = true;
                        ParseNode other = ComparisonExpression();
                        result = new ParseNode(UnionPtg.instance, result, other);
                        continue;
                }
                if (hasUnions)
                {
                    return AugmentWithMemPtg(result);
                }
                return result;
            }
        }
 
 
        private Ptg[] GetRPNPtg(FormulaType formulaType)
        {
            OperandClassTransformer oct = new OperandClassTransformer(formulaType);
            // RVA is for 'operand class': 'reference', 'value', 'array'
            oct.TransformFormula(_rootNode);
            return ParseNode.ToTokenArray(_rootNode);
        }
    }
}