定制 procionegobbo/polygen-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

procionegobbo/polygen-php

Composer 安装命令:

composer require procionegobbo/polygen-php

包简介

PHP 8.4+ implementation of Polygen - random sentence generator with BNF-like grammars

README 文档

README

A PHP 8.4+ implementation of Polygen - a random sentence generator based on BNF-like grammar definitions.

Disclaimer

This project is a tribute to the legendary Polygen. It was created almost entirely with Claude Code and makes no claim to approach the brilliance of Alvise Spanò's original implementation. The purpose of this project is simply to try to create a Composer-compatible implementation for the PHP community.

Features

  • Full implementation of the Polygen Meta Language (PML) parser
  • Recursive grammar evaluation with label filtering
  • Weighted random selection with shuffle algorithm
  • Support for definitions (::=) and assignments (:=)
  • Optional groups [...]
  • Mobile/shuffle groups {...} with all permutations
  • Multi-label selectors .(label1|label2)
  • Scoped redefinitions with inline declarations (X := value; body)
  • Deep unfold operator >>...<< for inlining alternatives
  • Terminal operators: epsilon _, concatenation ^, capitalization \
  • Non-terminal references and sub-grammarsIl
  • Label-based filtering and selection

Installation

Install via Composer:

composer require procionegobbo/polygen-php

Then use it in your code:

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Polygen\Polygen;

Usage

Basic Example

$grammar = 'S ::= hello world | goodbye world ;';
$generator = new Polygen($grammar);

echo $generator->generate();  // Output: "hello world" or "goodbye world"

Using Alternatives

$grammar = 'Greeting ::= hello | hi | hey ;
           Recipient ::= world | there ;
           S ::= Greeting Recipient ;';

$generator = new Polygen($grammar);
echo $generator->generate();  // "hello world", "hi there", etc.

Optional Groups

$grammar = 'S ::= hello [beautiful] world ;';
$generator = new Polygen($grammar);

// Generates either "hello world" or "hello beautiful world"
echo $generator->generate();

Capitalization and Concatenation

$grammar = 'S ::= \ hello ^ man ;';
$generator = new Polygen($grammar);

echo $generator->generate();  // "Hello man"
//                               ^ capitalize next word
//                                  ^ no space (concatenation)

Definitions vs Assignments

// Definition (re-evaluate each time)
$grammar = 'Color ::= red | blue | green ;
           S ::= Color Color ;';
$generator = new Polygen($grammar);
echo $generator->generate();  // e.g., "red blue" or "green green"

// Assignment (memoize result)
$grammar = 'Color := red | blue | green ;
           S ::= Color Color ;';
$generator = new Polygen($grammar);
echo $generator->generate();  // Always "color color" with the same color twice

Architecture

The implementation follows the original OCaml architecture:

Grammar String
    ↓
Lexer (tokenizes input)
    ↓
Parser (builds AST - Absyn0)
    ↓
Preprocessor (optimizes AST - Absyn1)
    ↓
Generator (random evaluation)
    ↓
Output String

File Structure

polygen-php/
├── src/
│   ├── Polygen.php                 # Main API facade
│   ├── Lexer/
│   │   ├── TokenType.php           # Token enum
│   │   ├── Token.php               # Token value object
│   │   └── Lexer.php               # Tokenizer
│   ├── Parser/
│   │   ├── Parser.php              # Recursive-descent parser
│   │   └── Ast/
│   │       ├── TerminalNode.php, TerminalEpsilon.php, TerminalConcat.php, etc.
│   │       ├── AtomNode.php, AtomTerminal.php, AtomNonTerm.php, etc.
│   │       ├── SeqNode.php, ProdNode.php, DeclNode.php, BindMode.php
│   ├── Preprocessor/
│   │   └── Preprocessor.php        # Optimization pass
│   └── Generator/
│       └── Generator.php           # Random generation engine
├── tests/                          # 127 comprehensive test cases
├── composer.json                   # Package metadata
└── [Documentation]                 # README, QUICKSTART, TESTING, INDEX

