Search by

1:1 PHP bindings of SheenBidi: the Unicode Bidirectional Algorithm, paragraph levels, line runs in visual order, script runs and mirrored characters

Package info

github.com/php-io-extensions/sheenbidi

Language:C

Type:php-ext

Ext name:ext-sheenbidi

pkg:composer/php-io-extensions/sheenbidi

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.11.0 2026-12-05 05:39 UTC

This package is auto-updated.

Last update: 2026-12-05 05:41:37 UTC


README

ext-sheenbidi

SheenBidi bound 1:1 into PHP 8.4+, at the 3.0.0 API

CI SheenBidi API Packagist PHP License Platform OKF PIE

Text in a string is stored in logical order, the order it is typed and read, but a line that mixes Hebrew or Arabic with Latin is not drawn in that order. "Hello, שלום (עולם)!" is drawn with the Hebrew words right to left inside a left-to-right line, and the parentheses around a right-to-left word are drawn mirrored, so "(" shows as ")". Which characters run in which direction depends on every character's bidirectional type, its neighbours, the paragraph's base direction and any explicit embedding marks, and getting it wrong puts words in the wrong place and cursors in the wrong gap.

SheenBidi answers that question. It implements the Unicode Bidirectional Algorithm (UAX #9), from paragraph boundaries (rule P1) through mirroring (rule L4): give it a string, and it resolves each paragraph's embedding levels, cuts a line into runs in visual order, and finds the characters to draw mirrored. It also finds runs of one script (UAX #24), the unit a shaper works on. It is written in C, and its headers document every call.

The only problem? PHP can't reach it. This extension binds SheenBidi one to one under the C names, at the SheenBidi 3.0.0 API: codepoint properties and decoding, the algorithm, paragraphs and lines, and the script and mirror locators. Handles are one PHP object per native pointer, counted with SheenBidi's own retain and release calls, the levels, runs and agents SheenBidi keeps come back as their addresses, and the code units SheenBidi would read past a string are refused before it reads them. No defaults, no composites, no opinions: what SheenBidi documents is what you call.

Basic usage

Most ways you will interface with ext-sheenbidi are in two parts -

Resolve a paragraph and cut a line. An SBCodepointSequence names the string, its encoding and its length in code units; SBAlgorithmCreate() reads the bidirectional types, SBAlgorithmCreateParagraph() resolves the levels, with the base level taken from the first strong character for SBLevelDefaultLTR, and SBParagraphCreateLine() orders a line's runs:

$text = 'Hello, שלום (עולם)!';
$sequence = new SBCodepointSequence();
$sequence->stringEncoding = SBStringEncodingUTF8;
$sequence->stringBuffer = $text;
$sequence->stringLength = strlen($text);

$algorithm = SBAlgorithmCreate($sequence);
$paragraph = SBAlgorithmCreateParagraph($algorithm, 0, strlen($text), SBLevelDefaultLTR);
$line = SBParagraphCreateLine($paragraph, 0, SBParagraphGetLength($paragraph));
echo 'base level ', SBParagraphGetBaseLevel($paragraph), "\n";

Read the runs and the mirrors. The runs are an array the line keeps, in visual order, read through SBRun, a run every 24 bytes on a 64-bit build. The mirror locator's agent is a record the locator rewrites at each move; its address is copied here with ext-posi, 16 bytes (the code unit index, then the codepoint to draw). Release what you made when you're done:

$read = static function (int $address, int $size): string {
    $copy = posi_mem_alloc($size);
    memcpy($copy, $address, $size);
    $bytes = posi_mem_read($copy, $size);
    posi_mem_free($copy);

    return $bytes;
};
$runs = SBLineGetRunsPtr($line);
for ($i = 0; $i < SBLineGetRunCount($line); $i++) {
    $run = SBRun::fromPointer($runs + 24 * $i);
    printf("run %d  level %d  %s\n", $i, $run->level, substr($text, $run->offset, $run->length));
}

$mirror = SBMirrorLocatorCreate();
SBMirrorLocatorLoadLine($mirror, $line, $text);
while (SBMirrorLocatorMoveNext($mirror)) {
    ['index' => $index, 'mirror' => $glyph] = unpack('Qindex/Lmirror', $read(SBMirrorLocatorGetAgent($mirror), 16));
    printf("byte %d  draw U+%04X\n", $index, $glyph);
}

SBMirrorLocatorRelease($mirror);
SBLineRelease($line);
SBParagraphRelease($paragraph);
SBAlgorithmRelease($algorithm);
$ php order.php
base level 0
run 0  level 0  Hello, 
run 1  level 1  שלום (עולם)
run 2  level 0  !
byte 16  draw U+0029
byte 25  draw U+0028

An odd level runs right to left: the run at level 1 is drawn with its characters reversed, and the "(" at byte 16 is drawn as ")". Each run goes to a shaper such as ext-harfbuzz in that direction.

Requirements

OS Linux or macOS. composer.json lists those two families.
PHP 8.4 or newer, NTS or ZTS.
Libraries SheenBidi 3.0.0 or newer, with its headers, found through pkg-config (sheenbidi). 3.0.0 is the floor: nothing newer is bound.

To build it you need a C compiler, pkg-config, SheenBidi's development files, and the development files of the PHP you intend to load it into. Debian forky packages SheenBidi 3.0.0 and Homebrew bottles it; Debian Trixie, Ubuntu 24.04 and 26.04 and Raspberry Pi OS do not, so there it is built from its v3.0.0 tag with CMake, into /usr/local:

# Debian forky
sudo apt install build-essential pkg-config libsheenbidi-dev php8.4-dev

# Debian Trixie, Ubuntu, Raspberry Pi OS
sudo apt install build-essential pkg-config cmake git php8.4-dev
git clone --depth 1 --branch v3.0.0 https://github.com/Tehreer/SheenBidi.git
cmake -S SheenBidi -B SheenBidi/build -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Release
cmake --build SheenBidi/build -j"$(nproc)"
sudo cmake --install SheenBidi/build && sudo ldconfig

# macOS: Xcode Command Line Tools, and Homebrew's PHP ships phpize and php-config
xcode-select --install
brew install pkgconf sheenbidi php@8.4

Installation

With PHP PIE (recommended)

PIE is the PHP Foundation's installer for extensions. It downloads the tagged source from Packagist, builds it against the PHP on your PATH, installs the module and enables it. sudo where your PHP's extension directory is root-owned, as on Debian; not on a Homebrew Mac. Install SheenBidi first:

pie install php-io-extensions/sheenbidi

Manually (install script)

The repository ships two installers, one per platform. Each one builds for each PHP it targets, installs sheenbidi.so into that PHP's extension_dir, writes 30-sheenbidi.ini into its conf.d scan directory, and checks the module loads. The macOS one builds in a temporary copy of the checkout and ad-hoc signs the module so the system loads it on first use; the Debian one builds in the checkout, writes the ini into the CLI, FPM and Apache conf.d of that PHP, and cleans the build products out afterwards.

git clone https://github.com/php-io-extensions/sheenbidi.git
cd sheenbidi

./install-debian-trixie.sh             # Debian Trixie, Ubuntu 24.04+, Raspberry Pi OS: the php on PATH
./install-macos.sh                     # Homebrew php@8.4 and php@8.4-zts
./install-macos.sh /path/to/bin/php    # the macOS script takes specific PHP binaries

Manually (phpize)

git clone https://github.com/php-io-extensions/sheenbidi.git
cd sheenbidi
phpize
./configure --enable-sheenbidi
make -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)"
sudo make install

