summaryrefslogtreecommitdiff
path: root/src/ste/Parser.php
blob: a588203178f517f167b5b9419aedf60dcf6dedd3 (plain)
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
<?php

namespace kch42\ste;

use LogicException;

/**
 * The class, where the parser lives in. Can not be constructed manually.
 * Use the static method parse.
 */
class Parser
{
    /** @var string */
    private $text;

    /** @var string */
    private $name;

    /** @var int */
    private $off;

    /** @var int */
    private $len;

    private const PARSE_SHORT = 1;
    private const PARSE_TAG   = 2;

    private const ESCAPES_DEFAULT = '$?~{}|\\';

    /**
     * @param string $text
     * @param string $name
     */
    private function __construct(string $text, string $name)
    {
        $this->text = $text;
        $this->name = $name;
        $this->off  = 0;
        $this->len  = mb_strlen($text);
    }

    /**
     * @param int $n
     * @return string
     */
    private function peek(int $n = 1): string
    {
        if ($n <= 0) {
            throw new \InvalidArgumentException("\$n must be > 0");
        }
        return mb_substr($this->text, $this->off, $n);
    }

    /**
     * @param int $n
     * @return string
     */
    private function next(int $n = 1): string
    {
        $c = $this->peek($n);
        $this->off = min($this->off + $n, $this->len);
        return $c;
    }

    /**
     * @return bool
     */
    private function eof(): bool
    {
        return ($this->off == $this->len);
    }

    /**
     * @param int $n
     */
    private function back(int $n = 1): void
    {
        if ($n <= 0) {
            throw new \InvalidArgumentException("\$n must be > 0");
        }
        $this->off = max($this->off - $n, 0);
    }

    /**
     * @param string $needle
     * @return false|int
     */
    private function search_off(string $needle)
    {
        return mb_strpos($this->text, $needle, $this->off);
    }

    /**
     * @param string[] $needles
     * @return array 4-tuple of found key, offset, text preceding offset, old offset
     */
    private function search_multi(array $needles): array
    {
        $oldoff = $this->off;

        $minoff = $this->len;
        $which = null;

        foreach ($needles as $key => $needle) {
            if (($off = $this->search_off($needle)) === false) {
                continue;
            }

            if ($off < $minoff) {
                $minoff = $off;
                $which = $key;
            }
        }

        $this->off = $minoff + (($which === null) ? 0 : mb_strlen((string) $needles[$which]));

        return [$which, $minoff, mb_substr($this->text, $oldoff, $minoff - $oldoff), $oldoff];
    }

    /**
     * @param string $needle
     * @return array 3-tuple of offset (or false), text preceding offset, old offset
     */
    private function search(string $needle): array
    {
        $oldoff = $this->off;

        $off = $this->search_off($needle);
        if ($off === false) {
            $this->off = $this->len;
            return [false, mb_substr($this->text, $oldoff), $oldoff];
        }

        $this->off = $off + mb_strlen($needle);
        return [$off, mb_substr($this->text, $oldoff, $off - $oldoff), $oldoff];
    }

    /**
     * @param callable $cb
     * @return string
     */
    private function take_while(callable $cb): string
    {
        $s = "";
        while (($c = $this->next()) !== "") {
            if (!call_user_func($cb, $c)) {
                $this->back();
                return $s;
            }
            $s .= $c;
        }
        return $s;
    }

    private function skip_ws(): void
    {
        $this->take_while("ctype_space");
    }

    /**
     * @return string
     * @throws ParseCompileError
     */
    private function get_name(): string
    {
        $off = $this->off;
        $name = $this->take_while(function ($c) {
            return ctype_alnum($c) || ($c == "_");
        });
        if (mb_strlen($name) == 0) {
            throw new ParseCompileError("Expected a name (alphanumeric chars + '_', at least one char)", $this->name, $off);
        }
        return $name;
    }

    /**
     * Parses the input into an AST.
     *
     * You only need this function, if you want to manually compile a template.
     *
     * @param string $text The input code.
     * @param string $name The name of the template.
     *
     * @return ASTNode[]
     * @throws ParseCompileError
     */
    public static function parse(string $text, string $name): array
    {
        $obj = new self($text, $name);
        $res = $obj->parse_text(
            self::ESCAPES_DEFAULT, /* Escapes */
            self::PARSE_SHORT | self::PARSE_TAG /* Flags */
        );
        return self::tidyup_ast($res[0]);
    }

    /**
     * @param ASTNode[] $ast
     * @return ASTNode[]
     */
    private static function combine_consecutive_text(array $ast): array
    {
        $out = [];

        /** @var TextNode|null $last_text */
        $last_text = null;

        $put_last_text = static function () use (&$out, &$last_text) {
            if ($last_text === null) {
                return;
            }

            if ($last_text->text !== "") {
                $out[] = $last_text;
            }

            $last_text = null;
        };

        foreach ($ast as $node) {
            if ($node instanceof TextNode) {
                if ($last_text !== null) {
                    $last_text->text .= $node->text;
                } else {
                    $last_text = $node;
                }
            } else {
                $put_last_text();
                $out[] = $node;
            }
        }

        $put_last_text();

        return $out;
    }

