Parser::matchRangeSheetnameQuoted()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
ccs 4
cts 4
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
8
use PhpOffice\PhpSpreadsheet\Spreadsheet;
9
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
10
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
11
12
// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class):
13
// -----------------------------------------------------------------------------------------
14
// *  Class for parsing Excel formulas
15
// *
16
// *  License Information:
17
// *
18
// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
19
// *    Copyright (c) 2002-2003 Xavier Noguer [email protected]
20
// *
21
// *    This library is free software; you can redistribute it and/or
22
// *    modify it under the terms of the GNU Lesser General Public
23
// *    License as published by the Free Software Foundation; either
24
// *    version 2.1 of the License, or (at your option) any later version.
25
// *
26
// *    This library is distributed in the hope that it will be useful,
27
// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
28
// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
29
// *    Lesser General Public License for more details.
30
// *
31
// *    You should have received a copy of the GNU Lesser General Public
32
// *    License along with this library; if not, write to the Free Software
33
// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
34
// */
35
class Parser
36
{
37
    /**    Constants                */
38
    // Sheet title in unquoted form
39
    // Invalid sheet title characters cannot occur in the sheet title:
40
    //         *:/\?[]
41
    // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
42
    // +-% '^&<>=,;#()"{}
43
    const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
44
45
    // Sheet title in quoted form (without surrounding quotes)
46
    // Invalid sheet title characters cannot occur in the sheet title:
47
    // *:/\?[]                    (usual invalid sheet title characters)
48
    // Single quote is represented as a pair ''
49
    // Former value for this constant led to "catastrophic backtracking",
50
    //     unable to handle double apostrophes.
51
    //     (*COMMIT) should prevent this.
52
    const REGEX_SHEET_TITLE_QUOTED = "([^*:/\\\\?\\[\\]']|'')+";
53
54
    const REGEX_CELL_TITLE_QUOTED = "~^'"
55
        . self::REGEX_SHEET_TITLE_QUOTED
56
        . '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
57
        . "'!(*COMMIT)"
58
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
59
        . '$~u';
60
61
    const REGEX_RANGE_TITLE_QUOTED = "~^'"
62
        . self::REGEX_SHEET_TITLE_QUOTED
63
        . '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
64
        . "'!(*COMMIT)"
65
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
66
        . ':'
67
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
68
        . '$~u';
69
70
    private const UTF8 = 'UTF-8';
71
72
    /**
73
     * The index of the character we are currently looking at.
74
     */
75
    public int $currentCharacter;
76
77
    /**
78
     * The token we are working on.
79
     */
80
    public string $currentToken;
81
82
    /**
83
     * The formula to parse.
84
     */
85
    private string $formula;
86
87
    /**
88
     * The character ahead of the current char.
89
     */
90
    public string $lookAhead;
91
92
    /**
93
     * The parse tree to be generated.
94
     *
95
     * @var mixed[]|string
96
     */
97
    public array|string $parseTree;
98
99
    /**
100
     * Array of external sheets.
101
     *
102
     * @var array<string, int>
103
     */
104
    private array $externalSheets;
105
106
    /**
107
     * Array of sheet references in the form of REF structures.
108
     *
109
     * @var array<int|string, int|string>
110
     */
111
    public array $references;
112
113
    /**
114
     * The Excel ptg indices.
115
     *
116
     * @var array<string, int>
117
     */
118
    private array $ptg = [
119
        'ptgExp' => 0x01,
120
        'ptgTbl' => 0x02,
121
        'ptgAdd' => 0x03,
122
        'ptgSub' => 0x04,
123
        'ptgMul' => 0x05,
124
        'ptgDiv' => 0x06,
125
        'ptgPower' => 0x07,
126
        'ptgConcat' => 0x08,
127
        'ptgLT' => 0x09,
128
        'ptgLE' => 0x0A,
129
        'ptgEQ' => 0x0B,
130
        'ptgGE' => 0x0C,
131
        'ptgGT' => 0x0D,
132
        'ptgNE' => 0x0E,
133
        'ptgIsect' => 0x0F,
134
        'ptgUnion' => 0x10,
135
        'ptgRange' => 0x11,
136
        'ptgUplus' => 0x12,
137
        'ptgUminus' => 0x13,
138
        'ptgPercent' => 0x14,
139
        'ptgParen' => 0x15,
140
        'ptgMissArg' => 0x16,
141
        'ptgStr' => 0x17,
142
        'ptgAttr' => 0x19,
143
        'ptgSheet' => 0x1A,
144
        'ptgEndSheet' => 0x1B,
145
        'ptgErr' => 0x1C,
146
        'ptgBool' => 0x1D,
147
        'ptgInt' => 0x1E,
148
        'ptgNum' => 0x1F,
149
        'ptgArray' => 0x20,
150
        'ptgFunc' => 0x21,
151
        'ptgFuncVar' => 0x22,
152
        'ptgName' => 0x23,
153
        'ptgRef' => 0x24,
154
        'ptgArea' => 0x25,
155
        'ptgMemArea' => 0x26,
156
        'ptgMemErr' => 0x27,
157
        'ptgMemNoMem' => 0x28,
158
        'ptgMemFunc' => 0x29,
159
        'ptgRefErr' => 0x2A,
160
        'ptgAreaErr' => 0x2B,
161
        'ptgRefN' => 0x2C,
162
        'ptgAreaN' => 0x2D,
163
        'ptgMemAreaN' => 0x2E,
164
        'ptgMemNoMemN' => 0x2F,
165
        'ptgNameX' => 0x39,
166
        'ptgRef3d' => 0x3A,
167
        'ptgArea3d' => 0x3B,
168
        'ptgRefErr3d' => 0x3C,
169
        'ptgAreaErr3d' => 0x3D,
170
        'ptgArrayV' => 0x40,
171
        'ptgFuncV' => 0x41,
172
        'ptgFuncVarV' => 0x42,
173
        'ptgNameV' => 0x43,
174
        'ptgRefV' => 0x44,
175
        'ptgAreaV' => 0x45,
176
        'ptgMemAreaV' => 0x46,
177
        'ptgMemErrV' => 0x47,
178
        'ptgMemNoMemV' => 0x48,
179
        'ptgMemFuncV' => 0x49,
180
        'ptgRefErrV' => 0x4A,
181
        'ptgAreaErrV' => 0x4B,
182
        'ptgRefNV' => 0x4C,
183
        'ptgAreaNV' => 0x4D,
184
        'ptgMemAreaNV' => 0x4E,
185
        'ptgMemNoMemNV' => 0x4F,
186
        'ptgFuncCEV' => 0x58,
187
        'ptgNameXV' => 0x59,
188
        'ptgRef3dV' => 0x5A,
189
        'ptgArea3dV' => 0x5B,
190
        'ptgRefErr3dV' => 0x5C,
191
        'ptgAreaErr3dV' => 0x5D,
192
        'ptgArrayA' => 0x60,
193
        'ptgFuncA' => 0x61,
194
        'ptgFuncVarA' => 0x62,
195
        'ptgNameA' => 0x63,
196
        'ptgRefA' => 0x64,
197
        'ptgAreaA' => 0x65,
198
        'ptgMemAreaA' => 0x66,
199
        'ptgMemErrA' => 0x67,
200
        'ptgMemNoMemA' => 0x68,
201
        'ptgMemFuncA' => 0x69,
202
        'ptgRefErrA' => 0x6A,
203
        'ptgAreaErrA' => 0x6B,
204
        'ptgRefNA' => 0x6C,
205
        'ptgAreaNA' => 0x6D,
206
        'ptgMemAreaNA' => 0x6E,
207
        'ptgMemNoMemNA' => 0x6F,
208
        'ptgFuncCEA' => 0x78,
209
        'ptgNameXA' => 0x79,
210
        'ptgRef3dA' => 0x7A,
211
        'ptgArea3dA' => 0x7B,
212
        'ptgRefErr3dA' => 0x7C,
213
        'ptgAreaErr3dA' => 0x7D,
214
    ];
215
216
    /**
217
     * Thanks to Michael Meeks and Gnumeric for the initial arg values.
218
     *
219
     * The following hash was generated by "function_locale.pl" in the distro.
220
     * Refer to function_locale.pl for non-English function names.
221
     *
222
     * The array elements are as follow:
223
     * ptg:   The Excel function ptg code.
224
     * args:  The number of arguments that the function takes:
225
     *           >=0 is a fixed number of arguments.
226
     *           -1  is a variable  number of arguments.
227
     * class: The reference, value or array class of the function args.
228
     * vol:   The function is volatile.
229
     *
230
     * @var array<string, array{int, int, int, int}>
231
     */
232
    private array $functions = [
233
        // function                  ptg  args  class  vol
234
        'COUNT' => [0, -1, 0, 0],
235
        'IF' => [1, -1, 1, 0],
236
        'ISNA' => [2, 1, 1, 0],
237
        'ISERROR' => [3, 1, 1, 0],
238
        'SUM' => [4, -1, 0, 0],
239
        'AVERAGE' => [5, -1, 0, 0],
240
        'MIN' => [6, -1, 0, 0],
241
        'MAX' => [7, -1, 0, 0],
242
        'ROW' => [8, -1, 0, 0],
243
        'COLUMN' => [9, -1, 0, 0],
244
        'NA' => [10, 0, 0, 0],
245
        'NPV' => [11, -1, 1, 0],
246
        'STDEV' => [12, -1, 0, 0],
247
        'DOLLAR' => [13, -1, 1, 0],
248
        'FIXED' => [14, -1, 1, 0],
249
        'SIN' => [15, 1, 1, 0],
250
        'COS' => [16, 1, 1, 0],
251
        'TAN' => [17, 1, 1, 0],
252
        'ATAN' => [18, 1, 1, 0],
253
        'PI' => [19, 0, 1, 0],
254
        'SQRT' => [20, 1, 1, 0],
255
        'EXP' => [21, 1, 1, 0],
256
        'LN' => [22, 1, 1, 0],
257
        'LOG10' => [23, 1, 1, 0],
258
        'ABS' => [24, 1, 1, 0],
259
        'INT' => [25, 1, 1, 0],
260
        'SIGN' => [26, 1, 1, 0],
261
        'ROUND' => [27, 2, 1, 0],
262
        'LOOKUP' => [28, -1, 0, 0],
263
        'INDEX' => [29, -1, 0, 1],
264
        'REPT' => [30, 2, 1, 0],
265
        'MID' => [31, 3, 1, 0],
266
        'LEN' => [32, 1, 1, 0],
267
        'VALUE' => [33, 1, 1, 0],
268
        'TRUE' => [34, 0, 1, 0],
269
        'FALSE' => [35, 0, 1, 0],
270
        'AND' => [36, -1, 0, 0],
271
        'OR' => [37, -1, 0, 0],
272
        'NOT' => [38, 1, 1, 0],
273
        'MOD' => [39, 2, 1, 0],
274
        'DCOUNT' => [40, 3, 0, 0],
275
        'DSUM' => [41, 3, 0, 0],
276
        'DAVERAGE' => [42, 3, 0, 0],
277
        'DMIN' => [43, 3, 0, 0],
278
        'DMAX' => [44, 3, 0, 0],
279
        'DSTDEV' => [45, 3, 0, 0],
280
        'VAR' => [46, -1, 0, 0],
281
        'DVAR' => [47, 3, 0, 0],
282
        'TEXT' => [48, 2, 1, 0],
283
        'LINEST' => [49, -1, 0, 0],
284
        'TREND' => [50, -1, 0, 0],
285
        'LOGEST' => [51, -1, 0, 0],
286
        'GROWTH' => [52, -1, 0, 0],
287
        'PV' => [56, -1, 1, 0],
288
        'FV' => [57, -1, 1, 0],
289
        'NPER' => [58, -1, 1, 0],
290
        'PMT' => [59, -1, 1, 0],
291
        'RATE' => [60, -1, 1, 0],
292
        'MIRR' => [61, 3, 0, 0],
293
        'IRR' => [62, -1, 0, 0],
294
        'RAND' => [63, 0, 1, 1],
295
        'MATCH' => [64, -1, 0, 0],
296
        'DATE' => [65, 3, 1, 0],
297
        'TIME' => [66, 3, 1, 0],
298
        'DAY' => [67, 1, 1, 0],
299
        'MONTH' => [68, 1, 1, 0],
300
        'YEAR' => [69, 1, 1, 0],
301
        'WEEKDAY' => [70, -1, 1, 0],
302
        'HOUR' => [71, 1, 1, 0],
303
        'MINUTE' => [72, 1, 1, 0],
304
        'SECOND' => [73, 1, 1, 0],
305
        'NOW' => [74, 0, 1, 1],
306
        'AREAS' => [75, 1, 0, 1],
307
        'ROWS' => [76, 1, 0, 1],
308
        'COLUMNS' => [77, 1, 0, 1],
309
        'OFFSET' => [78, -1, 0, 1],
310
        'SEARCH' => [82, -1, 1, 0],
311
        'TRANSPOSE' => [83, 1, 1, 0],
312
        'TYPE' => [86, 1, 1, 0],
313
        'ATAN2' => [97, 2, 1, 0],
314
        'ASIN' => [98, 1, 1, 0],
315
        'ACOS' => [99, 1, 1, 0],
316
        'CHOOSE' => [100, -1, 1, 0],
317
        'HLOOKUP' => [101, -1, 0, 0],
318
        'VLOOKUP' => [102, -1, 0, 0],
319
        'ISREF' => [105, 1, 0, 0],
320
        'LOG' => [109, -1, 1, 0],
321
        'CHAR' => [111, 1, 1, 0],
322
        'LOWER' => [112, 1, 1, 0],
323
        'UPPER' => [113, 1, 1, 0],
324
        'PROPER' => [114, 1, 1, 0],
325
        'LEFT' => [115, -1, 1, 0],
326
        'RIGHT' => [116, -1, 1, 0],
327
        'EXACT' => [117, 2, 1, 0],
328
        'TRIM' => [118, 1, 1, 0],
329
        'REPLACE' => [119, 4, 1, 0],
330
        'SUBSTITUTE' => [120, -1, 1, 0],
331
        'CODE' => [121, 1, 1, 0],
332
        'FIND' => [124, -1, 1, 0],
333
        'CELL' => [125, -1, 0, 1],
334
        'ISERR' => [126, 1, 1, 0],
335
        'ISTEXT' => [127, 1, 1, 0],
336
        'ISNUMBER' => [128, 1, 1, 0],
337
        'ISBLANK' => [129, 1, 1, 0],
338
        'T' => [130, 1, 0, 0],
339
        'N' => [131, 1, 0, 0],
340
        'DATEVALUE' => [140, 1, 1, 0],
341
        'TIMEVALUE' => [141, 1, 1, 0],
342
        'SLN' => [142, 3, 1, 0],
343
        'SYD' => [143, 4, 1, 0],
344
        'DDB' => [144, -1, 1, 0],
345
        'INDIRECT' => [148, -1, 1, 1],
346
        'CALL' => [150, -1, 1, 0],
347
        'CLEAN' => [162, 1, 1, 0],
348
        'MDETERM' => [163, 1, 2, 0],
349
        'MINVERSE' => [164, 1, 2, 0],
350
        'MMULT' => [165, 2, 2, 0],
351
        'IPMT' => [167, -1, 1, 0],
352
        'PPMT' => [168, -1, 1, 0],
353
        'COUNTA' => [169, -1, 0, 0],
354
        'PRODUCT' => [183, -1, 0, 0],
355
        'FACT' => [184, 1, 1, 0],
356
        'DPRODUCT' => [189, 3, 0, 0],
357
        'ISNONTEXT' => [190, 1, 1, 0],
358
        'STDEVP' => [193, -1, 0, 0],
359
        'VARP' => [194, -1, 0, 0],
360
        'DSTDEVP' => [195, 3, 0, 0],
361
        'DVARP' => [196, 3, 0, 0],
362
        'TRUNC' => [197, -1, 1, 0],
363
        'ISLOGICAL' => [198, 1, 1, 0],
364
        'DCOUNTA' => [199, 3, 0, 0],
365
        'USDOLLAR' => [204, -1, 1, 0],
366
        'FINDB' => [205, -1, 1, 0],
367
        'SEARCHB' => [206, -1, 1, 0],
368
        'REPLACEB' => [207, 4, 1, 0],
369
        'LEFTB' => [208, -1, 1, 0],
370
        'RIGHTB' => [209, -1, 1, 0],
371
        'MIDB' => [210, 3, 1, 0],
372
        'LENB' => [211, 1, 1, 0],
373
        'ROUNDUP' => [212, 2, 1, 0],
374
        'ROUNDDOWN' => [213, 2, 1, 0],
375
        'ASC' => [214, 1, 1, 0],
376
        'DBCS' => [215, 1, 1, 0],
377
        'RANK' => [216, -1, 0, 0],
378
        'ADDRESS' => [219, -1, 1, 0],
379
        'DAYS360' => [220, -1, 1, 0],
380
        'TODAY' => [221, 0, 1, 1],
381
        'VDB' => [222, -1, 1, 0],
382
        'MEDIAN' => [227, -1, 0, 0],
383
        'SUMPRODUCT' => [228, -1, 2, 0],
384
        'SINH' => [229, 1, 1, 0],
385
        'COSH' => [230, 1, 1, 0],
386
        'TANH' => [231, 1, 1, 0],
387
        'ASINH' => [232, 1, 1, 0],
388
        'ACOSH' => [233, 1, 1, 0],
389
        'ATANH' => [234, 1, 1, 0],
390
        'DGET' => [235, 3, 0, 0],
391
        'INFO' => [244, 1, 1, 1],
392
        'DB' => [247, -1, 1, 0],
393
        'FREQUENCY' => [252, 2, 0, 0],
394
        'ERROR.TYPE' => [261, 1, 1, 0],
395
        'REGISTER.ID' => [267, -1, 1, 0],
396
        'AVEDEV' => [269, -1, 0, 0],
397
        'BETADIST' => [270, -1, 1, 0],
398
        'GAMMALN' => [271, 1, 1, 0],
399
        'BETAINV' => [272, -1, 1, 0],
400
        'BINOMDIST' => [273, 4, 1, 0],
401
        'CHIDIST' => [274, 2, 1, 0],
402
        'CHIINV' => [275, 2, 1, 0],
403
        'COMBIN' => [276, 2, 1, 0],
404
        'CONFIDENCE' => [277, 3, 1, 0],
405
        'CRITBINOM' => [278, 3, 1, 0],
406
        'EVEN' => [279, 1, 1, 0],
407
        'EXPONDIST' => [280, 3, 1, 0],
408
        'FDIST' => [281, 3, 1, 0],
409
        'FINV' => [282, 3, 1, 0],
410
        'FISHER' => [283, 1, 1, 0],
411
        'FISHERINV' => [284, 1, 1, 0],
412
        'FLOOR' => [285, 2, 1, 0],
413
        'FLOOR.XCL' => [285, 2, 1, 0],
414
        'GAMMADIST' => [286, 4, 1, 0],
415
        'GAMMAINV' => [287, 3, 1, 0],
416
        'CEILING' => [288, 2, 1, 0],
417
        'CEILING.XCL' => [288, 2, 1, 0],
418
        'HYPGEOMDIST' => [289, 4, 1, 0],
419
        'LOGNORMDIST' => [290, 3, 1, 0],
420
        'LOGINV' => [291, 3, 1, 0],
421
        'NEGBINOMDIST' => [292, 3, 1, 0],
422
        'NORMDIST' => [293, 4, 1, 0],
423
        'NORMSDIST' => [294, 1, 1, 0],
424
        'NORMINV' => [295, 3, 1, 0],
425
        'NORMSINV' => [296, 1, 1, 0],
426
        'STANDARDIZE' => [297, 3, 1, 0],
427
        'ODD' => [298, 1, 1, 0],
428
        'PERMUT' => [299, 2, 1, 0],
429
        'POISSON' => [300, 3, 1, 0],
430
        'TDIST' => [301, 3, 1, 0],
431
        'WEIBULL' => [302, 4, 1, 0],
432
        'SUMXMY2' => [303, 2, 2, 0],
433
        'SUMX2MY2' => [304, 2, 2, 0],
434
        'SUMX2PY2' => [305, 2, 2, 0],
435
        'CHITEST' => [306, 2, 2, 0],
436
        'CORREL' => [307, 2, 2, 0],
437
        'COVAR' => [308, 2, 2, 0],
438
        'FORECAST' => [309, 3, 2, 0],
439
        'FTEST' => [310, 2, 2, 0],
440
        'INTERCEPT' => [311, 2, 2, 0],
441
        'PEARSON' => [312, 2, 2, 0],
442
        'RSQ' => [313, 2, 2, 0],
443
        'STEYX' => [314, 2, 2, 0],
444
        'SLOPE' => [315, 2, 2, 0],
445
        'TTEST' => [316, 4, 2, 0],
446
        'PROB' => [317, -1, 2, 0],
447
        'DEVSQ' => [318, -1, 0, 0],
448
        'GEOMEAN' => [319, -1, 0, 0],
449
        'HARMEAN' => [320, -1, 0, 0],
450
        'SUMSQ' => [321, -1, 0, 0],
451
        'KURT' => [322, -1, 0, 0],
452
        'SKEW' => [323, -1, 0, 0],
453
        'ZTEST' => [324, -1, 0, 0],
454
        'LARGE' => [325, 2, 0, 0],
455
        'SMALL' => [326, 2, 0, 0],
456
        'QUARTILE' => [327, 2, 0, 0],
457
        'PERCENTILE' => [328, 2, 0, 0],
458
        'PERCENTRANK' => [329, -1, 0, 0],
459
        'MODE' => [330, -1, 2, 0],
460
        'TRIMMEAN' => [331, 2, 0, 0],
461
        'TINV' => [332, 2, 1, 0],
462
        'CONCATENATE' => [336, -1, 1, 0],
463
        'POWER' => [337, 2, 1, 0],
464
        'RADIANS' => [342, 1, 1, 0],
465
        'DEGREES' => [343, 1, 1, 0],
466
        'SUBTOTAL' => [344, -1, 0, 0],
467
        'SUMIF' => [345, -1, 0, 0],
468
        'COUNTIF' => [346, 2, 0, 0],
469
        'COUNTBLANK' => [347, 1, 0, 0],
470
        'ISPMT' => [350, 4, 1, 0],
471
        'DATEDIF' => [351, 3, 1, 0],
472
        'DATESTRING' => [352, 1, 1, 0],
473
        'NUMBERSTRING' => [353, 2, 1, 0],
474
        'ROMAN' => [354, -1, 1, 0],
475
        'GETPIVOTDATA' => [358, -1, 0, 0],
476
        'HYPERLINK' => [359, -1, 1, 0],
477
        'PHONETIC' => [360, 1, 0, 0],
478
        'AVERAGEA' => [361, -1, 0, 0],
479
        'MAXA' => [362, -1, 0, 0],
480
        'MINA' => [363, -1, 0, 0],
481
        'STDEVPA' => [364, -1, 0, 0],
482
        'VARPA' => [365, -1, 0, 0],
483
        'STDEVA' => [366, -1, 0, 0],
484
        'VARA' => [367, -1, 0, 0],
485
        'BAHTTEXT' => [368, 1, 0, 0],
486
    ];
487
488
    private Spreadsheet $spreadsheet;
489
490
    /**
491
     * The class constructor.
492
     */
493 125
    public function __construct(Spreadsheet $spreadsheet)
494
    {
495 125
        $this->spreadsheet = $spreadsheet;
496
497 125
        $this->currentCharacter = 0;
498 125
        $this->currentToken = ''; // The token we are working on.
499 125
        $this->formula = ''; // The formula to parse.
500 125
        $this->lookAhead = ''; // The character ahead of the current char.
501 125
        $this->parseTree = ''; // The parse tree to be generated.
502 125
        $this->externalSheets = [];
503 125
        $this->references = [];
504
    }
505
506
    /**
507
     * Convert a token to the proper ptg value.
508
     *
509
     * @param string $token the token to convert
510
     *
511
     * @return string the converted token on success
512
     */
513 55
    private function convert(string $token): string
514
    {
515 55
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $token)) {
516 25
            return $this->convertString($token);
517
        }
