Cursor::getNextNonSpaceCharacter()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 12
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace League\CommonMark\Parser;
15
16
use League\CommonMark\Exception\UnexpectedEncodingException;
17
18
class Cursor
19
{
20
    public const INDENT_LEVEL = 4;
21
22
    /** @psalm-readonly */
23
    private string $line;
24
25
    /** @psalm-readonly */
26
    private int $length;
27
28
    /**
29
     * @var int
30
     *
31
     * It's possible for this to be 1 char past the end, meaning we've parsed all chars and have
32
     * reached the end.  In this state, any character-returning method MUST return null.
33
     */
34
    private int $currentPosition = 0;
35
36
    private int $column = 0;
37
38
    private int $indent = 0;
39
40
    private int $previousPosition = 0;
41
42
    private ?int $nextNonSpaceCache = null;
43
44
    private bool $partiallyConsumedTab = false;
45
46
    /**
47
     * @var int|false
48
     *
49
     * @psalm-readonly
50
     */
51
    private $lastTabPosition;
52
53
    /** @psalm-readonly */
54
    private bool $isMultibyte;
55
56
    /** @var array<int, string> */
57
    private array $charCache = [];
58
59
    /**
60
     * @param string $line The line being parsed (ASCII or UTF-8)
61
     */
62
    public function __construct(string $line)
63
    {
64
        if (! \mb_check_encoding($line, 'UTF-8')) {
65
            throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected');
66
        }
67
68
        $this->line            = $line;
69
        $this->length          = \mb_strlen($line, 'UTF-8') ?: 0;
70
        $this->isMultibyte     = $this->length !== \strlen($line);
71
        $this->lastTabPosition = $this->isMultibyte ? \mb_strrpos($line, "\t", 0, 'UTF-8') : \strrpos($line, "\t");
72
    }
73
74
    /**
75
     * Returns the position of the next character which is not a space (or tab)
76
     */
77
    public function getNextNonSpacePosition(): int
78
    {
79
        if ($this->nextNonSpaceCache !== null) {
80
            return $this->nextNonSpaceCache;
81
        }
82
83
        if ($this->currentPosition >= $this->length) {
84
            return $this->length;
85
        }
86
87
        $cols = $this->column;
88
89
        for ($i = $this->currentPosition; $i < $this->length; $i++) {
90
            // This if-else was copied out of getCharacter() for performance reasons
91
            if ($this->isMultibyte) {
92
                $c = $this->charCache[$i] ??= \mb_substr($this->line, $i, 1, 'UTF-8');
93
            } else {
94
                $c = $this->line[$i];
95
            }
96
97
            if ($c === ' ') {
98
                $cols++;
99
            } elseif ($c === "\t") {
100
                $cols += 4 - ($cols % 4);
101
            } else {
102
                break;
103
            }
104
        }
105
106
        $this->indent = $cols - $this->column;
107
108
        return $this->nextNonSpaceCache = $i;
109
    }
110
111
    /**
112
     * Returns the next character which isn't a space (or tab)
113
     */
114
    public function getNextNonSpaceCharacter(): ?string
115
    {
116
        $index = $this->getNextNonSpacePosition();
117
        if ($index >= $this->length) {
118
            return null;
119
        }
120
121
        if ($this->isMultibyte) {
122
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
123
        }
124
125
        return $this->line[$index];
126
    }
127
128
    /**
129
     * Calculates the current indent (number of spaces after current position)
130
     */
131
    public function getIndent(): int
132
    {
133
        if ($this->nextNonSpaceCache === null) {
134
            $this->getNextNonSpacePosition();
135
        }
136
137
        return $this->indent;
138
    }
139
140
    /**
141
     * Whether the cursor is indented to INDENT_LEVEL
142
     */
143
    public function isIndented(): bool
144
    {
145
        if ($this->nextNonSpaceCache === null) {
146
            $this->getNextNonSpacePosition();
147
        }
148
149
        return $this->indent >= self::INDENT_LEVEL;
150
    }
151
152
    public function getCharacter(?int $index = null): ?string
153
    {
154
        if ($index === null) {
155
            $index = $this->currentPosition;
156
        }
157
158
        // Index out-of-bounds, or we're at the end
159
        if ($index < 0 || $index >= $this->length) {
160
            return null;
161
        }
162
163
        if ($this->isMultibyte) {
164
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
165
        }
166
167
        return $this->line[$index];
168
    }
169
170
    /**
171
     * Slightly-optimized version of getCurrent(null)
172
     */
173
    public function getCurrentCharacter(): ?string
174
    {
175
        if ($this->currentPosition >= $this->length) {
176
            return null;
177
        }
178
179
        if ($this->isMultibyte) {
180
            return $this->charCache[$this->currentPosition] ??= \mb_substr($this->line, $this->currentPosition, 1, 'UTF-8');
181
        }
182
183
        return $this->line[$this->currentPosition];
184
    }
185
186
    /**
187
     * Returns the next character (or null, if none) without advancing forwards
188
     */
189
    public function peek(int $offset = 1): ?string
190
    {
191
        return $this->getCharacter($this->currentPosition + $offset);
192
    }
193
194
    /**
195
     * Whether the remainder is blank
196
     */
197
    public function isBlank(): bool
198
    {
199
        return $this->nextNonSpaceCache === $this->length || $this->getNextNonSpacePosition() === $this->length;
200
    }
201
202
    /**
203
     * Move the cursor forwards
204
     */
205
    public function advance(): void
206
    {
207
        $this->advanceBy(1);
208
    }
209
210
    /**
211
     * Move the cursor forwards
212
     *
213
     * @param int  $characters       Number of characters to advance by
214
     * @param bool $advanceByColumns Whether to advance by columns instead of spaces
215
     */
216
    public function advanceBy(int $characters, bool $advanceByColumns = false): void
217
    {
218
        $this->previousPosition  = $this->currentPosition;
219
        $this->nextNonSpaceCache = null;
220
221
        if ($this->currentPosition >= $this->length || $characters === 0) {
222
            return;
223
        }
224
225
        // Optimization to avoid tab handling logic if we have no tabs
226
        if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) {
227
            $length                     = \min($characters, $this->length - $this->currentPosition);
228
            $this->partiallyConsumedTab = false;
229
            $this->currentPosition     += $length;
230
            $this->column              += $length;
231
232
            return;
233
        }
234
235
        $nextFewChars = $this->isMultibyte ?
236
            \mb_substr($this->line, $this->currentPosition, $characters, 'UTF-8') :
237
            \substr($this->line, $this->currentPosition, $characters);
238
239
        if ($characters === 1) {
240
            $asArray = [$nextFewChars];
241
        } elseif ($this->isMultibyte) {
242
            /** @var string[] $asArray */
243
            $asArray = \mb_str_split($nextFewChars, 1, 'UTF-8');
244
        } else {
245
            $asArray = \str_split($nextFewChars);
246
        }
247
248
        foreach ($asArray as $c) {
249
            if ($c === "\t") {
250
                $charsToTab = 4 - ($this->column % 4);
251
                if ($advanceByColumns) {
252
                    $this->partiallyConsumedTab = $charsToTab > $characters;
253
                    $charsToAdvance             = $charsToTab > $characters ? $characters : $charsToTab;
254
                    $this->column              += $charsToAdvance;
255
                    $this->currentPosition     += $this->partiallyConsumedTab ? 0 : 1;
256
                    $characters                -= $charsToAdvance;
257
                } else {
258
                    $this->partiallyConsumedTab = false;
259
                    $this->column              += $charsToTab;
260
                    $this->currentPosition++;
261
                    $characters--;
262
                }
263
            } else {
264
                $this->partiallyConsumedTab = false;
265
                $this->currentPosition++;
266
                $this->column++;
267
                $characters--;
268
            }
269
270
            if ($characters <= 0) {
271
                break;
272
            }
273
        }
274
    }
