Skip to content
Closed
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
6 changes: 4 additions & 2 deletions src/wp-includes/compat-utf8.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
* @param int|null $max_bytes Stop scanning after this many bytes have been seen.
* @param int|null $max_code_points Stop scanning after this many code points have been seen.
* @param bool|null $has_noncharacters Set to indicate if scanned string contained noncharacters.
* @param-out bool $has_noncharacters

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please verify that this doesn’t break the docs-generation. before we start changing @param declarations, we should ensure that the published docs page isn’t broken.

you can hopefully lean on dmsnell#29 to figure out how to preview the generation.

I see that this is an additional annotation beyond the @param, but it would be ideal to double-check first.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for flagging this. I couldn't build the full Playground preview locally, so I checked the parser and theme versions pinned in your preview branch instead. The docblock tag regex allows -, so @param-out comes through as its own param-out tag rather than a @param. The reference templates only read tags named param for the signature and the Parameters section, so the published page should stay the same. I also reverted the @param wording change on _wp_utf8_codepoint_span() in 9b682d6, so now the docblock only gains the @param-out lines.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked both functions with the parser and developer theme pinned in the preview harness. I parsed trunk and 957f558, imported the records into a local WordPress test database, and rendered the signature, Parameters, and Return sections.

For both _wp_scan_utf8() and _wp_utf8_codepoint_span(), the PR added one distinct param-out tag to the stored metadata. The HTML for all three sections was byte-for-byte identical to trunk (six parameters and four, respectively). As a control, changing the description of $at changed the rendered Parameters section. This covers the reference sections affected by the annotations; I didn’t run the full Playground site.

AI review · gpt-6