    /**
     * @param ASTNode[] $ast
     * @return ASTNode[]
     */
    private static function tidyup_ast(array $ast): array
    {
        foreach ($ast as $node) {
            if ($node instanceof TagNode) {
                $node->sub = self::tidyup_ast($node->sub);
                $node->params = array_map([__CLASS__, 'tidyup_ast'], $node->params);
            } elseif ($node instanceof VariableNode) {
                $node->arrayfields = array_map([__CLASS__, 'tidyup_ast'], $node->arrayfields);
            }
        }

        $ast = self::combine_consecutive_text($ast);

        return $ast;
    }

    /**
     * @param string $escapes
     * @param int $flags
     * @param string|null $breakon
     * @param string|null $separator
     * @param null $nullaction
     * @param string|null $opentag
     * @param int $openedat
     * @return ASTNode[][]
     * @throws ParseCompileError
     */
    private function parse_text(string $escapes, int $flags, $breakon = null, $separator = null, $nullaction = null, $opentag = null, $openedat = -1): array
    {
        $elems = [];
        $astlist = [];

        $needles = [
            "commentopen" => "<ste:comment>",
            "rawopen" => "<ste:rawtext>",
            "escape" => '\\',
            "varcurlyopen" => '${',
            "var" => '$',
        ];

        if ($flags & self::PARSE_TAG) {
            $needles["tagopen"] = '<ste:';
            $needles["closetagopen"] = '</ste:';
        }
        if ($flags & self::PARSE_SHORT) {
            $needles["shortifopen"] = '?{';
            $needles["shortcompopen"] = '~{';
        }

        if ($separator !== null) {
            $needles["sep"] = $separator;
        }
        if ($breakon !== null) {
            $needles["break"] = $breakon;
        }

        for (;;) {
            list($which, $off, $before, $offbefore) = $this->search_multi($needles);

            $astlist[] = new TextNode($this->name, $offbefore, $before);

            switch ($which) {
            case null:
                if ($nullaction === null) {
                    $elems[] = $astlist;
                    return $elems;
                } else {
                    call_user_func($nullaction);
                }
                break;
            case "commentopen":
                list($off, , $offbefore) = $this->search("</ste:comment>");
                if ($off === false) {
                    throw new ParseCompileError("ste:comment was not closed", $this->name, $offbefore);
                }
                break;
            case "rawopen":
                $off_start = $off;
                list($off, $before, ) = $this->search("</ste:rawtext>");
                if ($off === false) {
                    throw new ParseCompileError("ste:rawtext was not closed", $this->name, $off_start);
                }
                $astlist[] = new TextNode($this->name, $off_start, $before);
                break;
            case "tagopen":
                $astlist[] = $this->parse_tag($off);
                break;
            case "closetagopen":
                $off_start = $off;
                $name = $this->get_name();
                $this->skip_ws();
                $off = $this->off;
                if ($this->next() != ">") {
                    throw new ParseCompileError("Expected '>' in closing ste-Tag", $this->name, $off);
                }

                if ($opentag === null) {
                    throw new ParseCompileError("Found closing ste:$name tag, but no tag was opened", $this->name, $off_start);
                }
                if ($opentag != $name) {
                    throw new ParseCompileError("Open ste:$opentag was not closed", $this->name, $openedat);
                }

                $elems[] = $astlist;
                return $elems;
            case "escape":
                $c = $this->next();
                if (mb_strpos($escapes, $c) !== false) {
                    $astlist[] = new TextNode($this->name, $off, $c);
                } else {
                    $astlist[] = new TextNode($this->name, $off, '\\');
                    $this->back();
                }
                break;
            case "shortifopen":
                $shortelems = $this->parse_short("?{", $off);
                if (count($shortelems) != 3) {
                    throw new ParseCompileError("A short if tag must have the form ?{..|..|..}", $this->name, $off);
                }

                list($cond, $then, $else) = $shortelems;
                $thentag = new TagNode($this->name, $off);
                $thentag->name = "then";
                $thentag->sub = $then;

                $elsetag = new TagNode($this->name, $off);
                $elsetag->name = "else";
                $elsetag->sub = $else;

                $iftag = new TagNode($this->name, $off);
                $iftag->name = "if";
                $iftag->sub = $cond;
                $iftag->sub[] = $thentag;
                $iftag->sub[] = $elsetag;

                $astlist[] = $iftag;
                break;
            case "shortcompopen":
                $shortelems = $this->parse_short("~{", $off);
                if (count($shortelems) != 3) {
                    throw new ParseCompileError("A short comparasion tag must have the form ~{..|..|..}", $this->name, $off);
                }

                // TODO: What will happen, if a tag was in one of the elements?
                list($a, $op, $b) = $shortelems;
                $cmptag = new TagNode($this->name, $off);
                $cmptag->name = "cmp";
                $cmptag->params["text_a"] = $a;
                $cmptag->params["op"] = $op;
                $cmptag->params["text_b"] = $b;

                $astlist[] = $cmptag;
                break;
            case "sep":
                $elems[] = $astlist;
                $astlist = [];
                break;
            case "varcurlyopen":
                $astlist[] = $this->parse_var($off, true);
                break;
            case "var":
                $astlist[] = $this->parse_var($off, false);
                break;
            case "break":
                $elems[] = $astlist;
                return $elems;
            }
        }

        $elems[] = $astlist;
        return $elems;
    }