518 54
        if (is_numeric($token)) {
519 47
            return $this->convertNumber($token);
520
        }
521
        // match references like A1 or $A$1
522 52
        if (Preg::isMatch('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
523 30
            return $this->convertRef2d($token);
524
        }
525
        // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
526 52
        if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\!\$?[A-Ia-i]?[A-Za-z]\$?(\d+)$/u', $token)) {
527 1
            return $this->convertRef3d($token);
528
        }
529
        // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
530 52
        if (self::matchCellSheetnameQuoted($token)) {
531 8
            return $this->convertRef3d($token);
532
        }
533
        // match ranges like A1:B2 or $A$1:$B$2
534 50
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
535 26
            return $this->convertRange2d($token);
536
        }
537
        // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
538 49
        if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\!\$?([A-Ia-i]?[A-Za-z])?\$?(\d+)\:\$?([A-Ia-i]?[A-Za-z])?\$?(\d+)$/u', $token)) {
539
            return $this->convertRange3d($token);
540
        }
541
        // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
542 49
        if (self::matchRangeSheetnameQuoted($token)) {
543 4
            return $this->convertRange3d($token);
544
        }
545
        // operators (including parentheses)
546 49
        if (isset($this->ptg[$token])) {
547 29
            return pack('C', $this->ptg[$token]);
548
        }