Then enable it: add extension=sheenbidi.so to your php.ini, or drop that line into a file in the scan directory that php --ini reports.

Verify

php --ri sheenbidi also names the SheenBidi headers it was built against and the library it runs with:

$ php --ri sheenbidi

sheenbidi

sheenbidi support => enabled
Version => 0.11.0
SheenBidi headers => 3.0.0
SheenBidi library => 3.0.0

API

Function, handle and constant names are the C names, so SheenBidi's headers are the reference: 45 functions, one stub per group in stubs/, each declared with its PHP types. SUPPORT.md lists every function SheenBidi 3.0.0 declares, bound or not; the API badge is computed from it. The text API (SBText*, SBAttribute*) is compiled only with SB_CONFIG_EXPERIMENTAL_TEXT_API, which neither SheenBidi's own build nor a distribution's turns on, so it is not counted.

Stub Functions What it covers
SBAlgorithm 19 SBAlgorithmCreate(), SBAlgorithmGetBidiTypesPtr(), SBAlgorithmGetParagraphBoundary(), SBAlgorithmCreateParagraph(), SBParagraphGetOffset(), SBParagraphGetLength(), SBParagraphGetBaseLevel(), SBParagraphGetLevelsPtr(), SBParagraphCreateLine(), SBLineGetOffset(), SBLineGetLength(), SBLineGetRunCount(), SBLineGetRunsPtr(), and the retain and release calls; the SBAlgorithmRef, SBParagraphRef and SBLineRef handles; the SBRun record.
SBCodepoint 12 SBCodepointGetBidiType(), SBCodepointGetGeneralCategory(), SBCodepointGetMirror(), SBCodepointGetScript(), the UTF-8 and UTF-16 decoders, SBCodepointSequenceGetCodepointBefore(), SBCodepointSequenceGetCodepointAt(), SBScriptGetUnicodeTag(), SBVersionGetString(); the SBCodepointSequence record.
SBLocator 14 SBScriptLocatorCreate(), SBScriptLocatorLoadCodepoints(), SBScriptLocatorGetAgent(), SBScriptLocatorMoveNext(), SBScriptLocatorReset(), the mirror locator's five of the same, and the retain and release calls; the SBScriptLocatorRef and SBMirrorLocatorRef handles; the SBScriptAgent record.
sheenbidi — The SBBidiType*, SBGeneralCategory* and SBScript* values, the SBStringEncoding* encodings, the SBLevel* levels, SBCodepointMax, SBCodepointInvalid, SBCodepointFaulty and the SHEENBIDI_VERSION_* numbers.