PML Grammar Syntax

Basic Rules

Name ::= definition ;

Alternatives

S ::= hello | goodbye ;

Terminals (Operators)

  • word - literal text
  • "quoted string" - quoted text
  • _ - epsilon (produces nothing)
  • ^ - concatenation (no space before next)
  • \ - capitalize next word

Grouping

  • (sub) - sub-expression
  • [sub] - optional (sub | nothing)
  • {sub} - mobile (shuffle)

Labels and Selection

S ::= word.label | word ;

Known Limitations

The implementation supports nearly all core PML features. The following are not yet implemented:

  • Path-based non-terminal references (e.g., module/symbol)
  • Import statements and file inclusion
  • Some advanced scoping rules in the original Polygen

Nested comments: Fully supported ✓ Mobile groups: Fully supported ✓ Deep unfold: Fully supported ✓ Multi-label selectors: Fully supported ✓ Scoped redefinitions: Fully supported ✓

Testing

Run the test suite with Composer:

composer test

Or run example scripts:

php examples.php
php simple_test.php
php test.php

Future Developments

Numeric Label Selectors

The original OCaml Polygen supports numeric label selectors - using numeric indices as shortcuts for selecting alternatives:

% Original Polygen (not yet supported in PHP):
Item ::= 1: apple | 2: banana | 3: orange ;
S ::= I like Item.1 ;  % Selects "apple"

This feature is used in approximately 5 real-world grammar files (3.4% of test suite). Implementation would require:

  1. Lexer enhancement: Support digit-only label tokens
  2. Parser update: Allow numeric selectors in label position
  3. Preprocessor mapping: Map numeric indices to internal label representation
  4. Generator support: Resolve numeric labels to alternatives

Status: Not implemented due to:

  • Reduced readability compared to named labels
  • Low usage in real-world grammars (3.4%)
  • Potential for confusion with line numbers and array indices
  • Standard PML uses identifier-based labeling

Workaround: Convert numeric labels to identifier-based labels:

% Polygen PHP (supported):
Item ::= apple: apple | banana: banana | orange: orange ;
S ::= I like Item.apple ;  % Explicitly named

Advanced Features

Other original Polygen features that could be added:

  • Weighted multi-label selection: .(++A|B) syntax for prioritizing label options
  • Chained numeric selection: .1.2.3 to select union of alternatives
  • Numeric alternative unions: Selecting multiple alternatives by index in one selector

These remain low-priority due to niche usage and better alternatives available through standard PML syntax.

PML Specification & Resources

Official Documentation

PML Language Reference

The Polygen Meta Language (PML) is documented in the original Polygen repository:

  • Grammar Syntax: See docs/ or inline documentation in original repository
  • Tutorial & Examples: Available in the original Polygen distribution
  • Grammar Collection: The grm/ directory contains 150+ example grammars in Italian, English, and French

Related Resources

Polygen PHP Documentation

This implementation includes:

  • README.md - Overview and features
  • QUICKSTART.md - Quick setup and basic examples
  • INDEX.md - File structure and architecture
  • CLAUSE.md - Detailed implementation notes
  • GRAMMAR_TEST_RESULTS.md - Test results against 150+ grammars
  • UNSUPPORTED_SYNTAX_ANALYSIS.md - Details on unsupported features

Acknowledgments

This PHP 8.4+ implementation is a port of the original Polygen project by Alvise Spanò (@alvisespano).

The original Polygen is an OCaml implementation of a random sentence generator based on BNF-like grammars. This port preserves the core architecture and grammar syntax while adapting it for modern PHP with strict typing, sealed classes, and zero external dependencies.

Original Repository: https://github.com/alvisespano/Polygen

License

MIT License - Same terms as the original Polygen project.

procionegobbo/polygen-php 适用场景与选型建议

procionegobbo/polygen-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 33 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「generator」 「random」 「grammar」 「bnf」 「polygen」 「pml」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 procionegobbo/polygen-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 procionegobbo/polygen-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 procionegobbo/polygen-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 33
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 26
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-14