549
        // match error codes
550 40
        if (Preg::isMatch('/^#[A-Z0\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') {
551 1
            return $this->convertError($token);
552
        }
553 40
        if (Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
554 6
            return $this->convertDefinedName($token);
555
        }
556
        // commented so argument number can be processed correctly. See toReversePolish().
557
        /*if (Preg::isMatch("/[A-Z0-9\xc0-\xdc\.]+/", $token))
558
        {
559
            return($this->convertFunction($token, $this->_func_args));
560
        }*/
561
        // if it's an argument, ignore the token (the argument remains)
562 37
        if ($token == 'arg') {
563 36
            return '';
564
        }
565 3
        if (Preg::isMatch('/^true$/i', $token)) {
566 2
            return $this->convertBool(1);
567
        }
568 3
        if (Preg::isMatch('/^false$/i', $token)) {
569 2
            return $this->convertBool(0);
570
        }
571
572
        // TODO: use real error codes
573 1
        throw new WriterException("Unknown token $token");
574
    }
575
576
    /**
577
     * Convert a number token to ptgInt or ptgNum.
578
     *
579
     * @param float|int|string $num an integer or double for conversion to its ptg value
580
     */
581 47
    private function convertNumber(mixed $num): string
582
    {
583
        // Integer in the range 0..2**16-1
584 47
        if ((Preg::isMatch('/^\d+$/', (string) $num)) && ($num <= 65535)) {
585 47
            return pack('Cv', $this->ptg['ptgInt'], $num);
586
        }
587
588
        // A float
589 13
        if (BIFFwriter::getByteOrder()) { // if it's Big Endian
590
            $num = strrev((string) $num);
591
        }
592
593 13
        return pack('Cd', $this->ptg['ptgNum'], $num);
594
    }