275
276
    /**
277
     * Advances the cursor by a single space or tab, if present
278
     */
279
    public function advanceBySpaceOrTab(): bool
280
    {
281
        $character = $this->getCurrentCharacter();
282
283
        if ($character === ' ' || $character === "\t") {
284
            $this->advanceBy(1, true);
285
286
            return true;
287
        }
288
289
        return false;
290
    }
291
292
    /**
293
     * Parse zero or more space/tab characters
294
     *
295
     * @return int Number of positions moved
296
     */
297
    public function advanceToNextNonSpaceOrTab(): int
298
    {
299
        $newPosition = $this->nextNonSpaceCache ?? $this->getNextNonSpacePosition();
300
        if ($newPosition === $this->currentPosition) {
301
            return 0;
302
        }
303
304
        $this->advanceBy($newPosition - $this->currentPosition);
305
        $this->partiallyConsumedTab = false;
306
307
        // We've just advanced to where that non-space is,
308
        // so any subsequent calls to find the next one will
309
        // always return the current position.
310
        $this->nextNonSpaceCache = $this->currentPosition;
311
        $this->indent            = 0;
312
313
        return $this->currentPosition - $this->previousPosition;
314
    }
315
316
    /**
317
     * Parse zero or more space characters, including at most one newline.
318
     *
319
     * Tab characters are not parsed with this function.
320
     *
321
     * @return int Number of positions moved
322
     */
323
    public function advanceToNextNonSpaceOrNewline(): int
