Registry / serialization / phpegjs

phpegjs

JSON →
library1.0.0-beta7jsnpmunverified

`phpegjs` is a plugin for the PEG.js parser generator that enables the generation of parsers in PHP. Currently in beta version 1.0.0-beta7, it extends PEG.js to output PHP source code based on a given grammar, allowing developers to define complex parsing logic using PEG.js's syntax and then deploy the resulting parser in a PHP environment. This library acts as a crucial bridge for projects requiring robust parsing capabilities in PHP without manually writing lexical analyzers and parsers. It maintains compatibility with various PHP versions, offering options for namespace management and `mbstring` extension usage. The project is a fork of `php-pegjs` and focuses on providing a stable PHP target for PEG.js grammars, making it a key tool for language processing, DSL implementation, or complex data format parsing within PHP applications. Its release cadence is tied to its beta status, with updates reflecting progress towards a stable 1.0 release.

npm install phpegjs
INSTALL
IMPORT
SIG · PHPEGJS
P
phpegjs
serializationjavascriptv1.0.0-beta7
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pegjs
const pegjs = require('pegjs');
import pegjs from 'pegjs';
The official documentation for this beta version uses CommonJS `require`. For modern Node.js environments, ESM `import` might be used, but confirm compatibility.
phpegjs
const phpegjs = require('phpegjs');
import phpegjs from 'phpegjs';
`phpegjs` is primarily consumed as a plugin passed to `pegjs.buildParser`. The documentation uses CommonJS `require` for its integration.
plugin options
pegjs.buildParser(grammar, { plugins: [phpegjs], phpegjs: { /* plugin options */ } });
The `phpegjs` plugin instance is passed in the `plugins` array, and `phpegjs`-specific configuration options are provided within an object under the `phpegjs` key in the main options object.

Demonstrates how to use `phpegjs` with PEG.js to define a simple arithmetic grammar, generate the corresponding PHP parser code, and provides a conceptual example of how to instantiate and use the generated parser in a PHP application.

const pegjs = require("pegjs"); const phpegjs = require("phpegjs"); const grammar = ` start = expression expression = left:term op:("+"|"-") right:expression { return { type: "binary", op, left, right }; } / term term = left:factor op:("*"|"/") right:term { return { type: "binary", op, left, right }; } / factor factor = number / "(" expression:expression ")" { return expression; } number "number" = [0-9]+ { return parseInt(text(), 10); } `; try { const phpParserSource = pegjs.buildParser(grammar, { plugins: [phpegjs], cache: true, // Recommended for larger grammars phpegjs: { parserNamespace: 'MyNamespace', parserClassName: 'SimpleCalculator' } }); console.log("Generated PHP Parser Source (first 200 chars):\n", phpParserSource.substring(0, 200) + '...'); // In a real application, you would save phpParserSource to a file, // e.g., './src/MyNamespace/SimpleCalculator.php' // Example PHP usage (conceptual): // ----------------------------------------------------- // File: my_parser_app.php // <?php // require_once __DIR__ . '/src/MyNamespace/SimpleCalculator.php'; // try { // $parser = new MyNamespace\\SimpleCalculator(); // $input = "1 + 2 * (3 - 1)"; // $result = $parser->parse($input); // echo "Input: " . $input . "\n"; // echo "Result (AST): " . json_encode($result, JSON_PRETTY_PRINT) . "\n"; // } catch (MyNamespace\\SyntaxError $ex) { // echo "Syntax error: " . $ex->getMessage() . // ' at line ' . $ex->grammarLine . // ' column ' . $ex->grammarColumn . // ' offset ' . $ex->grammarOffset . "\n"; // } // ?> // ----------------------------------------------------- } catch (e) { console.error("Error building parser:", e.message); }
Debug
Known issues
breakingDisabling `mbstringAllowed` (by setting `phpegjs.mbstringAllowed: false`) will disable case-insensitive string matching, case-insensitive character classes, and empty character classes in the generated PHP parser. Attempting to use these features will result in `buildParser` throwing an error.
fix
Ensure `mbstringAllowed` is `true` (default) if these features are required and the PHP `mbstring` extension is available, or avoid using these features if the extension is not installed.
affects: >=1.0.0-beta7
gotchaUsing the `parserGlobalNamePrefix` option sacrifices modern PHP namespace usage for PHP 5.2 compatibility. For PHP 5.3+ environments, prefer `parserNamespace` for better code organization and adherence to PSR standards.
fix
For PHP 5.3 and later, set `phpegjs.parserNamespace` to define a namespace for the generated parser class. Only use `parserGlobalNamePrefix` if strict PHP 5.2 compatibility is a non-negotiable requirement.
affects: >=1.0.0-beta7
gotchaFor large or complex grammars, not enabling the `cache` option in `pegjs.buildParser` can lead to significantly slower, even exponential, parsing times in pathological cases due to redundant computations during the parsing process.
fix
Always set `cache: true` in the `pegjs.buildParser` options object, especially for complex or frequently used grammars, to enable memoization and optimize parsing performance.
affects: >=1.0.0-beta7
gotchaThe generated PHP parser uses `preg_match_all('/./us', ...)` on the input string, which may cause issues with older PCRE versions lacking Unicode support. This is particularly relevant for environments like older WordPress installations or certain shared hosting setups.
fix
If Unicode PCRE support is a concern or leads to unexpected behavior, pre-split the input string into an array of UTF-8 characters (e.g., `mb_str_split` in PHP) and pass this array directly to the parser's `parse` method instead of the raw string.
affects: >=1.0.0-beta7
Errors
Common errors & fixes
PEG.js: Error: Character class cannot be empty.
This error occurs during parser generation if `phpegjs.mbstringAllowed` is set to `false`, and the grammar contains an empty character class or a character class that effectively becomes empty (e.g., due to case-insensitivity rules not supported without `mbstring`).
fix
Either set `phpegjs.mbstringAllowed: true` in your `buildParser` options (requires PHP `mbstring` extension) or modify your grammar to remove the offending empty character class.
Uncaught exception 'MyNamespace\SyntaxError' with message 'Expected ...'
The input string provided to the generated PHP parser does not conform to the grammar rules, leading to a parsing failure at a specific point.
fix
Review the input string for syntax errors based on your grammar. Utilize the `grammarLine`, `grammarColumn`, and `grammarOffset` properties of the `SyntaxError` exception for precise debugging location.
Class 'MyNamespace\Parser' not found
The generated PHP parser file has not been correctly included in your PHP script, or the namespace used during instantiation does not match what was specified during parser generation.
fix
Ensure the generated PHP parser file is included using `require_once` or `include` at the beginning of your PHP script. Verify that the namespace used when instantiating the parser (e.g., `new MyNamespace\Parser()`) precisely matches the `parserNamespace` option configured in the `pegjs.buildParser` call.
Upgrade
Version history
1.0.0-beta7latest on npm
Audit
Dependencies
pegjsrequired`phpegjs` is a plugin for PEG.js and requires it to generate parsers.
Agent activity
2 hits · last 30 days
node
2
Resources