595
596 2
    private function convertBool(int $num): string
597
    {
598 2
        return pack('CC', $this->ptg['ptgBool'], $num);
599
    }
600
601
    /**
602
     * Convert a string token to ptgStr.
603
     *
604
     * @param string $string a string for conversion to its ptg value
605
     *
606
     * @return string the converted token
607
     */
608 25
    private function convertString(string $string): string
609
    {
610
        // chop away beggining and ending quotes
611 25
        $string = substr($string, 1, -1);
612 25
        if (strlen($string) > 255) {
613
            throw new WriterException('String is too long');
614
        }
615
616 25
        return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string);
617
    }
618
619
    /**
620
     * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
621
     * args that it takes.
622
     *
623
     * @param string $token the name of the function for convertion to ptg value
624
     * @param int $num_args the number of arguments the function receives
625
     *
626
     * @return string The packed ptg for the function
627
     */
628 35
    private function convertFunction(string $token, int $num_args): string
629
    {
630 35
        $args = $this->functions[$token][1];
631
632
        // Fixed number of args eg. TIME($i, $j, $k).
633 35
        if ($args >= 0) {
634 15
            return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]);
635
        }
636
637
        // Variable number of args eg. SUM($i, $j, $k, ..).
638 31
        return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
639
    }
640
641
    /**
642
     * Convert an Excel range such as A1:D4 to a ptgRefV.
643
     *
644
     * @param string $range An Excel range in the A1:A2
645
     */
646 26
    private function convertRange2d(string $range, int $class = 0): string
647
    {
648
        // TODO: possible class value 0,1,2 check Formula.pm
649
        // Split the range into 2 cell refs
650 26
        if (Preg::isMatch('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
651 26
            [$cell1, $cell2] = explode(':', $range);
652
        } else {
653
            // TODO: use real error codes
654
            throw new WriterException('Unknown range separator');
655
        }
656
        // Convert the cell references
657 26
        [$row1, $col1] = $this->cellToPackedRowcol($cell1);
658 26
        [$row2, $col2] = $this->cellToPackedRowcol($cell2);
659
660
        // The ptg value depends on the class of the ptg.
661 26
        if ($class == 0) {
662 26
            $ptgArea = pack('C', $this->ptg['ptgArea']);
663
        } elseif ($class == 1) {
664
            $ptgArea = pack('C', $this->ptg['ptgAreaV']);
665
        } elseif ($class == 2) {
666
            $ptgArea = pack('C', $this->ptg['ptgAreaA']);
667
        } else {
668
            // TODO: use real error codes
669
            throw new WriterException("Unknown class $class");
670
        }
671
672 26
        return $ptgArea . $row1 . $row2 . $col1 . $col2;
673
    }
674
675
    /**
676
     * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
677
     * a ptgArea3d.
678
     *
679
     * @param string $token an Excel range in the Sheet1!A1:A2 format
680
     *
681
     * @return string the packed ptgArea3d token on success
682
     */
683 4
    private function convertRange3d(string $token): string
684
    {
685
        // Split the ref at the ! symbol
686 4
        [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true, true);
687
688
        // Convert the external reference part (different for BIFF8)
689 4
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
690
691
        // Split the range into 2 cell refs
692 4
        [$cell1, $cell2] = explode(':', $range ?? '');
693
694
        // Convert the cell references
695 4
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $cell1)) {
696 4
            [$row1, $col1] = $this->cellToPackedRowcol($cell1);
697 4
            [$row2, $col2] = $this->cellToPackedRowcol($cell2);
698
        } else { // It's a rows range (like 26:27)
699
            [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2);
700
        }
701
702
        // The ptg value depends on the class of the ptg.
703 4
        $ptgArea = pack('C', $this->ptg['ptgArea3d']);
704
705 4
        return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2;
706
    }
707
708
    /**
709
     * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
710
     *
711
     * @param string $cell An Excel cell reference
712
     *
713
     * @return string The cell in packed() format with the corresponding ptg
714
     */
715 30
    private function convertRef2d(string $cell): string
716
    {
717
        // Convert the cell reference
718 30
        $cell_array = $this->cellToPackedRowcol($cell);
719 30
        [$row, $col] = $cell_array;
720
721
        // The ptg value depends on the class of the ptg.
722 30
        $ptgRef = pack('C', $this->ptg['ptgRefA']);
723
724 30
        return $ptgRef . $row . $col;
725
    }
726
727
    /**
728
     * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
729
     * ptgRef3d.
730
     *
731
     * @param string $cell An Excel cell reference
732
     *
733
     * @return string the packed ptgRef3d token on success
734
     */
735 8
    private function convertRef3d(string $cell): string
736
    {
737
        // Split the ref at the ! symbol
738 8
        [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true, true);
739
740
        // Convert the external reference part (different for BIFF8)
741 8
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
742
743
        // Convert the cell reference part
744 7
        [$row, $col] = $this->cellToPackedRowcol($cell ?? '');
745
746
        // The ptg value depends on the class of the ptg.
747 7
        $ptgRef = pack('C', $this->ptg['ptgRef3dA']);
748
749 7
        return $ptgRef . $ext_ref . $row . $col;
750
    }