Translations

Every C parameter is its own PHP parameter, in C order. The only differences from C:

  • const SBCodepointSequence * is an SBCodepointSequence: a final record with int $stringEncoding, ?string $stringBuffer and int $stringLength, copied in for each call. stringLength counts code units of the encoding: bytes for SBStringEncodingUTF8, 16-bit units for SBStringEncodingUTF16, 32-bit units for SBStringEncodingUTF32, in host byte order. A decoder's const SBUInt8 * or const SBUInt16 * buffer is a string, with $length counted the same way.
  • An out-parameter is a by-reference parameter: SBAlgorithmGetParagraphBoundary() writes $acutalLength (SheenBidi's spelling) and $separatorLength, and the decoders and SBCodepointSequenceGet*() read and advance $index or $stringIndex in place, as in C.
  • SBUInteger, SBLevel, SBCodepoint, SBBidiType, SBGeneralCategory, SBScript and SBStringEncoding are int. SBBoolean is bool.
  • SBAlgorithmGetBidiTypesPtr(), SBParagraphGetLevelsPtr() and SBLineGetRunsPtr() answer the address of the array the algorithm, paragraph or line keeps, and SBScriptLocatorGetAgent() and SBMirrorLocatorGetAgent() the address of the record the locator rewrites at each move. Each is SheenBidi's memory until the last release of its owner. On a 64-bit build an SBRun and an SBScriptAgent are 24 bytes (offset and length as 64-bit unsigned integers, then the level or the script as a byte) and an SBMirrorAgent is 16 (index as a 64-bit unsigned integer, then mirror and codepoint as 32-bit unsigned integers).
  • SBRun and SBScriptAgent read those records where SheenBidi keeps them: final, with fromPointer() and pointer() as a handle has, and readonly int fields (offset, length, and level or script) that read the native record each time they are read. Run $i of a line is SBRun::fromPointer(SBLineGetRunsPtr($line) + 24 * $i); SBScriptAgent::fromPointer(SBScriptLocatorGetAgent($locator)) answers the next run after each SBScriptLocatorMoveNext(). A record holds no reference: it is valid while its owner is.
  • SBMirrorLocatorLoadLine() loads the line only when $stringBuffer is the very string the line's sequence was made from: SheenBidi compares the addresses. Pass the same PHP string, unchanged; a copy, or null, leaves the locator with no line.
  • SBAlgorithmRef, SBParagraphRef, SBLineRef, SBScriptLocatorRef and SBMirrorLocatorRef are final handles with a private constructor, not cloneable or serializable, with pointer(): int and static fromPointer(int $pointer): static. fromPointer() trusts any address other than 0. The same native pointer and class in one thread is the same PHP object.

Lifetime

Dropping the last PHP reference does not release the native object: SheenBidi counts its own references, so call the SB*Release() that matches each SB*Create() and SB*Retain(). The release that drops the last reference PHP holds empties the handle. An algorithm, a paragraph and a line read the string of the sequence the algorithm was made from, a script locator the string of the sequence it last loaded, and a mirror locator the string of the line it last loaded; each of their handles keeps that PHP string until its last release, so a string reassigned or unset in PHP is never read after it is freed. The arrays and agents the *Ptr() and *GetAgent() calls point at belong to their owner and are freed with it.

Refusals

The extension refuses four kinds of call, each of which crashes the process otherwise (tests/Probes shows each crash on a probe build):

  • A handle that holds NULL (released by its last release, or made from address 0) in any call that takes an algorithm, a paragraph, a line or a locator: ValueError. SheenBidi reads each one without a check, and its retain and release calls change the count in place.
  • An SBCodepointSequence whose stringLength is past the end of its stringBuffer in SBAlgorithmCreate(), SBScriptLocatorLoadCodepoints() and SBCodepointSequenceGet*(), or that has a stringLength and no stringBuffer in the last two: ValueError. SheenBidi reads as many code units as stringLength says.
  • A $length past the end of the buffer in the UTF-8 and UTF-16 decoders: ValueError.
  • A field read on an SBRun or SBScriptAgent made from address 0: ValueError. The field is read at the address the record holds.

A null stringBuffer passes through to SBAlgorithmCreate(), which answers null, and a null line to SBMirrorLocatorLoadLine(), which loads nothing.

Extensions you might use with this one

  • ext-harfbuzz: shapes each run SheenBidi orders, in the run's direction and script.
  • ext-freetype: renders the glyphs HarfBuzz picks.
  • ext-posi: copies the levels, runs and agents SheenBidi keeps so PHP can read them.

AI-assisted development

This codebase was built with LLM assistance under human direction. Prompts, reviews, and architectural decisions were owned by a professional software engineer — the model accelerates drafting and exploration; it does not replace judgment on APIs, dependency direction, or what ships.

Agentic Documentation

This repository carries an Open Knowledge Format bundle at .okf/: Markdown with YAML frontmatter, readable by you and loadable by a coding agent. It records what the README doesn't: every function, class and constant by stub, how handles keep one PHP object per native pointer and the string their native object reads, which NULL handles pass through and which are refused, how to build release and probe builds, how to add a binding, and a log of every change that altered behaviour.

Start at .okf/index.md. AGENTS.md is the short rule sheet an agent reads before touching the C, the stubs, or packaging; each rule points into the bundle for the reason behind it.

Point your agent at the repo and it has the same context the maintainer has. Point yourself at it when the README's answer is "it does X" and you want "because".

Resources

  • SheenBidi: the library, its headers and their documentation of every call this extension binds; this README only adds what PHP changes.
  • SheenBidi 3.0.0: the upstream tag the stubs and SUPPORT.md are checked against.
  • UAX #9: the Unicode Bidirectional Algorithm SheenBidi implements.
  • PIE: the PHP Foundation's extension installer.
  • gen_stub.php: the php-src stub format. stubs/ holds the API declarations; each *_arginfo.h is generated from its stub.
  • Open Knowledge Format: the spec the .okf/ bundle follows.

Running the test suite

The suite is Pest v4: codepoint properties and decoding in UTF-8 and UTF-16, paragraph levels for left-to-right, right-to-left and mixed text, paragraph boundaries, line runs in visual order, script runs, mirrors, retain and release counts, handle identity, and the coverage script. It runs on Linux and macOS. It needs ext-posi for its memory tests; the package itself does not use it. ext-posi copies the levels, runs and agents SheenBidi keeps so those tests can read them, and without it they are skipped with a message naming ext-posi; install with composer install --ignore-platform-req=ext-posi then. Build the module, then enable it through an ini scan directory rather than -d, so the child processes the tests start load it too:

git clone https://github.com/php-io-extensions/sheenbidi.git
cd sheenbidi
phpize && ./configure --enable-sheenbidi && make -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)"
composer install
mkdir -p /tmp/sheenbidi-ini && echo "extension=$PWD/modules/sheenbidi.so" > /tmp/sheenbidi-ini/30-sheenbidi.ini
PHP_INI_SCAN_DIR=":/tmp/sheenbidi-ini" php -d memory_limit=128M vendor/bin/pest
Tests:    9 skipped, 47 passed (91 assertions)
Duration: 0.17s

