Skip to content
Merged
Show file tree
Hide file tree
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
10 changes: 9 additions & 1 deletion .github/workflows/compatibility.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,16 @@ jobs:
extensions: mbstring
tools: composer:v2

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm

- name: Install Dependencies
run: composer update --no-interaction --prefer-dist
run: |
composer update --no-interaction --prefer-dist
npm ci

- name: Generate report
run: composer compatibility
Expand Down
407 changes: 204 additions & 203 deletions COMPATIBILITY.md

Large diffs are not rendered by default.

159 changes: 107 additions & 52 deletions meta/compatibility.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

/**
* Compare how the Oniguruma and PCRE engines tokenize the sample for every grammar, and write
* the results to COMPATIBILITY.md. Oniguruma is the reference, so this needs mbregex or mb_onig.
* Compare how the Oniguruma and PCRE engines tokenize the sample for every grammar with how
* vscode-textmate does, and write the results to COMPATIBILITY.md. This needs mbregex or mb_onig
* for the Oniguruma engine, and Node.js with the npm dependencies for vscode-textmate.
*
* Usage: php meta/compatibility.php [grammar ...]
* Passing grammar names prints their results instead of writing the report.
Expand Down Expand Up @@ -106,51 +107,81 @@ function grammarRegexes(object $grammar): array
}

/**
* Key each token on a line by its position and scopes. The newline at the end of each line is
* left out: mbregex lets `.` match it and PCRE does not, which never changes the rendered output.
* Key each token on a line by its position in code points and its scopes, so they can be compared
* with vscode-textmate's. Neighbouring tokens with the same scopes are merged, since where they are
* split never changes the rendered output, and the newline at the end of the line is left out.
*
* @param Token[] $line
* @param list<array{int, int, string}> $tokens
* @return list<string>
*/
function tokenKeys(array $line): array
function tokenKeys(array $tokens): array
{
$keys = [];
$merged = [];

foreach ($line as $token) {
$text = $token === end($line) ? rtrim($token->text, "\n") : $token->text;
foreach ($tokens as [$start, $end, $scopes]) {
if ($start === $end) {
continue;
}

if ($text !== '') {
$keys[] = $token->start.':'.($token->start + strlen($text)).':'.implode(' ', $token->scopes);
$last = array_key_last($merged);

if ($last !== null && $merged[$last][2] === $scopes && $merged[$last][1] === $start) {
$merged[$last][1] = $end;
} else {
$merged[] = [$start, $end, $scopes];
}
}

return $keys;
return array_map(fn (array $token) => implode(':', $token), $merged);
}

/**
* @param Token[] $line
* @return list<array{int, int, string}>
*/
function phikiTokens(array $line): array
{
$tokens = [];
$offset = 0;

foreach ($line as $token) {
$length = mb_strlen(rtrim($token->text, "\n"));
$tokens[] = [$offset, $offset + $length, implode(' ', $token->scopes)];
$offset += $length;
}

return $tokens;
}

/**
* @return array{tokens: int, matching: int, lines: int, identicalLines: int, firstDifference: ?int, coverage: float}
* Compare the tokens each engine produces for the sample with vscode-textmate's.
*
* @param list<list<array{int, int, string}>> $reference
* @return array{tokens: int, oniguruma: int, pcre: int, onigurumaIdentical: bool, firstDifference: ?int, coverage: float}
*/
function compareGrammar(Grammar $grammar, string $code): array
function compareGrammar(Grammar $grammar, string $code, array $reference): array
{
$recorder = new RecordingEngine(new OnigurumaEngine);
$oniguruma = (new Phiki)->engine($recorder);
$expected = $oniguruma->codeToTokens($code, $grammar);
$actual = (new Phiki)->engine(new PcreEngine)->codeToTokens($code, $grammar);
$engines = [
'oniguruma' => $oniguruma->codeToTokens($code, $grammar),
'pcre' => (new Phiki)->engine(new PcreEngine)->codeToTokens($code, $grammar),
];

$rules = grammarRegexes($oniguruma->environment->grammars->get($grammar->value));
$result = ['tokens' => 0, 'matching' => 0, 'lines' => count($expected), 'identicalLines' => 0, 'firstDifference' => null];
$result = ['tokens' => 0, 'oniguruma' => 0, 'pcre' => 0, 'onigurumaIdentical' => true, 'firstDifference' => null];

foreach ($expected as $index => $line) {
$expectedKeys = tokenKeys($line);
$actualKeys = tokenKeys($actual[$index] ?? []);
foreach ($reference as $index => $line) {
$expected = tokenKeys($line);
$result['tokens'] += count($expected);

$result['tokens'] += count($expectedKeys);
$result['matching'] += count(array_intersect($expectedKeys, $actualKeys));
foreach ($engines as $engine => $lines) {
$actual = tokenKeys(phikiTokens($lines[$index] ?? []));
$result[$engine] += count(array_intersect($expected, $actual));

if ($expectedKeys === $actualKeys) {
$result['identicalLines']++;
} else {
$result['firstDifference'] ??= $index + 1;
if ($actual !== $expected) {
$engine === 'pcre' ? $result['firstDifference'] ??= $index + 1 : $result['onigurumaIdentical'] = false;
}
}
}

Expand All @@ -165,14 +196,13 @@ function percent(int|float $part, int|float $whole): string
}

if (! OnigurumaEngine::isSupported()) {
fwrite(STDERR, "The Oniguruma engine is the reference for this report, so it needs mbregex or the mb_onig extension.\n");
fwrite(STDERR, "This report compares the Oniguruma engine too, so it needs mbregex or the mb_onig extension.\n");

exit(1);
}

$only = array_slice($argv, 1);
$rows = [];
$totals = ['tokens' => 0, 'matching' => 0, 'lines' => 0, 'identicalLines' => 0, 'identical' => 0];
$samples = [];

foreach (Grammar::cases() as $grammar) {
// ANSI is handled by its own tokenizer rather than a TextMate grammar.
Expand All @@ -188,32 +218,54 @@ function percent(int|float $part, int|float $whole): string
continue;
}

$result = compareGrammar($grammar, file_get_contents(__DIR__."/../{$sample}"));
$samples[$grammar->value] = [$grammar, $sample];
}

// vscode-textmate is the reference: it is what VS Code and Shiki tokenize with.
$referenceFile = tempnam(sys_get_temp_dir(), 'phiki-compatibility');
$command = implode(' ', array_map('escapeshellarg', ['node', __DIR__.'/vscode-textmate-samples.js', $referenceFile, ...array_keys($samples)]));
exec($command, result_code: $exitCode);

if ($exitCode !== 0) {
fwrite(STDERR, "Could not tokenize the samples with vscode-textmate. Run `npm ci` first.\n");

exit(1);
}

$references = json_decode(file_get_contents($referenceFile), true);
unlink($referenceFile);

$rows = [];
$totals = ['tokens' => 0, 'oniguruma' => 0, 'pcre' => 0, 'onigurumaIdentical' => 0, 'pcreIdentical' => 0];

foreach ($samples as $name => [$grammar, $sample]) {
$result = compareGrammar($grammar, file_get_contents(__DIR__."/../{$sample}"), $references[$name]);
$identical = $result['firstDifference'] === null;

foreach (['tokens', 'matching', 'lines', 'identicalLines'] as $key) {
foreach (['tokens', 'oniguruma', 'pcre'] as $key) {
$totals[$key] += $result[$key];
}

$totals['identical'] += (int) $identical;
$totals['onigurumaIdentical'] += (int) $result['onigurumaIdentical'];
$totals['pcreIdentical'] += (int) $identical;

$rows[$grammar->value] = sprintf(
$rows[$name] = sprintf(
'| %s | [%s](%s) | %s | %d | %s | %s | %s |',
$grammar->value,
$name,
basename($sample),
$sample,
percent($result['coverage'], 1),
$result['tokens'],
percent($result['matching'], $result['tokens']),
percent($result['identicalLines'], $result['lines']),
percent($result['oniguruma'], $result['tokens']),
percent($result['pcre'], $result['tokens']),
$identical ? '✅ Identical' : sprintf('[Line %d](%s#L%d)', $result['firstDifference'], $sample, $result['firstDifference']),
);
}

ksort($rows);

$header = [
'| Grammar | Sample | Rule coverage | Tokens | Matching tokens | Identical lines | First difference |',
'| Grammar | Sample | Rule coverage | Tokens | Oniguruma | PCRE | First PCRE difference |',
'| --- | --- | ---: | ---: | ---: | ---: | --- |',
];

Expand All @@ -226,22 +278,23 @@ function percent(int|float $part, int|float $whole): string
$report = <<<'MD'
# Engine compatibility

Phiki can tokenize code with two regex engines: Oniguruma (through mbregex or the `mb_onig` extension), and PCRE, which every PHP build includes. Oniguruma is the engine TextMate grammars are written for, so it is the reference. This report shows how closely the PCRE engine reproduces its tokens for the sample of each bundled grammar.
Phiki can tokenize code with two regex engines: Oniguruma (through mbregex or the `mb_onig` extension), and PCRE, which every PHP build includes. This report compares the tokens each engine produces for the sample of each bundled grammar with the tokens from [vscode-textmate](https://github.com/microsoft/vscode-textmate), the tokenizer used by VS Code and Shiki.

Regenerate it with `composer compatibility` after changing the PCRE engine, the translator, the grammars or the samples.
Regenerate it with `composer compatibility` after changing an engine, the translator, the tokenizer, the grammars or the samples. It needs Node.js and `npm ci`.

- **Rule coverage** is the share of the grammar's own rules that match at least once while its sample is tokenized. Rules from embedded grammars are not counted.
- **Matching tokens** is the share of Oniguruma's tokens that PCRE produces with the same position, text and scopes.
- **Identical lines** is the share of lines whose tokens are all the same.
- The newline at the end of each line is not compared. mbregex lets `.` match it and PCRE does not, which never changes the rendered output.
- **Oniguruma** and **PCRE** are the share of vscode-textmate's tokens that each engine produces with the same position and scopes.
- **First PCRE difference** is the first line where the PCRE engine's tokens differ from vscode-textmate's.
- Neighbouring tokens with the same scopes are merged before comparing, and the newline at the end of each line is not compared. Neither changes the rendered output.

Generated with PHP %s, PCRE2 %s and Oniguruma %s.

## Summary

- %d of %d grammars tokenize their sample identically.
- %s of tokens match (%d of %d).
- %s of lines are identical (%d of %d).
| Engine | Grammars identical | Matching tokens |
| --- | ---: | ---: |
| Oniguruma | %d of %d | %s (%d of %d) |
| PCRE | %d of %d | %s (%d of %d) |

## Grammars

Expand All @@ -253,16 +306,18 @@ function percent(int|float $part, int|float $whole): string
PHP_VERSION,
explode(' ', PCRE_VERSION)[0],
defined('MB_ONIGURUMA_VERSION') ? MB_ONIGURUMA_VERSION : 'unknown',
$totals['identical'],
$totals['onigurumaIdentical'],
count($rows),
percent($totals['oniguruma'], $totals['tokens']),
$totals['oniguruma'],
$totals['tokens'],
$totals['pcreIdentical'],
count($rows),
percent($totals['matching'], $totals['tokens']),
$totals['matching'],
percent($totals['pcre'], $totals['tokens']),
$totals['pcre'],
$totals['tokens'],
percent($totals['identicalLines'], $totals['lines']),
$totals['identicalLines'],
$totals['lines'],
);

file_put_contents(__DIR__.'/../COMPATIBILITY.md', $report.implode("\n", [...$header, ...$rows])."\n");

echo "Wrote COMPATIBILITY.md: {$totals['identical']} of ".count($rows)." grammars identical.\n";
echo "Wrote COMPATIBILITY.md: PCRE matches vscode-textmate for {$totals['pcreIdentical']} of ".count($rows)." grammars, Oniguruma for {$totals['onigurumaIdentical']}.\n";
65 changes: 65 additions & 0 deletions meta/vscode-textmate-samples.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Tokenize the sample of each grammar with vscode-textmate, for meta/compatibility.php.
//
// Usage: node meta/vscode-textmate-samples.js <output.json> <grammar> [grammar ...]
// Writes {grammar: lines}, where each line is a list of [start, end, scopes] tokens with
// offsets in code points.

import fs from 'node:fs'
import path from 'node:path'
import vsctm from 'vscode-textmate'
import oniguruma from 'vscode-oniguruma'

const [output, ...names] = process.argv.slice(2)

if (! output || names.length === 0) {
console.error('Usage: node meta/vscode-textmate-samples.js <output.json> <grammar> [grammar ...]')
process.exit(1)
}

const root = path.join(import.meta.dirname, '..')

await oniguruma.loadWASM(fs.readFileSync(path.join(root, 'node_modules/vscode-oniguruma/release/onig.wasm')).buffer)

const grammarsDir = path.join(root, 'resources/grammars/oniguruma')
const grammars = {}
const scopeNames = {}

for (const file of fs.readdirSync(grammarsDir)) {
const grammar = vsctm.parseRawGrammar(fs.readFileSync(path.join(grammarsDir, file), 'utf8'), file)

grammars[grammar.scopeName] = grammar
scopeNames[path.basename(file, '.json')] = grammar.scopeName
}

const registry = new vsctm.Registry({
onigLib: Promise.resolve({
createOnigScanner: (patterns) => new oniguruma.OnigScanner(patterns),
createOnigString: (string) => new oniguruma.OnigString(string),
}),
loadGrammar: async (scopeName) => grammars[scopeName] ?? null,
})

const results = {}

for (const name of names) {
const grammar = await registry.loadGrammar(scopeNames[name])
const code = fs.readFileSync(path.join(root, `tests/Fixtures/samples/${name}.sample`), 'utf8')
let ruleStack = vsctm.INITIAL

results[name] = code.split('\n').map((line) => {
const result = grammar.tokenizeLine(line, ruleStack)
ruleStack = result.ruleStack

// vscode-textmate reports offsets in UTF-16 code units, so count code points instead.
let offset = 0

return result.tokens.map((token) => {
const start = offset
offset += [...line.substring(token.startIndex, token.endIndex)].length

return [start, offset, token.scopes.join(' ')]
})
})
}

fs.writeFileSync(output, JSON.stringify(results))
Loading
Loading