751
752
    /**
753
     * Convert an error code to a ptgErr.
754
     *
755
     * @param string $errorCode The error code for conversion to its ptg value
756
     *
757
     * @return string The error code ptgErr
758
     */
759 1
    private function convertError(string $errorCode): string
760
    {
761 1
        return match ($errorCode) {
762
            '#NULL!' => pack('C', 0x00),
763
            '#DIV/0!' => pack('C', 0x07),
764
            '#VALUE!' => pack('C', 0x0F),
765
            '#REF!' => pack('C', 0x17),
766 1
            '#NAME?' => pack('C', 0x1D),
767
            '#NUM!' => pack('C', 0x24),
768
            '#N/A' => pack('C', 0x2A),
769 1
            default => pack('C', 0xFF),
770 1
        };
771
    }
772
773
    private bool $tryDefinedName = false;
774
775 6
    private function convertDefinedName(string $name): string
776
    {
777 6
        if (strlen($name) > 255) {
778
            throw new WriterException('Defined Name is too long');
779
        }
780
781 6
        if ($this->tryDefinedName) {
782
            // @codeCoverageIgnoreStart
783
            $nameReference = 1;
784
            foreach ($this->spreadsheet->getDefinedNames() as $definedName) {
785
                if ($name === $definedName->getName()) {
786
                    break;
787
                }
788
                ++$nameReference;
789
            }
790
791
            $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference);
792
793
            return $ptgRef;
794
            // @codeCoverageIgnoreEnd
795
        }
796
797 6
        throw new WriterException('Cannot yet write formulae with defined names to Xls');
798
    }
799
800
    /**
801
     * Look up the REF index that corresponds to an external sheet name
802
     * (or range). If it doesn't exist yet add it to the workbook's references
803
     * array. It assumes all sheet names given must exist.
804
     *
805
     * @param string $ext_ref The name of the external reference
806
     *
807
     * @return string The reference index in packed() format on success
808
     */
809 9
    private function getRefIndex(string $ext_ref): string
810
    {
811 9
        $ext_ref = Preg::replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any.
812 9
        $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
813
814
        // Check if there is a sheet range eg., Sheet1:Sheet2.
815 9
        if (Preg::isMatch('/:/', $ext_ref)) {
816
            [$sheet_name1, $sheet_name2] = explode(':', $ext_ref);
817
818
            $sheet1 = $this->getSheetIndex($sheet_name1);
819
            if ($sheet1 == -1) {
820
                throw new WriterException("Unknown sheet name $sheet_name1 in formula");
821
            }
822
            $sheet2 = $this->getSheetIndex($sheet_name2);
823
            if ($sheet2 == -1) {
824
                throw new WriterException("Unknown sheet name $sheet_name2 in formula");
825
            }
826
827
            // Reverse max and min sheet numbers if necessary
828
            if ($sheet1 > $sheet2) {
829
                [$sheet1, $sheet2] = [$sheet2, $sheet1];
830
            }
831
        } else { // Single sheet name only.
832 9
            $sheet1 = $this->getSheetIndex($ext_ref);
833 9
            if ($sheet1 == -1) {
834 1
                throw new WriterException("Unknown sheet name $ext_ref in formula");
835
            }
836 8
            $sheet2 = $sheet1;
837
        }
838
839
        // assume all references belong to this document
840 8
        $supbook_index = 0x00;
841 8
        $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
842 8
        $totalreferences = count($this->references);
843 8
        $index = -1;
844 8
        for ($i = 0; $i < $totalreferences; ++$i) {
845 8
            if ($ref == $this->references[$i]) {
846 8
                $index = $i;
847
848 8
                break;
849
            }
850
        }
851
        // if REF was not found add it to references array
852 8
        if ($index == -1) {
853
            $this->references[$totalreferences] = $ref;
854
            $index = $totalreferences;
855
        }
856
857 8
        return pack('v', $index);
858
    }
859
860
    /**
861
     * Look up the index that corresponds to an external sheet name. The hash of
862
     * sheet names is updated by the addworksheet() method of the
863
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
864
     *
865
     * @param string $sheet_name Sheet name
866
     *
867
     * @return int The sheet index, -1 if the sheet was not found
868
     */
869 9
    private function getSheetIndex(string $sheet_name): int
870
    {
871 9
        if (!isset($this->externalSheets[$sheet_name])) {
872 1
            return -1;
873
        }
874
875 8
        return $this->externalSheets[$sheet_name];
876
    }
877
878
    /**
879
     * This method is used to update the array of sheet names. It is
880
     * called by the addWorksheet() method of the
881
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
882
     *
883
     * @param string $name The name of the worksheet being added
884
     * @param int $index The index of the worksheet being added
885
     *
886
     * @see Workbook::addWorksheet
887
     */
888 120
    public function setExtSheet(string $name, int $index): void
889
    {
890 120
        $this->externalSheets[$name] = $index;
891
    }
892
893
    /**
894
     * pack() row and column into the required 3 or 4 byte format.
895
     *
896
     * @param string $cell The Excel cell reference to be packed
897
     *
898
     * @return array{string, string} Array containing the row and column in packed() format
899
     */
900 41
    private function cellToPackedRowcol(string $cell): array
901
    {
902 41
        $cell = strtoupper($cell);
903 41
        [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell);
904 41
        if ($col >= 256) {
905
            throw new WriterException("Column in: $cell greater than 255");
906
        }
907 41
        if ($row >= 65536) {
908
            throw new WriterException("Row in: $cell greater than 65536 ");
909
        }
910
911
        // Set the high bits to indicate if row or col are relative.
912 41
        $col |= $col_rel << 14;
913 41
        $col |= $row_rel << 15;
914 41
        $col = pack('v', $col);
915
916 41
        $row = pack('v', $row);
917
918 41
        return [$row, $col];
919
    }
920
921
    /**
922
     * pack() row range into the required 3 or 4 byte format.
923
     * Just using maximum col/rows, which is probably not the correct solution.
924
     *
925
     * @param string $range The Excel range to be packed
926
     *
927
     * @return array{string, string, string, string} Array containing (row1,col1,row2,col2) in packed() format
928
     */
929
    private function rangeToPackedRange(string $range): array