The nine skipped tests are in tests/Probes: they run only against a probe build (./configure --enable-sheenbidi --enable-sheenbidi-probes, or SHEENBIDI_CONFIGURE=--enable-sheenbidi-probes ./install-macos.sh), which can turn each refusal off to show the crash it prevents. Never install a probe build for use.

The leading : keeps your PHP's own scan directory and adds the second one. If that PHP already loads an installed sheenbidi.so, the suite warns Module "sheenbidi" is already loaded and tests the installed one instead; copy the scan directory somewhere, replace its sheenbidi ini with the line above, and point PHP_INI_SCAN_DIR at the copy without the colon. A module only loads in the PHP whose phpize built it: for Homebrew's ZTS build, run phpize and pass --with-php-config from /opt/homebrew/opt/php@8.4-zts/bin. Set XDEBUG_MODE=off for any timing you intend to read.

Contributing

Open an issue first for anything beyond a typo. Pull requests change a stub in stubs/ and the C under src/ together, regenerate the *_arginfo.h files with gen_stub, regenerate SUPPORT.md and the API badge with php scripts/support.php, and add a Pest test for the behaviour. A new refusal needs a probe test that shows the crash it prevents. CI must be green on every cell of the matrix, NTS and ZTS alike. Read AGENTS.md for the rules the code follows.

Security

ext-sheenbidi hands strings to SheenBidi, which reads them as many code units as it is told. See SECURITY.md for what it guards against and how to report a vulnerability.

License

MIT. See LICENSE. SheenBidi is under the Apache License 2.0; it is linked, not shipped.