* @return int How many code points were successfully scanned.
*/
function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max_bytes = null, ?int $max_code_points = null, ?bool &$has_noncharacters = null ): int {
Expand Down Expand Up @@ -151,7 +152,7 @@ function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max

// Covers the range U+FDD0–U+FDEF, U+FFFE, U+FFFF.
if ( 0xEF === $b1 ) {
$has_noncharacters |= (
$has_noncharacters = $has_noncharacters || (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this might result in a performance degradation inside a hot path, but I have not measured the change. it takes a branchless instruction and replaces it with a branching one.

in any case, this compat function is mostly here for edge cases where the built-in UTF-8 support is lacking, so if it does introduce a performance regression, that may be tolerable if the ultimate goal is ensuring that nothing expected appears for the types.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good point. I ran a quick benchmark to check. I compared the original |=, the || in this PR, and a third option that keeps a branchless |= on a local int and casts to bool before each return. Each ran on about 1 MB of text, 15 runs, taking the median, two separate runs each:

Text PHP 8.5 (native) PHP 8.3 (Docker)
all 4-byte emoji +0.3% / +3.0% +0.1% / −3.4%
all fullwidth 0xEF +1.3% / −2.1% +2.8% / +0.3%
CJK, 3-byte without 0xEF −1.1% / +0.3% +6.7% / +2.9%
mostly Latin with some emoji +1.0% / +1.1% −0.2% / −3.2%

These are || vs |=. The differences change direction between runs, and the largest one is on CJK text, where the changed line never runs, so it looks like noise rather than a regression. The local cast version wasn't consistently faster either. I'd lean toward keeping || for simplicity, but I'm happy to switch to the local cast version if you prefer to keep the hot path branchless.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are || vs |=

Are you saying that +6.7% / +2.9% means that the current patch’s || is 6.7% slower than trunk, and that using the branchless |= then casting at the end is 2.9% slower?

up until around 3% the variation seemed like plausible noise, but almost 7% seems surprising, as does the difference in PHP 8.3 vs. 8.5

I would have been happy with || if the benchmark were conclusive, but these numbers raise more questions to me.

15 runs, taking the median, two separate runs each

what does this mean?

can you do a few more checks?

  • use a full table so that the results aren’t ambiguous, showing which test group reports which numbers
  • include the absolute timings of these runs, since a few microseconds on a 1 MB document may still be insignificant even if it’s 100% slower
  • run the benchmarks once with -d opcache.enable_cli=true -d opcache.jit=on -d opcache.jit_buffer_size=50M and once with -d opcache.jit=off and report separately if the numbers are meaningfully different
  • make sure that the “15 runs” are interleaved between the test groups and the input groups. if we run the same branch on the same input 15 times in a row, it could have significant impacts on the findings. you can use random_int() to get a secure random pick among each group at each test tier and then continue testing until you have enough iterations on each group and each test

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran an independent comparison of trunk (accd2d4), this PR (957f558), and a local integer accumulator cast to bool on each return. On PHP 8.3 I could not reproduce the reported ~7% CJK slowdown in either JIT mode. These measurements are independent of the original author’s two runs.

Median milliseconds per scan of ~1 MiB, on the same arm64 Mac. The last two columns show the PR’s change versus trunk within each session. Negative means faster.

PHP JIT Input Trunk (ms) PR (ms) Local cast (ms) PR Δ run 1 PR Δ run 2
8.3.36 off emoji 63.83 62.46 63.36 -1.1% -3.4%
8.3.36 off fullwidth 75.04 72.55 76.17 -1.9% -3.5%
8.3.36 off CJK 63.87 65.21 65.14 +0.7% +1.2%
8.3.36 off Latin 38.82 38.80 38.82 +1.2% -0.3%
8.3.36 on emoji 23.20 22.69 23.35 -1.2% -4.0%
8.3.36 on fullwidth 27.23 25.92 27.73 -4.0% -4.1%
8.3.36 on CJK 26.07 25.82 25.96 -0.3% +1.1%
8.3.36 on Latin 34.74 34.88 34.81 +0.4% +0.9%
8.5.12 off emoji 37.11 36.54 36.36 +0.3% -4.5%
8.5.12 off fullwidth 45.17 45.96 45.85 +0.8% -0.4%
8.5.12 off CJK 40.97 41.13 41.76 -1.0% -1.5%
8.5.12 off Latin 3.21 3.16 3.13 +1.3% -8.3%
8.5.12 on emoji 20.94 19.61 20.91 -8.6% -7.4%
8.5.12 on fullwidth 25.57 23.96 25.82 -6.1% -4.5%
8.5.12 on CJK 23.13 23.57 23.52 +1.7% +0.0%
8.5.12 on Latin 1.99 1.85 1.98 -7.9% -3.3%

Each session used three warm-up rounds, then 20 measured rounds. Each round ran all 12 implementation/input pairs once in a freshly shuffled order. I pooled the two sessions for the absolute medians. The elapsed time covers only the scan. I checked the consumed length, count, invalid length, and noncharacter truth value after each scan.

Inputs repeated a four-byte emoji, fullwidth A, 漢, or a short English sentence followed by an emoji. The CJK input never reaches either changed comparison. CLI OPcache was enabled throughout, with a 50 MB JIT buffer. I verified the runtime JIT state in each process.

These inputs support keeping the simpler boolean expression on this machine. They don’t establish a general speedup. The original author can still clarify what the two earlier percentages represented.

AI review · gpt-6

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @lancewillett — this clears up the questions, and demonstrates the outcome I expected (this is not significant). I see around a couple of milliseconds at most difference between these on extraordinarily-long documents.

I think the 7% number is also probably explained in the original by the last row in the table: latin inputs in PHP 8.5 are so fast that minor differences in measurements appear with much higher percentages than is helpful.

must say I didn’t expect the non-branching case to be faster, but that’s why we measure 😄

it’s clear to say that any potential performance impact here is moot, and if anything, it’s likely marginally faster.

( 0xB7 === $b2 && $b3 >= 0x90 && $b3 <= 0xAF ) ||
( 0xBF === $b2 && ( 0xBE === $b3 || 0xBF === $b3 ) )
);
Expand All @@ -176,7 +177,7 @@ function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max
$i += 3;

// Covers U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, …, U+10FFFE, U+10FFFF.
$has_noncharacters |= (
$has_noncharacters = $has_noncharacters || (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm kinda surprised that ||= is not a valid assignment operator in PHP, when JavaScript and Perl have such logical shortcut assignment operators. That would have been a nice diff:

- $has_noncharacters |= (
+ $has_noncharacters ||= (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, me too

( 0x0F === ( $b2 & 0x0F ) ) &&
0xBF === $b3 &&
( 0xBE === $b4 || 0xBF === $b4 )
Expand Down Expand Up @@ -376,6 +377,7 @@ function _wp_utf8_codepoint_count( string $text, ?int $byte_offset = 0, ?int $ma
* @param ?int $found_code_points Optional. Will be set to number of found code points in
* span, as this might be smaller than the maximum count if
* the string is not long enough.
* @param-out int $found_code_points
* @return int Number of bytes spanned by the code points.
*/
function _wp_utf8_codepoint_span( string $text, int $byte_offset, int $max_code_points, ?int &$found_code_points = 0 ): int {
Expand Down
5 changes: 0 additions & 5 deletions tests/phpstan/baselines/parameterByRef.type.neon
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,6 @@ parameters:
identifier: parameterByRef.type
count: 1
path: ../../../src/wp-includes/class-wp-token-map.php
-
message: '#^Parameter &\$has_noncharacters by\-ref type of function _wp_scan_utf8\(\) expects bool\|null, int given\.$#'
identifier: parameterByRef.type
count: 2
path: ../../../src/wp-includes/compat-utf8.php
-
message: '#^Parameter &\$result by\-ref type of function _page_traverse_name\(\) expects array\<string\>, array given\.$#'
identifier: parameterByRef.type
Expand Down
30 changes: 0 additions & 30 deletions tests/phpstan/baselines/parameterByRef.unusedType.neon

This file was deleted.

154 changes: 154 additions & 0 deletions tests/phpunit/tests/compat/wpScanUtf8.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php
/**
* Unit tests covering _wp_scan_utf8().
*
* @package WordPress
* @subpackage Charset
*
* @group compat
*
* @covers ::_wp_scan_utf8
*/
class Tests_Compat_wpScanUtf8 extends WP_UnitTestCase {

/**
* Ensures that valid UTF-8 is scanned to the end, counting every code point.
*
* @ticket 65817
*
* @dataProvider data_valid_utf8
*
* @param string $text Valid UTF-8 text without noncharacters.
*/
public function test_counts_code_points_in_valid_utf8( string $text ) {
$at = 0;
$invalid_length = 0;
$has_noncharacters = null;

$count = _wp_scan_utf8( $text, $at, $invalid_length, null, null, $has_noncharacters );

$this->assertSame( mb_strlen( $text, 'UTF-8' ), $count, 'Should have counted every code point.' );
$this->assertSame( strlen( $text ), $at, 'Should have scanned to the end of the text.' );
$this->assertSame( 0, $invalid_length, 'Should not have found any invalid bytes.' );
$this->assertFalse( $has_noncharacters, 'Should not have found any noncharacters.' );
}

/**
* Data provider for {@see self::test_counts_code_points_in_valid_utf8()}.
*
* @return array<non-falsy-string, array{ 0: string }>
*/
public static function data_valid_utf8(): array {
return array(
'Empty string' => array( '' ),
'US-ASCII' => array( 'Hello, World!' ),
'Two-byte sequences' => array( "Pi\u{00F1}a \u{00E9}t\u{00E9}" ),
'Three-byte sequences' => array( "\u{65E5}\u{672C}\u{8A9E}" ),
'Four-byte sequences' => array( "\u{1F600}\u{1F170}\u{10348}" ),
'Mixed sequence lengths' => array( "a\u{00F1}\u{65E5}\u{1F600}z" ),
'Boundaries between lengths' => array( "\u{007F}\u{0080}\u{07FF}\u{0800}\u{FFFD}\u{10000}\u{10FFFD}" ),
'Combining character' => array( "e\u{0301}" ),
'Hangul syllable as conjoining jamo' => array( "\u{1112}\u{1161}\u{11AB}" ),
'Devanagari grapheme clusters' => array( "\u{0928}\u{092E}\u{0938}\u{094D}\u{0924}\u{0947}" ),
'Regional indicator pair (flag)' => array( "\u{1F1E7}\u{1F1E9}" ),
'Emoji with skin tone modifier' => array( "\u{1F44D}\u{1F3FD}" ),
'Keycap sequence' => array( "1\u{FE0F}\u{20E3}" ),
'ZWJ sequence' => array( "\u{1F469}\u{200D}\u{1F4BB}" ),
'ZWJ family sequence' => array( "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}" ),
'ZWJ sequence with VS-16' => array( "\u{1F3F3}\u{FE0F}\u{200D}\u{1F308}" ),
);
}

/**
* Ensures that each maximal subpart of an invalid byte sequence is reported
* as its own invalid span, so that it can be replaced by a single U+FFFD.
*
* @ticket 65817
*
* @dataProvider data_invalid_utf8
*
* @param string $text Text containing invalid UTF-8 bytes.
* @param list<positive-int> $expected_spans Byte length of each invalid span, in order.
* @param positive-int $expected_code_points Code points when each invalid span counts as one.
*/
public function test_finds_maximal_subparts_of_invalid_bytes( string $text, array $expected_spans, int $expected_code_points ) {
$end = strlen( $text );
$at = 0;
$invalid_length = 0;
$invalid_spans = array();
$code_points = 0;

while ( $at < $end ) {
$code_points += _wp_scan_utf8( $text, $at, $invalid_length );

if ( 0 === $invalid_length ) {
break;
}

$invalid_spans[] = $invalid_length;
++$code_points;
$at += $invalid_length;
}

$this->assertSame( $expected_spans, $invalid_spans, 'Should have found the maximal subpart of each invalid span.' );
$this->assertSame( $expected_code_points, $code_points, 'Should have counted one code point for each invalid span.' );
$this->assertSame( $end, $at, 'Should have scanned to the end of the text.' );
}

/**
* Data provider for {@see self::test_finds_maximal_subparts_of_invalid_bytes()}.
*
* @return array<non-falsy-string, array{ 0: string, 1: list<positive-int>, 2: positive-int }>
*/
public static function data_invalid_utf8(): array {
return array(
'Lone continuation byte' => array( "a\x80b", array( 1 ), 3 ),
'Run of continuation bytes' => array( "a\x80\xBF\x80b", array( 1, 1, 1 ), 5 ),
'Truncated two-byte sequence' => array( "a\xC3b", array( 1 ), 3 ),
'Truncated three-byte sequence' => array( "a\xE2\x82b", array( 2 ), 3 ),
'Truncated four-byte sequence' => array( "a\xF0\x9F\x98b", array( 3 ), 3 ),
'Truncated sequence at the end' => array( "abc\xF0\x9F\x98", array( 3 ), 4 ),
'Overlong two-byte sequence' => array( "a\xC0\xAFb", array( 1, 1 ), 4 ),
'Overlong three-byte sequence' => array( "a\xE0\x80\xAFb", array( 1, 1, 1 ), 5 ),
'UTF-16 surrogate half' => array( "a\xED\xA0\x80b", array( 1, 1, 1 ), 5 ),
'Code point above U+10FFFF' => array( "a\xF4\x90\x80\x80b", array( 1, 1, 1, 1 ), 6 ),
'Byte that never appears in UTF-8' => array( "a\xFFb", array( 1 ), 3 ),
'Windows-1252 encoded text' => array( "Pi\xF1a", array( 1 ), 4 ),
'Truncated sequences back to back' => array( "\xE2\x82\xF0\x9F\x98", array( 2, 3 ), 2 ),
'Invalid span between valid multibyte' => array( "\u{1F600}\xE2\x82\u{65E5}", array( 2 ), 3 ),
);
}

/**
* Tests scanning UTF-8 string containing noncharacters.
*
* @ticket 65817
*
* @dataProvider data_strings_with_noncharacters
*
* @param string $text UTF-8 string containing a noncharacter.
*/
public function test_scan_string_with_noncharacters( string $text ) {
$at = 0;
$invalid_length = 0;
$has_noncharacters = null;

_wp_scan_utf8( $text, $at, $invalid_length, null, null, $has_noncharacters );

$this->assertTrue( $has_noncharacters );
}

/**
* Data provider for {@see self::test_scan_string_with_noncharacters()}.
*
* @return array<non-falsy-string, array{ 0: string }>
*/
public static function data_strings_with_noncharacters(): array {
return array(
'U+FFFF (3-byte noncharacter)' => array( "test \xEF\xBF\xBF end" ),
'U+FFFE (3-byte noncharacter)' => array( "test \xEF\xBF\xBE end" ),
'U+FDD0 (3-byte noncharacter)' => array( "test \xEF\xB7\x90 end" ),
'U+1FFFF (4-byte noncharacter)' => array( "test \xF0\x9F\xBF\xBF end" ),
);
}
}
Loading