930
    {
931
        if (!Preg::isMatch('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match)) {
932
            // @codeCoverageIgnoreStart
933
            throw new WriterException('Regexp failure in rangeToPackedRange');
934
            // @codeCoverageIgnoreEnd
935
        }
936
        // return absolute rows if there is a $ in the ref
937
        $row1_rel = empty($match[1]) ? 1 : 0;
938
        $row1 = $match[2];
939
        $row2_rel = empty($match[3]) ? 1 : 0;
940
        $row2 = $match[4];
941
        // Convert 1-index to zero-index
942
        --$row1;
943
        --$row2;
944
        // Trick poor inocent Excel
945
        $col1 = 0;
946
        $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
947
948
        // FIXME: this changes for BIFF8
949
        if (($row1 >= 65536) || ($row2 >= 65536)) {
950
            throw new WriterException("Row in: $range greater than 65536 ");
951
        }
952
953
        // Set the high bits to indicate if rows are relative.
954
        $col1 |= $row1_rel << 15;
955
        $col2 |= $row2_rel << 15;
956
        $col1 = pack('v', $col1);
957
        $col2 = pack('v', $col2);
958
959
        $row1 = pack('v', $row1);
960
        $row2 = pack('v', $row2);
961
962
        return [$row1, $col1, $row2, $col2];
963
    }
964
965
    /**
966
     * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
967
     * indexed row and column number. Also returns two (0,1) values to indicate
968
     * whether the row or column are relative references.
969
     *
970
     * @param string $cell the Excel cell reference in A1 format
971
     *
972
     * @return array{int, int, int, int}
973
     */
974 41
    private function cellToRowcol(string $cell): array
975
    {
976 41
        if (!Preg::isMatch('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match)) {
977
            // @codeCoverageIgnoreStart
978
            throw new WriterException('Regexp failure in cellToRowcol');
979
            // @codeCoverageIgnoreEnd
980
        }
981
        // return absolute column if there is a $ in the ref
982 41
        $col_rel = empty($match[1]) ? 1 : 0;
983 41
        $col_ref = $match[2];
984 41
        $row_rel = empty($match[3]) ? 1 : 0;
985 41
        $row = $match[4];
986
987
        // Convert base26 column string to a number.
988 41
        $expn = strlen($col_ref) - 1;
989 41
        $col = 0;
990 41
        $col_ref_length = strlen($col_ref);
991 41
        for ($i = 0; $i < $col_ref_length; ++$i) {
992 41
            $col += (ord($col_ref[$i]) - 64) * 26 ** $expn;
993 41
            --$expn;
994
        }
995
996
        // Convert 1-index to zero-index
997 41
        --$row;
998 41
        --$col;
999
1000 41
        return [(int) $row, (int) $col, $row_rel, $col_rel];
1001
    }
1002
1003
    /**
1004
     * Advance to the next valid token.
1005
     */
1006 53
    private function advance(): void
1007
    {
1008 53
        $token = '';
1009 53
        $i = $this->currentCharacter;
1010 53
        $formula = mb_str_split($this->formula, 1, self::UTF8);
1011 53
        $formula_length = count($formula);
1012
        // eat up white spaces
1013 53
        if ($i < $formula_length) {
1014 53
            while ($formula[$i] === ' ') {
1015 5
                ++$i;
1016
            }
1017
1018 53
            if ($i < ($formula_length - 1)) {
1019 52
                $this->lookAhead = $formula[$i + 1];
1020
            }
1021 53
            $token = '';
1022
        }
1023
1024 53
        while ($i < $formula_length) {
1025 53
            $token .= $formula[$i];
1026
1027 53
            if ($i < ($formula_length - 1)) {
1028 52
                $this->lookAhead = $formula[$i + 1];
1029
            } else {
1030 53
                $this->lookAhead = '';
1031
            }
1032
1033 53
            if ($this->match($token) !== '') {
1034 53
                $this->currentCharacter = $i + 1;
1035 53
                $this->currentToken = $token;
1036
1037 53
                return;
1038
            }
1039
1040 52
            if ($i < ($formula_length - 2)) {
1041 49
                $this->lookAhead = $formula[$i + 2];
1042
            } else { // if we run out of characters lookAhead becomes empty
1043 35
                $this->lookAhead = '';
1044
            }
1045 52
            ++$i;
1046
        }
1047
    }
1048
1049
    /**
1050
     * Checks if it's a valid token.
1051
     *
1052
     * @param string $token the token to check
1053
     *
1054
     * @return string The checked token or empty string on failure
1055
     */
1056 53
    private function match(string $token): string
1057
    {
1058
        switch ($token) {
1059 53
            case '+':
1060 53
            case '-':
1061 53
            case '*':
1062 53
            case '/':
1063 53
            case '(':
1064 53
            case ')':
1065 53
            case ',':
1066 53
            case ';':
1067 53
            case '>=':
1068 53
            case '<=':
1069 53
            case '=':
1070 53
            case '<>':
1071 53
            case '^':
1072 53
            case '&':
1073 53
            case '%':
1074 47
                return $token;
1075
1076 53
            case '>':
1077 2
                if ($this->lookAhead === '=') { // it's a GE token
1078 1
                    break;
1079
                }
1080
1081 2
                return $token;
1082
1083 53
            case '<':
1084
                // it's a LE or a NE token
1085 8
                if (($this->lookAhead === '=') || ($this->lookAhead === '>')) {
1086 8
                    break;
1087
                }
1088
1089 1
                return $token;
1090
        }
1091
1092
        // if it's a reference A1 or $A$1 or $A1 or A$1
1093
        if (
1094 53
            Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token)
1095 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1096 53
            && ($this->lookAhead !== ':')
1097 53
            && ($this->lookAhead !== '.')
1098 53
            && ($this->lookAhead !== '!')
1099
        ) {
1100 30
            return $token;
1101
        }
1102
        // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1103
        if (
1104 53
            Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\!\$?[A-Ia-i]?[A-Za-z]\$?\d+$/u', $token)
1105 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1106 53
            && ($this->lookAhead !== ':')
1107 53
            && ($this->lookAhead !== '.')
1108
        ) {
1109 1
            return $token;
1110
        }
1111
        // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1112
        if (
1113 53
            self::matchCellSheetnameQuoted($token)
1114 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1115 53
            && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')
1116
        ) {
1117 8
            return $token;
1118
        }
1119
        // if it's a range A1:A2 or $A$1:$A$2
1120
        if (
1121 53
            Preg::isMatch(
1122 53
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1123 53
                $token
1124 53
            )
1125 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1126
        ) {
1127 26
            return $token;
1128
        }
1129
        // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
1130
        if (
1131 53
            Preg::isMatch(
1132 53
                '/^'
1133 53
                . self::REGEX_SHEET_TITLE_UNQUOTED
1134 53
                . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1135 53
                . ')?\!\$?([A-Ia-i]?[A-Za-z])?\$?\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\d+$/u',
1136 53
                $token
1137 53
            )
1138 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1139
        ) {
1140
            return $token;
1141
        }
1142
        // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
1143
        if (
1144 53
            self::matchRangeSheetnameQuoted($token)
1145 53
            && !Preg::isMatch('/\d/', $this->lookAhead)
1146
        ) {
1147 4
            return $token;
1148
        }
1149
        // If it's a number (check that it's not a sheet name or range)
1150 53
        if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) {
1151 31
            return $token;
1152
        }
1153
        if (
1154 52
            Preg::isMatch('/"([^"]|""){0,255}"/', $token)
1155 52
            && $this->lookAhead !== '"'
1156 52
            && (substr_count($token, '"') % 2 == 0)
1157
        ) {
1158
            // If it's a string (of maximum 255 characters)
1159 25
            return $token;
1160
        }
1161
        // If it's an error code
1162
        if (
1163 52
            Preg::isMatch('/^#[A-Z0\/]{3,5}[!?]{1}$/', $token)
1164 52
            || $token === '#N/A'
1165
        ) {
1166 1
            return $token;
1167
        }
1168
        // if it's a function call
1169
        if (
1170 52
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token)
1171 52
            && ($this->lookAhead === '(')
1172
        ) {
1173 36
            return $token;
1174
        }
1175
        if (
1176 52
            Preg::isMatch(
1177 52
                '/^'
1178 52
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1179 52
                . '$/miu',
1180 52
                $token
1181 52
            )
1182 52
            && $this->spreadsheet->getDefinedName($token) !== null
1183
        ) {
1184 6
            return $token;
1185
        }
1186
        if (
1187 52
            Preg::isMatch('/^true$/i', $token)
1188 52
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1189
        ) {
1190 2
            return $token;
1191
        }
1192
        if (
1193 52
            Preg::isMatch('/^false$/i', $token)
1194 52
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1195
        ) {
1196 2
            return $token;
1197
        }
1198 52
        if (str_ends_with($token, ')')) {
1199
            //    It's an argument of some description (e.g. a named range),
1200
            //        precise nature yet to be determined
1201 1
            return $token;
1202
        }
1203
1204 52
        return '';
1205
    }
1206
1207
    /**
1208
     * The parsing method. It parses a formula.
1209
     *
1210
     * @param string $formula the formula to parse, without the initial equal
1211
     *                        sign (=)
1212
     *
1213
     * @return bool true on success
1214
     */
1215 53
    public function parse(string $formula): bool
1216
    {
1217 53
        $this->currentCharacter = 0;
1218 53
        $this->formula = $formula;
1219 53
        $this->lookAhead = mb_substr($formula, 1, 1, self::UTF8);
1220 53
        $this->advance();
1221 53
        $this->parseTree = $this->condition();
1222
1223 53
        return true;
1224
    }
1225
1226
    /**
1227
     * It parses a condition. It assumes the following rule:
1228
     * Cond -> Expr [(">" | "<") Expr].
1229
     *
1230
     * @return mixed[] The parsed ptg'd tree on success
1231
     */
1232 53
    private function condition(): array