324
    {
325
        $currentCharacter = $this->getCurrentCharacter();
326
327
        // Optimization: Avoid the regex if we know there are no spaces or newlines
328
        if ($currentCharacter !== ' ' && $currentCharacter !== "\n") {
329
            $this->previousPosition = $this->currentPosition;
330
331
            return 0;
332
        }
333
334
        $matches = [];
335
        \preg_match('/^ *(?:\n *)?/', $this->getRemainder(), $matches, \PREG_OFFSET_CAPTURE);
336
337
        // [0][0] contains the matched text
338
        // [0][1] contains the index of that match
339
        \assert(isset($matches[0]));
340
        $increment = $matches[0][1] + \strlen($matches[0][0]);
341
342
        $this->advanceBy($increment);
343
344
        return $this->currentPosition - $this->previousPosition;
345
    }
346
347
    /**
348
     * Move the position to the very end of the line
349
     *
350
     * @return int The number of characters moved
351
     */
352
    public function advanceToEnd(): int
353
    {
354
        $this->previousPosition  = $this->currentPosition;
355
        $this->nextNonSpaceCache = null;
356
357
        $this->currentPosition = $this->length;
358
359
        return $this->currentPosition - $this->previousPosition;
360
    }
361
362
    public function getRemainder(): string
363
    {
364
        if ($this->currentPosition >= $this->length) {
365
            return '';
366
        }
367
368
        $prefix   = '';
369
        $position = $this->currentPosition;
370
        if ($this->partiallyConsumedTab) {
371
            $position++;
372
            $charsToTab = 4 - ($this->column % 4);
373
            $prefix     = \str_repeat(' ', $charsToTab);
374
        }
375
376
        $subString = $this->isMultibyte ?
377
            \mb_substr($this->line, $position, null, 'UTF-8') :
378
            \substr($this->line, $position);
379
380
        return $prefix . $subString;
381
    }
382
383
    public function getLine(): string
384
    {
385
        return $this->line;
386
    }
387
388
    public function isAtEnd(): bool
389
    {
390
        return $this->currentPosition >= $this->length;
391
    }
392
393
    /**
394
     * Try to match a regular expression
395
     *
396
     * Returns the matching text and advances to the end of that match
397
     *
398
     * @psalm-param non-empty-string $regex
399
     */
400
    public function match(string $regex): ?string
401
    {
402
        $subject = $this->getRemainder();
403
404
        if (! \preg_match($regex, $subject, $matches, \PREG_OFFSET_CAPTURE)) {
405
            return null;
406
        }
407
408
        // $matches[0][0] contains the matched text
409
        // $matches[0][1] contains the index of that match
410
411
        if ($this->isMultibyte) {
412
            // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying
413
            $offset      = \mb_strlen(\substr($subject, 0, $matches[0][1]), 'UTF-8');
414
            $matchLength = \mb_strlen($matches[0][0], 'UTF-8');
415
        } else {
416
            $offset      = $matches[0][1];
417
            $matchLength = \strlen($matches[0][0]);
418
        }
419
420
        // [0][0] contains the matched text
421
        // [0][1] contains the index of that match
422
        $this->advanceBy($offset + $matchLength);
423
424
        return $matches[0][0];
425
    }
426
427
    /**
428
     * Encapsulates the current state of this cursor in case you need to rollback later.
429
     *
430
     * WARNING: Do not parse or use the return value for ANYTHING except for
431
     * passing it back into restoreState(), as the number of values and their
432
     * contents may change in any future release without warning.
433
     */
434
    public function saveState(): CursorState
435
    {
436
        return new CursorState([
437
            $this->currentPosition,
438
            $this->previousPosition,
439
            $this->nextNonSpaceCache,
440
            $this->indent,
441
            $this->column,
442
            $this->partiallyConsumedTab,
443
        ]);
444
    }
445
446
    /**
447
     * Restore the cursor to a previous state.
448
     *
449
     * Pass in the value previously obtained by calling saveState().
450
     */
451
    public function restoreState(CursorState $state): void
452
    {
453
        [
454
            $this->currentPosition,
455
            $this->previousPosition,
456
            $this->nextNonSpaceCache,
457
            $this->indent,
458
            $this->column,
459
            $this->partiallyConsumedTab,
460
        ] = $state->toArray();
461
    }
462
463
    public function getPosition(): int
464
    {
465
        return $this->currentPosition;
466
    }
467
468
    public function getPreviousText(): string
469
    {
470
        if ($this->isMultibyte) {
471
            return \mb_substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition, 'UTF-8');
472
        }
473
474
        return \substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition);
475
    }
476
477
    public function getSubstring(int $start, ?int $length = null): string
478
    {
479
        if ($this->isMultibyte) {
480
            return \mb_substr($this->line, $start, $length, 'UTF-8');
481
        }
482
483
        if ($length !== null) {
484
            return \substr($this->line, $start, $length);
485
        }
486
487
        return \substr($this->line, $start);
488
    }
489
490
    public function getColumn(): int
491
    {
492
        return $this->column;
493
    }
494
}
495