-
Notifications
You must be signed in to change notification settings - Fork 3
/
Lexer.php
1935 lines (1611 loc) · 53 KB
/
Lexer.php
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
<?php
/**
* The Tale Pug Lexer.
*
* Contains the a lexer that analyzes the input-jade and generates
* tokens out of it via a PHP Generator
*
* This file is part of the Tale Pug Template Engine for PHP
*
* LICENSE:
* The code of this file is distributed under the MIT license.
* If you didn't receive a copy of the license text, you can
* read it here https://github.com/Talesoft/tale-pug/blob/master/LICENSE.md
*
* @category Presentation
* @package Tale\Pug
* @author Torben Koehn <[email protected]>
* @author Talesoft <[email protected]>
* @copyright Copyright (c) 2015-2016 Torben Köhn (http://talesoft.codes)
* @license https://github.com/Talesoft/tale-pug/blob/master/LICENSE.md MIT License
* @version 1.4.5
* @link http://jade.talesoft.codes/docs/files/Lexer.html
* @since File available since Release 1.0
*/
namespace Tale\Pug;
use RuntimeException;
use Tale\ConfigurableTrait;
use Tale\Pug\Lexer\Exception;
/**
* Performs lexical analysis and provides a token generator.
*
* Tokens are defined as single units of code
* (e.g. tag, class, id, attributeStart, attribute, attributeEnd)
*
* These will run through the parser and be converted to an AST
*
* The lexer works sequentially, ->lex will return a generator and
* you can read that generator in any manner you like.
* The generator will produce valid tokens until the end of the passed
* input.
*
* Usage example:
* <code>
*
* use Tale\Pug\Lexer;
*
* $lexer = new Lexer();
*
* foreach ($lexer->lex($jadeInput) as $token)
* echo $token;
*
* //Prints a human-readable dump of the generated tokens
*
* </code>
*
* @category Presentation
* @package Tale\Pug
* @author Torben Koehn <[email protected]>
* @author Talesoft <[email protected]>
* @copyright Copyright (c) 2015-2016 Torben Köhn (http://talesoft.codes)
* @license https://github.com/Talesoft/tale-pug/blob/master/LICENSE.md MIT License
* @version 1.4.5
* @link http://jade.talesoft.codes/docs/classes/Tale.Pug.Lexer.html
* @since File available since Release 1.0
*/
class Lexer
{
use ConfigurableTrait;
/**
* Tab Indentation (\t)
*/
const INDENT_TAB = "\t";
/**
* Space Indentation ( )
*/
const INDENT_SPACE = ' ';
/**
* The current input string.
*
* @var string
*/
private $input;
/**
* The total length of the current input.
*
* @var int
*/
private $length;
/**
* The current position inside the input string.
*
* @var int
*/
private $position;
/**
* The current line we are on.
*
* @var int
*/
private $line;
/**
* The current offset in a line we are on.
*
* Resets on each new line and increases on each read character
*
* @var int
*/
private $offset;
/**
* The current indentation level we are on.
*
* @var int
*/
private $level;
/**
* The current indentation character.
*
* @var string
*/
private $indentStyle;
/**
* The width of the indentation.
*
* Specifies how often $_indentStyle
* is repeated for each $_level
*
* @var string
*/
private $indentWidth;
/**
* The last result gotten via ->peek().
*
* @see Lexer->peek
* @var string
*/
private $lastPeekResult;
/**
* The last matches gotten via ->match()
*
* @see Lexer->match
* @var array
*/
private $lastMatches;
/**
* Creates a new lexer instance.
*
* The options should be an associative array
*
* Valid options are:
*
* indentStyle: The indentation character (auto-detected)
* indentWidth: How often to repeat indentStyle (auto-detected)
* encoding: The encoding when working with mb_*-functions (Default: UTF-8)
* scans: An array of scans that will be performed
*
* Passing an indentation-style forces you to stick to that style.
* If not, the lexer will assume the first indentation type it finds as the indentation.
* Mixed indentation is not possible, since it would be a bitch to calculate without
* taking away configuration freedom
*
* Add a new scan to 'scans' to extend the lexer.
* Notice that you need the fitting 'handle*'-method in the parser
* or you will get unhandled-token-exceptions.
*
* @param array|null $options the options passed to the lexer instance
*
* @throws \Exception
*/
public function __construct(array $options = null)
{
$this->defineOptions([
'indent_style' => null,
'indent_width' => null,
'encoding' => mb_internal_encoding(),
'scans' => [
'newLine', 'indent',
'import',
'block',
'conditional', 'each', 'case', 'when', 'do', 'while', 'forLoop',
'mixin', 'mixinCall',
'doctype',
'tag', 'classes', 'id', 'attributes',
'assignment',
'variable',
'comment', 'filter',
'expression',
'code',
'markup',
'textLine',
'text'
]
], $options);
//Validate options
if (!in_array($this->options['indent_style'], [null, self::INDENT_TAB, self::INDENT_SPACE]))
throw new RuntimeException(
"indentStyle needs to be null or one of the INDENT_* constants of the lexer"
);
if (!is_null($this->options['indent_width']) &&
(!is_int($this->options['indent_width']) || $this->options['indent_width'] < 1)
)
throw new RuntimeException(
"indentWidth needs to be a integer above 0"
);
}
/**
* Returns the current input-string worked on.
*
* @return string
*/
public function getInput()
{
return $this->input;
}
/**
* Returns the total length of the current input-string.
*
* @return int
*/
public function getLength()
{
return $this->length;
}
/**
* Returns the total position in the current input-string.
*
* @return int
*/
public function getPosition()
{
return $this->position;
}
/**
* Returns the line we are working on in the current input-string.
*
* @return int
*/
public function getLine()
{
return $this->line;
}
/**
* Gets the offset on a line (Line-start is 0) in the current input-string.
*
* @return int
*/
public function getOffset()
{
return $this->offset;
}
/**
* Returns the current indentation level we are on.
*
* @return int
*/
public function getLevel()
{
return $this->level;
}
/**
* Returns the detected or previously passed indentation style.
*
* @return string
*/
public function getIndentStyle()
{
return $this->indentStyle;
}
/**
* Returns the detected or previously passed indentation width.
*
* @return int
*/
public function getIndentWidth()
{
return $this->indentWidth;
}
/**
* Returns the last result of ->peek().
*
* @see Lexer->peek
* @return string|null
*/
public function getLastPeekResult()
{
return $this->lastPeekResult;
}
/**
* Returns the last array of matches through ->match.
*
* @see Lexer->match
* @return array|null
*/
public function getLastMatches()
{
return $this->lastMatches;
}
/**
* Returns a generator that will lex the passed $input sequentially.
*
* If you don't move the generator, the lexer does nothing.
* Only as soon as you iterate the generator or call next()/current() on it
* the lexer will start it's work and spit out tokens sequentially.
* This approach takes less memory during the lexing process.
*
* Tokens are always an array and always provide the following keys:
* <samp>
* [
* 'type' => The token type,
* 'line' => The line this token is on,
* 'offset' => The offset this token is at
* ]
* </samp>
*
* @param string $input the Pug-string to lex into tokens
*
* @return \Generator a generator that can be iterated sequentially
*/
public function lex($input)
{
$this->input = rtrim(str_replace([
"\r", "\0"
], '', $input))."\n";
$this->length = $this->strlen($this->input);
$this->position = 0;
$this->line = 1;
$this->offset = 0;
$this->level = 0;
$this->indentStyle = $this->options['indent_style'];
$this->indentWidth = $this->options['indent_width'];
$this->lastPeekResult = null;
$this->lastMatches = null;
foreach ($this->scanFor($this->options['scans'], true) as $token)
yield $token;
}
/**
* Dumps jade-input into a set of string-represented tokens.
*
* This makes debugging the lexer easier.
*
* @param string $input the jade input to dump the tokens of
*/
public function dump($input)
{
foreach ($this->lex($input) as $token) {
$type = $token['type'];
$line = $token['line'];
$offset = $token['offset'];
unset($token['type'], $token['line'], $token['offset']);
echo "[$type($line:$offset)";
$vals = implode(', ', array_map(function ($key, $value) {
return "$key=$value";
}, array_keys($token), $token));
if (!empty($vals))
echo " $vals";
echo ']';
if ($type === 'newLine')
echo "\n";
}
}
/**
* Checks if our read pointer is at the end of the code.
*
* @return bool
*/
protected function isAtEnd()
{
return $this->position >= $this->length;
}
/**
* Shows the next characters in our input.
*
* Pass a $length to get more than one character.
* The character's _won't_ be consumed here, they are just shown.
* The position pointer won't be moved forward
*
* The result gets saved in $_lastPeekResult
*
* @param int $length the length of the string we want to peek on
*
* @return string the peeked string
*/
protected function peek($length = 1)
{
$this->lastPeekResult = $this->substr($this->input, 0, $length);
return $this->lastPeekResult;
}
/**
* Consumes a length or the length of the last peeked string.
*
* Internally $input = substr($input, $length) is done,
* so everything _before_ the consumed length will be cut off and
* removed from the RAM (since we probably tokenized it already,
* remember? sequential shit etc.?)
*
* @see Lexer->peek
*
* @param int|null $length the length to consume or null, to use the length of the last peeked string
*
* @return $this
* @throws Exception
*/
protected function consume($length = null)
{
if ($length === null) {
if ($this->lastPeekResult === null)
$this->throwException(
"Failed to consume: Nothing has been peeked and you"
." didnt pass a length to consume"
);
$length = $this->strlen($this->lastPeekResult);
}
$this->input = $this->substr($this->input, $length);
$this->position += $length;
$this->offset += $length;
return $this;
}
/**
* Peeks and consumes chars until the passed callback returns false.
*
* The callback takes the current character as the first argument.
*
* This works great with ctype_*-functions
*
* If the last character doesn't match, it also won't be consumed
* You can always go on reading right after a call to ->read()
*
* e.g.
* $alNumString = $this->read('ctype_alnum')
* $spaces = $this->read('ctype_space')
*
* @param callable $callback the callback to check the current character against
* @param int $length the length to peek. This will also increase the length of the characters passed to the callback
*
* @return string the read string
* @throws \Exception
*/
protected function read($callback, $length = 1)
{
if (!is_callable($callback))
throw new \InvalidArgumentException(
"Argument 1 passed to peekWhile needs to be callback"
);
$result = '';
while (!$this->isAtEnd() && $callback($this->peek($length))) {
//Keep $_line and $_offset updated
$newLines = $this->substr_count($this->lastPeekResult, "\n");
$this->line += $newLines;
if ($newLines) {
if (strlen($this->lastPeekResult) === 1)
$this->offset = 0;
else {
$parts = explode("\n", $this->lastPeekResult);
$this->offset = strlen($parts[count($parts) - 1]) - 1;
}
}
$this->consume();
$result .= $this->lastPeekResult;
}
return $result;
}
/**
* Reads all TAB (\t) and SPACE ( ) chars until something else is found.
*
* This is primarily used to parse the indentation
* at the begin of each line.
*
* @return string the spaces that have been found
* @throws Exception
*/
protected function readSpaces()
{
return $this->read(function ($char) {
return $char === self::INDENT_SPACE || $char === self::INDENT_TAB;
});
}
/**
* Reads a "value", 'value' or value style string really gracefully.
*
* It will stop on all chars passed to $breakChars as well as a closing ')'
* when _not_ inside an expression initiated with either
* ", ', (, [ or {.
*
* $breakChars might be [','] as an example to read sequential arguments
* into an array. Scan for ',', skip spaces, repeat readBracketContents
*
* Brackets are counted, strings are respected.
*
* Inside a " string, \" escaping is possible, inside a ' string, \' escaping
* is possible
*
* As soon as a ) is found and we're outside a string and outside any kind of bracket,
* the reading will stop and the value, including any quotes, will be returned
*
* Examples:
* ('`' marks the parts that are read, understood and returned by this function)
*
* <samp>
* (arg1=`abc`, arg2=`"some expression"`, `'some string expression'`)
* some-mixin(`'some arg'`, `[1, 2, 3, 4]`, `(isset($complex) ? $complex : 'complex')`)
* and even
* some-mixin(callback=`function($input) { return trim($input, '\'"'); }`)
* </samp>
*
* @param array|null $breakChars the chars to break on.
*
* @return string the (possibly quote-enclosed) result string
*/
protected function readBracketContents(array $breakChars = null)
{
$breakChars = $breakChars ? $breakChars : [];
$value = '';
$prev = null;
$char = null;
$level = 0;
$inString = false;
$stringType = null;
$finished = false;
while (!$this->isAtEnd() && !$finished) {
if ($this->isAtEnd())
break;
$prev = $char;
$char = $this->peek();
switch ($char) {
case '"':
case '\'':
if ($inString && $stringType === $char && $prev !== '\\')
$inString = false;
else if (!$inString) {
$inString = true;
$stringType = $char;
}
break;
case '(':
case '[':
case '{':
if (!$inString)
$level++;
break;
case ')':
case ']':
case '}':
if ($inString)
break;
if ($level === 0) {
$finished = true;
break;
}
$level--;
break;
}
if (in_array($char, $breakChars, true) && !$inString && $level === 0)
$finished = true;
if (!$finished) {
$value .= $char;
$this->consume();
}
}
return trim($value);
}
/**
* Matches a pattern against the start of the current $input.
*
* Notice that this always takes the start of the current pointer
* position as a reference, since `consume` means cutting of the front
* of the input string
*
* After a match was successful, you can retrieve the matches
* with ->getMatch() and consume the whole match with ->consumeMatch()
*
* ^ gets automatically prepended to the pattern (since it makes no sense
* for a sequential lexer to search _inside_ the input)
*
* @param string $pattern the regular expression without delimeters and a ^-prefix
* @param string $modifiers the usual PREG RegEx-modifiers
*
* @return bool
*/
protected function match($pattern, $modifiers = '')
{
return preg_match(
"/^$pattern/$modifiers",
$this->input,
$this->lastMatches
) ? true : false;
}
/**
* Consumes a match previously read and matched by ->match().
*
* @see Lexer->match
* @return $this
*/
protected function consumeMatch()
{
//Make sure we don't consume matched newlines (We match for them sometimes)
//We need the newLine tokens and don't want them consumed here.
$match = $this->lastMatches[0] !== "\n" ? rtrim($this->lastMatches[0], "\n") : $this->lastMatches[0];
return $this->consume($this->strlen($match));
}
/**
* Gets a match from the last ->match() call
*
* @see Lexer->match
*
* @param int|string $index the index of the usual PREG $matches argument
*
* @return mixed|null the value of the match or null, if none found
*/
protected function getMatch($index)
{
return isset($this->lastMatches[$index]) ? $this->lastMatches[$index] : null;
}
/**
* Keeps scanning for all types of tokens passed as the first argument.
*
* If one token is encountered that's not in $scans, the function breaks
* or throws an exception, if the second argument is true
*
* The passed scans get converted to methods
* e.g. newLine => scanNewLine, blockExpansion => scanBlockExpansion etc.
*
* @param array $scans the scans to perform
* @param bool|false $throwException throw an exception if no tokens in $scans found anymore
*
* @return \Generator the generator yielding all tokens found
* @throws Exception
*/
protected function scanFor(array $scans, $throwException = false)
{
while (!$this->isAtEnd()) {
$found = false;
foreach ($scans as $name) {
foreach (call_user_func([$this, 'scan'.ucfirst($name)]) as $token) {
$found = true;
yield $token;
}
if ($found)
continue 2;
}
$spaces = $this->readSpaces();
if (!empty($spaces) && !$this->isAtEnd())
continue;
if ($throwException) {
$this->throwException(
'Unexpected `'.htmlentities($this->peek(20), \ENT_QUOTES).'`, '
.implode(', ', $scans).' expected'
);
} else
return;
}
}
/**
* Creates a new token.
*
* A token is an associative array.
* The following keys _always_ exist:
*
* type: The type of the node (e.g. newLine, tag, class, id)
* line: The line we encountered this token on
* offset: The offset on a line we encountered it on
*
* Before adding a new token-type, make sure that the Parser knows how
* to handle it and the Compiler knows how to compile it.
*
* @param string $type the type to give that token
*
* @return array the token array
*/
protected function createToken($type)
{
return [
'type' => $type,
'line' => $this->line,
'level' => $this->level,
'offset' => $this->offset
];
}
/**
* Scans for a specific token-type based on a pattern
* and converts it to a valid token automatically.
*
* All matches that have a name (RegEx (?<name>...)-directive
* will directly get a key with that name and value
* on the token array
*
* For matching, ->match() is used internally
*
* @see Lexer->match
*
* @param string $type the token type to create, if matched
* @param string $pattern the pattern to match
* @param string $modifiers the regex-modifiers for the pattern
*
* @return \Generator
*/
protected function scanToken($type, $pattern, $modifiers = '')
{
if (!$this->match($pattern, $modifiers))
return;
$this->consumeMatch();
$token = $this->createToken($type);
foreach ($this->lastMatches as $key => $value) {
//We append all STRING-Matches (?<name>) to the token
if (is_string($key)) {
$token[$key] = empty($value) ? null : $value;
}
}
yield $token;
}
/**
* Scans for indentation and automatically keeps
* the $_level updated through all tokens.
*
* Upon reaching a higher level, an <indent>-token is
* yielded, upon reaching a lower level, an <outdent>-token is yielded
*
* If you outdented 3 levels, 3 <outdent>-tokens are yielded
*
* The first indentation this function encounters will be used
* as the indentation style for this document.
*
* You can indent with everything between 1 space and a few million tabs
* other than most Pug implementations
*
* @return \Generator|void
* @throws Exception
*/
protected function scanIndent()
{
if ($this->offset !== 0 || !$this->match("([\t ]*)"))
return;
$this->consumeMatch();
$indent = $this->getMatch(1);
//If this is an empty line, we ignore the indentation completely.
foreach ($this->scanNewLine() as $token) {
yield $token;
return;
}
$oldLevel = $this->level;
if (!empty($indent)) {
$spaces = $this->strpos($indent, ' ') !== false;
$tabs = $this->strpos($indent, "\t") !== false;
$mixed = $spaces && $tabs;
if ($mixed) {
switch ($this->indentStyle) {
case self::INDENT_SPACE:
default:
//Convert tabs to spaces based on indentWidth
$spaces = str_replace(self::INDENT_TAB, str_repeat(
self::INDENT_SPACE,
$this->indentWidth ? $this->indentWidth : 4
), $spaces);
$tabs = false;
$mixed = false;
break;
case self::INDENT_TAB:
//Convert spaces to tabs
$spaces = str_replace(self::INDENT_SPACE, str_repeat(
self::INDENT_TAB,
$this->indentWidth ? $this->indentWidth : 1
), $spaces);
$spaces = false;
$mixed = false;
break;
}
}
//Validate the indentation style
$this->indentStyle = $tabs ? self::INDENT_TAB : self::INDENT_SPACE;
//Validate the indentation width
if (!$this->indentWidth)
//We will use the pretty first indentation as our indent width
$this->indentWidth = $this->strlen($indent);
$this->level = intval(round($this->strlen($indent) / $this->indentWidth));
if ($this->level > $oldLevel + 1)
$this->level = $oldLevel + 1;
} else
$this->level = 0;
$levels = $this->level - $oldLevel;
//Unchanged levels
if (!empty($indent) && $levels === 0)
return;
//We create a token for each indentation/outdentation
$type = $levels > 0 ? 'indent' : 'outdent';
$levels = abs($levels);
while ($levels--)
yield $this->createToken($type);
}
/**
* Scans for a new-line character and yields a <newLine>-token if found.
*
* @return \Generator
*/
protected function scanNewLine()
{
foreach ($this->scanToken('newLine', "\n") as $token) {
$this->line++;
$this->offset = 0;
yield $token;
}
}
/**
* Scans for text until the end of the current line
* and yields a <text>-token if found.
*
* @param bool $escaped
* @return \Generator
*/
protected function scanText($escaped = false)
{
foreach ($this->scanToken('text', "[ ]?([^\n]*)?") as $token) {
$value = trim($this->getMatch(1), "\t");
$token['value'] = $value;
$token['escaped'] = $escaped;
yield $token;
}
}
/**
* Scans for text and keeps scanning text, if you indent once
* until it is outdented again (e.g. .-text-blocks, expressions, comments).
*
* Yields anything between <text>, <newLine>, <indent> and <outdent> tokens
* it encounters
*
* @return \Generator
*/
protected function scanTextBlock($escaped = false)
{
foreach ($this->scanText($escaped) as $token)
yield $token;
foreach ($this->scanNewLine() as $token)
yield $token;
if ($this->isAtEnd())
return;
$level = 0;
do {
foreach ($this->scanFor(['newLine', 'indent']) as $token) {
if ($token['type'] === 'indent')
$level++;
if ($token['type'] === 'outdent')
$level--;
yield $token;
}
if ($level <= 0)
continue;
foreach ($this->scanText($escaped) as $token)
yield $token;