1233
    {
1234 53
        $result = $this->expression();
1235 53
        if ($this->currentToken == '<') {
1236 1
            $this->advance();
1237 1
            $result2 = $this->expression();
1238 1
            $result = $this->createTree('ptgLT', $result, $result2);
1239 53
        } elseif ($this->currentToken == '>') {
1240 2
            $this->advance();
1241 2
            $result2 = $this->expression();
1242 2
            $result = $this->createTree('ptgGT', $result, $result2);
1243 53
        } elseif ($this->currentToken == '<=') {
1244 2
            $this->advance();
1245 2
            $result2 = $this->expression();
1246 2
            $result = $this->createTree('ptgLE', $result, $result2);
1247 53
        } elseif ($this->currentToken == '>=') {
1248 1
            $this->advance();
1249 1
            $result2 = $this->expression();
1250 1
            $result = $this->createTree('ptgGE', $result, $result2);
1251 53
        } elseif ($this->currentToken == '=') {
1252 4
            $this->advance();
1253 4
            $result2 = $this->expression();
1254 4
            $result = $this->createTree('ptgEQ', $result, $result2);
1255 53
        } elseif ($this->currentToken == '<>') {
1256 7
            $this->advance();
1257 7
            $result2 = $this->expression();
1258 7
            $result = $this->createTree('ptgNE', $result, $result2);
1259
        }
1260
1261 53
        return $result;
1262
    }
1263
1264
    /**
1265
     * It parses a expression. It assumes the following rule:
1266
     * Expr -> Term [("+" | "-") Term]
1267
     *      -> "string"
1268
     *      -> "-" Term : Negative value
1269
     *      -> "+" Term : Positive value
1270
     *      -> Error code.
1271
     *
1272
     * @return mixed[] The parsed ptg'd tree on success
1273
     */
1274 53
    private function expression(): array
1275
    {
1276
        // If it's a string return a string node
1277 53
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $this->currentToken)) {
1278 25
            $tmp = str_replace('""', '"', $this->currentToken);
1279 25
            if (($tmp == '"') || ($tmp == '')) {
1280
                //    Trap for "" that has been used for an empty string
1281 7
                $tmp = '""';
1282
            }
1283 25
            $result = $this->createTree($tmp, '', '');
1284 25
            $this->advance();
1285
1286 25
            return $result;
1287
        }
1288
        if (
1289 53
            Preg::isMatch('/^#[A-Z0\/]{3,5}[!?]{1}$/', $this->currentToken)
1290 53
            || $this->currentToken == '#N/A'
1291
        ) { // error code
1292 1
            $result = $this->createTree($this->currentToken, 'ptgErr', '');
1293 1
            $this->advance();
1294
1295 1
            return $result;
1296
        }
1297 53
        if ($this->currentToken == '-') { // negative value
1298
            // catch "-" Term
1299 6
            $this->advance();
1300 6
            $result2 = $this->expression();
1301
1302 6
            return $this->createTree('ptgUminus', $result2, '');
1303 53
        } elseif ($this->currentToken == '+') { // positive value
1304
            // catch "+" Term
1305 1
            $this->advance();
1306 1
            $result2 = $this->expression();
1307
1308 1
            return $this->createTree('ptgUplus', $result2, '');
1309
        }
1310 53
        $result = $this->term();
1311 52
        while ($this->currentToken === '&') {
1312 8
            $this->advance();
1313 8
            $result2 = $this->expression();
1314 8
            $result = $this->createTree('ptgConcat', $result, $result2);
1315
        }
1316
        while (
1317 52
            ($this->currentToken == '+')
1318 52
            || ($this->currentToken == '-')
1319 52
            || ($this->currentToken == '^')
1320
        ) {
1321 21
            if ($this->currentToken == '+') {
1322 21
                $this->advance();
1323 21
                $result2 = $this->term();
1324 21
                $result = $this->createTree('ptgAdd', $result, $result2);
1325 6
            } elseif ($this->currentToken == '-') {
1326 6
                $this->advance();
1327 6
                $result2 = $this->term();
1328 6
                $result = $this->createTree('ptgSub', $result, $result2);
1329
            } else {
1330 1
                $this->advance();
1331 1
                $result2 = $this->term();
1332 1
                $result = $this->createTree('ptgPower', $result, $result2);
1333
            }
1334
        }
1335
1336 52
        return $result;
1337
    }
1338
1339
    /**
1340
     * This function just introduces a ptgParen element in the tree, so that Excel
1341
     * doesn't get confused when working with a parenthesized formula afterwards.
1342
     *
1343
     * @return mixed[] The parsed ptg'd tree
1344
     *
1345
     * @see fact()
1346
     */
1347 3
    private function parenthesizedExpression(): array
1348
    {
1349 3
        return $this->createTree('ptgParen', $this->expression(), '');
1350
    }
1351
1352
    /**
1353
     * It parses a term. It assumes the following rule:
1354
     * Term -> Fact [("*" | "/") Fact].
1355
     *
1356
     * @return mixed[] The parsed ptg'd tree on success
1357
     */
1358 53
    private function term(): array
1359
    {
1360 53
        $result = $this->fact();
1361
        while (
1362 52
            ($this->currentToken == '*')
1363 52
            || ($this->currentToken == '/')
1364
        ) {
1365 17
            if ($this->currentToken == '*') {
1366 16
                $this->advance();
1367 16
                $result2 = $this->fact();
1368 16
                $result = $this->createTree('ptgMul', $result, $result2);
1369
            } else {
1370 4
                $this->advance();
1371 4
                $result2 = $this->fact();
1372 4
                $result = $this->createTree('ptgDiv', $result, $result2);
1373
            }
1374
        }
1375
1376 52
        return $result;
1377
    }
1378
1379
    /**
1380
     * It parses a factor. It assumes the following rule:
1381
     * Fact -> ( Expr )
1382
     *       | CellRef
1383
     *       | CellRange
1384
     *       | Number
1385
     *       | Function.
1386
     *
1387
     * @return mixed[] The parsed ptg'd tree on success
1388
     */
1389 53
    private function fact(): array
1390
    {
1391 53
        $currentToken = $this->currentToken;
1392 53
        if ($currentToken === '(') {
1393 3
            $this->advance(); // eat the "("
1394 3
            $result = $this->parenthesizedExpression();
1395 3
            if ($this->currentToken !== ')') {
1396
                throw new WriterException("')' token expected.");
1397
            }
1398 3
            $this->advance(); // eat the ")"
1399
1400 3
            return $result;
1401
        }
1402
        // if it's a reference
1403 53
        if (Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) {
1404 30
            $result = $this->createTree($this->currentToken, '', '');
1405 30
            $this->advance();
1406
1407 30
            return $result;
1408
        }
1409
        if (
1410 50
            Preg::isMatch(
1411 50
                '/^'
1412 50
                . self::REGEX_SHEET_TITLE_UNQUOTED
1413 50
                . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1414 50
                . ')?\!\$?[A-Ia-i]?[A-Za-z]\$?\d+$/u',
1415 50
                $this->currentToken
1416 50
            )
1417
        ) {
1418
            // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1419 1
            $result = $this->createTree($this->currentToken, '', '');
1420 1
            $this->advance();
1421
1422 1
            return $result;
1423
        }
1424 50
        if (self::matchCellSheetnameQuoted($this->currentToken)) {
1425
            // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1426 8
            $result = $this->createTree($this->currentToken, '', '');
1427 8
            $this->advance();
1428
1429 8
            return $result;
1430
        }
1431
        if (
1432 48
            Preg::isMatch(
1433 48
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1434 48
                $this->currentToken
1435 48
            )
1436 48
            || Preg::isMatch(
1437 48
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1438 48
                $this->currentToken
1439 48
            )
1440
        ) {
1441
            // if it's a range A1:B2 or $A$1:$B$2
1442
            // must be an error?
1443 26
            $result = $this->createTree($this->currentToken, '', '');
1444 26
            $this->advance();
1445
1446 26
            return $result;
1447
        }
1448
        if (
1449 48
            Preg::isMatch(
1450 48
                '/^'
1451 48
                . self::REGEX_SHEET_TITLE_UNQUOTED
1452 48
                . '(\:'
1453 48
                . self::REGEX_SHEET_TITLE_UNQUOTED
1454 48
                . ')?\!\$?([A-Ia-i]?[A-Za-z])?\$?\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\d+$/u',
1455 48
                $this->currentToken
1456 48
            )
1457
        ) {
1458
            // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
1459
            // must be an error?
1460
            $result = $this->createTree($this->currentToken, '', '');
1461
            $this->advance();
1462
1463
            return $result;
1464
        }
1465 48
        if (self::matchRangeSheetnameQuoted($this->currentToken)) {
1466
            // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
1467
            // must be an error?
1468 4
            $result = $this->createTree($this->currentToken, '', '');
1469 4
            $this->advance();
1470
1471 4
            return $result;
1472
        }
1473 48
        if (is_numeric($this->currentToken)) {
1474
            // If it's a number or a percent
1475 31
            if ($this->lookAhead === '%') {
1476 1
                $result = $this->createTree('ptgPercent', $this->currentToken, '');
1477 1
                $this->advance(); // Skip the percentage operator once we've pre-built that tree
1478
            } else {
1479 31
                $result = $this->createTree($this->currentToken, '', '');
1480
            }
1481 31
            $this->advance();
1482
1483 31
            return $result;
1484
        }
1485
        if (
1486 41
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken)
1487 41
            && ($this->lookAhead === '(')
1488
        ) {
1489
            // if it's a function call
1490 36
            return $this->func();
1491
        }