    /**
     * @param string $shortname
     * @param int $openedat
     * @return ASTNode[][]
     * @throws ParseCompileError
     */
    private function parse_short(string $shortname, int $openedat): array
    {
        $tplname = $this->name;

        return $this->parse_text(
            self::ESCAPES_DEFAULT, /* Escapes */
            self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
            '}', /* Break on */
            '|', /* Separator */
            function () use ($shortname, $tplname, $openedat) { /* NULL action */
                throw new ParseCompileError("Unclosed $shortname", $tplname, $openedat);
            },
            null, /* Open tag */
            $openedat /* Opened at */
        );
    }

    /**
     * @param int $openedat
     * @param bool $curly
     * @return VariableNode
     * @throws ParseCompileError
     */
    private function parse_var(int $openedat, bool $curly): VariableNode
    {
        $varnode = new VariableNode($this->name, $openedat);
        $varnode->name = $this->get_name();
        if (!$this->eof()) {
            $varnode->arrayfields = $this->parse_array();
        }

        if ($curly && ($this->next() != "}")) {
            throw new ParseCompileError("Unclosed '\${'", $this->name, $openedat);
        }
        return $varnode;
    }

    /**
     * @return ASTNode[]
     * @throws ParseCompileError
     */
    private function parse_array()
    {
        $tplname = $this->name;

        $arrayfields = [];

        while ($this->peek() == "[") {
            $this->next();

            $openedat = $this->off - 1;
            $res = $this->parse_text(
                self::ESCAPES_DEFAULT, /* Escapes */
                0, /* Flags */
                ']', /* Break on */
                null, /* Separator */
                function () use ($tplname, $openedat) { /* NULL action */
                    throw new ParseCompileError("Unclosed array access '[...]'", $tplname, $openedat);
                },
                null, /* Open tag */
                $openedat /* Opened at */
            );
            $arrayfields[] = $res[0];
        }

        return $arrayfields;
    }

    /**
     * @param int $openedat
     * @return TagNode
     * @throws ParseCompileError
     */
    private function parse_tag(int $openedat)
    {
        $tplname = $this->name;

        $this->skip_ws();
        $tag = new TagNode($this->name, $openedat);
        $name = $tag->name = $this->get_name();
        $tag->params = [];
        $tag->sub = [];

        for (;;) {
            $this->skip_ws();

            switch ($this->next()) {
            case '/': /* Self-closing tag */
                $this->skip_ws();
                if ($this->next() != '>') {
                    throw new ParseCompileError("Unclosed opening <ste: tag (expected >)", $this->name, $openedat);
                }

                return $tag;
            case '>':
                $sub = $this->parse_text(
                    self::ESCAPES_DEFAULT, /* Escapes */
                    self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
                    null, /* Break on */
                    null, /* Separator */
                    function () use ($name, $tplname, $openedat) { /* NULL action */
                        throw new ParseCompileError("Open ste:$name tag was not closed", $tplname, $openedat);
                    },
                    $tag->name, /* Open tag */
                    $openedat /* Opened at */
                );
                $tag->sub = $sub[0];
                return $tag;
            default:
                $this->back();

                $param = $this->get_name();

                $this->skip_ws();
                if ($this->next() != '=') {
                    throw new ParseCompileError("Expected '=' after tag parameter name", $this->name, $this->off - 1);
                }
                $this->skip_ws();

                $quot = $this->next();
                if (($quot != '"') && ($quot != "'")) {
                    throw new ParseCompileError("Expected ' or \" after '=' of tag parameter", $this->name, $this->off - 1);
                }

                $off = $this->off - 1;
                $paramval = $this->parse_text(
                    self::ESCAPES_DEFAULT . $quot, /* Escapes */
                    0, /* Flags */
                    $quot, /* Break on */
                    null, /* Separator */
                    function () use ($quot, $tplname, $off) { /* NULL action */
                        throw new ParseCompileError("Open tag parameter value ($quot) was not closed", $tplname, $off);
                    },
                    null, /* Open tag */
                    $off /* Opened at */
                );
                $tag->params[$param] = $paramval[0];
            }
        }

        // Help PhpStorm detect that we shouldn't be here
        throw new LogicException("Somehow we left the infinite loop?");
    }
}