Skip to content

Micro-optimize #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions src/Lexer/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

namespace PHPStan\PhpDocParser\Lexer;

use function array_keys;
use function assert;
use function count;
use function implode;
use function preg_match_all;
use const PREG_SET_ORDER;
Expand Down Expand Up @@ -93,23 +90,17 @@ class Lexer
/** @var string|null */
private $regexp;

/** @var int[]|null */
private $types;

public function tokenize(string $s): array
{
if ($this->regexp === null || $this->types === null) {
$this->initialize();
if ($this->regexp === null) {
$this->regexp = $this->generateRegexp();
}

assert($this->regexp !== null);
assert($this->types !== null);

preg_match_all($this->regexp, $s, $matches, PREG_SET_ORDER);

$tokens = [];
foreach ($matches as $match) {
$tokens[] = [$match[0], $this->types[count($match) - 2]];
$tokens[] = [$match[0], (int) $match['MARK']];
}

$tokens[] = ['', self::TOKEN_END];
Expand All @@ -118,7 +109,7 @@ public function tokenize(string $s): array
}


private function initialize(): void
private function generateRegexp(): string
{
$patterns = [
self::TOKEN_HORIZONTAL_WS => '[\\x09\\x20]++',
Expand Down Expand Up @@ -166,8 +157,11 @@ private function initialize(): void
self::TOKEN_OTHER => '(?:(?!\\*/)[^\\s])++',
];

$this->regexp = '~(' . implode(')|(', $patterns) . ')~Asi';
$this->types = array_keys($patterns);
foreach ($patterns as $type => &$pattern) {
$pattern = '(?:' . $pattern . ')(*MARK:' . $type . ')';
}

return '~' . implode('|', $patterns) . '~Asi';
}

}