1492
        if (
1493 12
            Preg::isMatch(
1494 12
                '/^'
1495 12
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1496 12
                . '$/miu',
1497 12
                $this->currentToken
1498 12
            )
1499 12
            && $this->spreadsheet->getDefinedName($this->currentToken) !== null
1500
        ) {
1501 6
            $result = $this->createTree('ptgName', $this->currentToken, '');
1502 6
            $this->advance();
1503
1504 6
            return $result;
1505
        }
1506 6
        if (Preg::isMatch('/^true|false$/i', $this->currentToken)) {
1507 2
            $result = $this->createTree($this->currentToken, '', '');
1508 2
            $this->advance();
1509
1510 2
            return $result;
1511
        }
1512
1513 4
        throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter);
1514
    }
1515
1516
    /**
1517
     * It parses a function call. It assumes the following rule:
1518
     * Func -> ( Expr [,Expr]* ).
1519
     *
1520
     * @return mixed[] The parsed ptg'd tree on success
1521
     */
1522 36
    private function func(): array
1523
    {
1524 36
        $num_args = 0; // number of arguments received
1525 36
        $function = strtoupper($this->currentToken);
1526 36
        $result = ''; // initialize result
1527 36
        $this->advance();
1528 36
        $this->advance(); // eat the "("
1529 36
        while ($this->currentToken !== ')') {
1530 36
            if ($num_args > 0) {
1531 22
                if ($this->currentToken === ',' || $this->currentToken === ';') {
1532 22
                    $this->advance(); // eat the "," or ";"
1533
                } else {
1534
                    throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}");
1535
                }
1536 22
                $result2 = $this->condition();
1537 22
                $result = $this->createTree('arg', $result, $result2);
1538
            } else { // first argument
1539 36
                $result2 = $this->condition();
1540 36
                $result = $this->createTree('arg', '', $result2);
1541
            }
1542 36
            ++$num_args;
1543
        }
1544 36
        if (!isset($this->functions[$function])) {
1545 3
            throw new WriterException("Function $function() doesn't exist");
1546
        }
1547 36
        $args = $this->functions[$function][1];
1548
        // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid.
1549 36
        if (($args >= 0) && ($args != $num_args)) {
1550
            throw new WriterException("Incorrect number of arguments in function $function() ");
1551
        }
1552
1553 36
        $result = $this->createTree($function, $result, $num_args);
1554 36
        $this->advance(); // eat the ")"
1555
1556 36
        return $result;
1557
    }
1558
1559
    /**
1560
     * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
1561
     * as elements.
1562
     *
1563
     * @param mixed $value the value of this node
1564
     * @param mixed $left the left array (sub-tree) or a final node
1565
     * @param mixed $right the right array (sub-tree) or a final node
1566
     *
1567
     * @return mixed[] A tree
1568
     */
1569 53
    private function createTree(mixed $value, mixed $left, mixed $right): array
1570
    {
1571 53
        return ['value' => $value, 'left' => $left, 'right' => $right];
1572
    }
1573
1574
    /**
1575
     * Builds a string containing the tree in reverse polish notation (What you
1576
     * would use in a HP calculator stack).
1577
     * The following tree:.
1578
     *
1579
     *    +
1580
     *   / \
1581
     *  2   3
1582
     *
1583
     * produces: "23+"
1584
     *
1585
     * The following tree:
1586
     *
1587
     *    +
1588
     *   / \
1589
     *  3   *
1590
     *     / \
1591
     *    6   A1
1592
     *
1593
     * produces: "36A1*+"
1594
     *
1595
     * In fact all operands, functions, references, etc... are written as ptg's
1596
     *
1597
     * @param mixed[] $tree the optional tree to convert
1598
     *
1599
     * @return string The tree in reverse polish notation
1600
     */
1601 57
    public function toReversePolish(array $tree = []): string
1602
    {
1603 57
        $polish = ''; // the string we are going to return
1604 57
        if (empty($tree)) { // If it's the first call use parseTree
1605 54
            $tree = $this->parseTree;
1606
        }
1607 57
        if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) {
1608 2
            throw new WriterException('Unexpected non-array');
1609
        }
1610
1611 55
        if (is_array($tree['left'])) {
1612 47
            $converted_tree = $this->toReversePolish($tree['left']);
1613 47
            $polish .= $converted_tree;
1614 55
        } elseif ($tree['left'] != '') { // It's a final node
1615 9
            $converted_tree = $this->convert($tree['left']); //* @phpstan-ignore-line
1616 3
            $polish .= $converted_tree;
1617
        }
1618 55
        if (is_array($tree['right'])) {
1619 46
            $converted_tree = $this->toReversePolish($tree['right']);
1620 45
            $polish .= $converted_tree;
1621 55
        } elseif ($tree['right'] != '') { // It's a final node
1622 37
            $converted_tree = $this->convert(StringHelper::convertToString($tree['right']));
1623 37
            $polish .= $converted_tree;
1624
        }
1625
        // if it's a function convert it here (so we can set it's arguments)
1626
        /** @var string */
1627 55
        $treeValueString = $tree['value'];
1628
        if (
1629 55
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/", $treeValueString)
1630 55
            && !Preg::isMatch('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $treeValueString)
1631 55
            && !Preg::isMatch(
1632 55
                '/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/',
1633 55
                $treeValueString
1634 55
            )
1635 55
            && !is_numeric($treeValueString)
1636 55
            && !isset($this->ptg[$treeValueString])
1637
        ) {
1638
            // left subtree for a function is always an array.
1639 35
            if ($tree['left'] != '') {
1640 35
                $left_tree = $this->toReversePolish($tree['left']); //* @phpstan-ignore-line
1641
            } else {
1642 9
                $left_tree = '';
1643
            }
1644
1645
            // add its left subtree and return.
1646 35
            if ($left_tree !== '' || $tree['right'] !== '') {
1647
                /** @var string */
1648 35
                $treeValueString = $tree['value'];
1649
                /** @var int */
1650 35
                $treeRightInt = is_numeric($tree['right']) ? ((int) $tree['right']) : 0;
1651
1652 35
                return $left_tree . $this->convertFunction($treeValueString, $treeRightInt);
1653
            }
1654
        }
1655
        /** @var string */
1656 55
        $treeValueString = $tree['value'];
1657 55
        $converted_tree = $this->convert($treeValueString);
1658
1659 53
        return $polish . $converted_tree;
1660
    }
1661
1662 64
    public static function matchCellSheetnameQuoted(string $token): bool
1663
    {
1664 64
        return Preg::isMatch(
1665 64
            self::REGEX_CELL_TITLE_QUOTED,
1666 64
            $token
1667 64
        );
1668
    }
1669
1670 64
    public static function matchRangeSheetnameQuoted(string $token): bool
1671
    {
1672 64
        return Preg::isMatch(
1673 64
            self::REGEX_RANGE_TITLE_QUOTED,
1674 64
            $token
1675 64
        );
1676
    }
1677
}
1678