Skip to content

Syntaxx-HQ/PHPX-Compiler

Repository files navigation

PHPX - JSX-like Syntax for PHP

PHPX is a powerful library that brings JSX-like syntax to PHP, enabling developers to write component-based UI code in PHP with a familiar JSX syntax. It supports both Frontend rendering through WebAssembly and Server-Side Rendering (SSR).

Features

  • JSX-like syntax in PHP: Write React-style components with familiar JSX syntax
  • Component-based architecture: Build modular, reusable UI components
  • Dual-target support: Compile for both Frontend (WebAssembly) and Server-Side Rendering
  • Seamless integration: Works with existing PHP applications
  • Developer-friendly: Familiar syntax for React/JSX developers
  • Type-safe development: Leverage PHP's type system for component props
  • Powerful CLI: Multi-level verbose mode with colored output and JSON format
  • Rust-style error messages: Beautiful, context-rich error formatting with hints
  • Source maps: Debug mode generates source maps (v3) for accurate error tracking
  • AI/LLM-friendly: Structured JSON output, AI source maps with semantic context, and LLM-optimized debugging hints
  • Event system: Hook into the compilation process for custom tooling and monitoring
  • Zero configuration: Works out of the box with sensible defaults

Quick Start

New to PHPX? Start with the PHPX Guide for a complete introduction!

Installation

composer require syntaxx/phpx-parser

Basic Usage

<?php

use Syntaxx\PHPX\Parser;

$component = <div>
    <h1>Hello, PHPX!</h1>
    <p>This is a component written in PHPX syntax</p>
</div>;

$html = Parser::render($component);

Compiler Usage

The PHPX compiler can transform PHPX files (.phpx) into standard PHP files:

# Basic compilation (directory)
./bin/compile <input_directory> [output_directory]

# Single file compilation
./bin/compile src/Component.phpx build/Component.php

# Compile both PHPX and PHP files
./bin/compile <input_directory> [output_directory] --compile-php-files

# Lint mode - validate syntax without compiling
./bin/compile src/ --lint
./bin/compile src/ --check  # Alias for --lint
./bin/compile src/Component.phpx --lint  # Lint single file

# PHP linting - run php -l on compiled files
./bin/compile src/ build/ --php-lint
./bin/compile src/Component.phpx build/Component.php --php-lint

# Continue compilation even if some files fail
./bin/compile src/ build/ --continue-on-error

# Generate source maps for debugging
./bin/compile src/ build/ --source-maps
./bin/compile src/ build/ --debug  # Alias

# Generate AI-friendly source maps for LLM/agent consumption
./bin/compile src/ build/ --ai-source-maps

# Verbose mode for debugging
./bin/compile <input_directory> [output_directory] -v
./bin/compile <input_directory> [output_directory] -vv
./bin/compile <input_directory> [output_directory] -vvv

# JSON output for automation
./bin/compile <input_directory> [output_directory] -v --format=json

Command Line Options

Arguments

  • <input>: File or directory containing PHPX files to compile
  • [output]: Optional output file or directory (defaults to <input_directory>/compiled for directories, .php extension for files)

Options

  • --compile-php-files: Also compile pure PHP files alongside PHPX files
  • --lint, --check: Lint mode - validate syntax without compiling (useful for CI/CD)
  • --php-lint: Run PHP syntax check (php -l) on compiled files to ensure valid PHP output
  • --source-maps, --debug: Generate source maps (.map files) for debugging
  • --ai-source-maps: Generate AI-friendly source maps (.ai.map files) for LLM/agent consumption
  • --continue-on-error: Continue compiling other files even if some fail to parse
  • -v: Verbose mode - show basic progress (file written, errors)
  • -vv: More verbose - show detailed progress (parsing, transforming, generating)
  • -vvv: Debug mode - show all details including timing information
  • --format=<fmt>: Output format: cli (default, colored), plain (no colors), json (machine-readable)
  • -h, --help: Show help message

Verbose Mode Output

The compiler supports three verbosity levels for debugging and monitoring:

  • -v: Basic progress (files written, errors, summary)
  • -vv: Detailed progress (parsing, transforming, generating)
  • -vvv: Debug mode (individual JSX elements, timing info)

Example (-v):

[DISCOVERY] ✓ Found 5 file(s)
[WRITE]   ✓ Written (1.68 KB)
[COMPILE] ✓ Compiled 5 file(s)

For detailed verbose mode documentation, including JSON format, CI/CD integration, and performance tips, see Verbose Mode Guide.

PHP File Compilation

When using --compile-php-files, the compiler will:

  • Transform .phpx files into .php files with the JSX syntax converted to PHP
  • Also process .php files through the transformer (useful for mixed PHPX/PHP projects)
  • Preserve directory structure in the output

Practical Use Cases

Lint Mode for CI/CD

Validate PHPX syntax in your CI pipeline without compiling:

# GitHub Actions example
- name: Lint PHPX files
  run: vendor/bin/phpx-compiler src/ --lint --compile-php-files
# Pre-commit hook
vendor/bin/phpx-compiler src/ --lint && echo "✓ All PHPX files valid"

Single File Compilation

Quickly compile individual components during development:

# Compile specific component
./bin/compile src/components/Button.phpx build/components/Button.php

# Test single file syntax
./bin/compile src/components/Header.phpx --lint

Continue-on-Error for Large Projects

Compile as many files as possible in projects with temporary errors:

# Continue building even if some files have errors
./bin/compile src/ build/ --continue-on-error

# Combine with verbose mode to see which files failed
./bin/compile src/ build/ --continue-on-error -v

PHP Linting for Quality Assurance

Ensure compiled output is valid PHP syntax:

# Validate generated PHP files during compilation
./bin/compile src/ build/ --php-lint

# Combine with continue-on-error to check all files
./bin/compile src/ build/ --php-lint --continue-on-error -v

# Use in CI/CD to catch compiler bugs
./bin/compile src/ build/ --php-lint || exit 1

Source Maps for Debugging

Enable source maps to map compiled PHP code back to original PHPX source:

# Generate source maps alongside compiled files
./bin/compile src/ build/ --source-maps

# Use --debug as alias
./bin/compile src/ build/ --debug

What are Source Maps?

Source maps create a mapping between your compiled PHP code and the original PHPX source. When errors occur in compiled code, the source map allows debuggers and tools to show you the exact location in your original PHPX file.

Generated Files:

build/
├── Component.php           # Compiled PHP
├── Component.php.map       # Source Map v3 (JSON, for tools)
└── Component.php.map.txt   # Human-readable source map (for developers)

Source Map Comment (added to compiled PHP):

<?php
// ... compiled code ...
//# sourceMappingURL=Component.php.map

Source Map Format (Source Map v3):

{
  "version": 3,
  "file": "Component.php",
  "sourceRoot": "",
  "sources": ["Component.phpx"],
  "sourcesContent": ["<?php\nfunction Component() {...}"],
  "mappings": "AAAA;AACA;..."
}

Human-Readable Format (.map.txt):

Source Map (Human Readable Format)
===================================

Generated File: Component.php
Source File:    Component.phpx

Line Mappings:
--------------
Format: [Generated Line] → [Source Line]

  Line   2 → Line   3
  Line   3 → Line   4
  Line   4 → Line   8
  Line   5 → Line   9

Total mappings: 15

The .map.txt file provides an easy-to-read overview of how compiled PHP lines map back to the original PHPX source. Perfect for:

  • Quick manual debugging
  • Understanding compilation behavior
  • Teaching/learning the compilation process
  • Verifying source map accuracy

Why Source Maps Matter:

  1. AI/LLM Debugging - AI agents can map runtime errors back to the code they generated
  2. IDE Integration - IDEs can show errors at the correct PHPX line, not compiled PHP line
  3. Stack Traces - Error stack traces reference original PHPX files
  4. Xdebug Integration - Debug original PHPX code, not compiled output
  5. Team Workflow - Developers work with PHPX, not compiled PHP

Example Error Mapping:

Without source maps:

Parse error in Component.php on line 42

With source maps:

Parse error in Component.phpx on line 15
                         ^^^^ Original source file

For AI Agents:

Source maps enable accurate debugging feedback loops:

// 1. AI generates PHPX code
file_put_contents('Component.phpx', $aiGeneratedCode);

// 2. Compile with source maps
exec('./bin/compile Component.phpx build/ --source-maps');

// 3. Execute compiled PHP
try {
    include 'build/Component.php';
} catch (\Exception $e) {
    // 4. Map error back to original PHPX using source map
    $sourceMap = json_decode(file_get_contents('build/Component.php.map'), true);
    $originalLine = mapToSource($e->getLine(), $sourceMap);

    // 5. AI sees error at the line it wrote, not compiled line
    echo "Error in your generated code at line $originalLine";
}

Combining with JSON Errors:

For the ultimate AI-friendly debugging setup:

# Compile with source maps
./bin/compile src/ build/ --source-maps

# Lint with JSON errors
./bin/compile src/ --lint --format=json

This gives you:

  • Structured error data (JSON) for parsing
  • Source position tracking (source maps) for accurate line/column
  • Context awareness (error type, expected tokens, hints)

For even more AI-friendly debugging, see AI-Friendly Source Maps - enhanced source maps with semantic context, transformation provenance, checksums, confidence scores, and debugging hints specifically designed for LLM/agent consumption.

JSON Output for AI Agents & Tooling

For AI agents, LLMs, and automated tooling, use --format=json to get machine-readable structured error data:

# Get structured JSON error output
./bin/compile src/ --lint --format=json

JSON Output Structure:

{
  "success": false,
  "total": 1,
  "valid": 0,
  "invalid": 1,
  "errors": [
    {
      "type": "SyntaxError",
      "message": "Syntax error, unexpected '}', expecting '>' on line 4",
      "token": "}",
      "expected": [">"],
      "context": "PHPX",
      "file": "/tmp/test.phpx",
      "line": 4,
      "column": 3,
      "hint": "Missing closing tag '>' - check your JSX syntax"
    }
  ]
}

Key Fields for AI/LLM Processing:

  • type: Error category (SyntaxError, ParseError, Error)
  • token: The problematic token that caused the error
  • expected: Array of tokens the parser expected
  • context: Where the error occurred (PHP, PHPX, JSXElement, JSXAttribute, JSXExpression)
  • file, line, column: Exact error location for source map navigation
  • hint: Human-readable suggestion for fixing the error

Why This Matters for AI:

  1. Source Maps: The line and column fields map directly to your generated code, enabling accurate debugging
  2. Context Awareness: The context field tells you if the error is in JSX vs PHP code
  3. Expected Tokens: Use expected array to understand what the parser wanted
  4. Actionable Hints: The hint field provides fix suggestions your AI can apply
  5. Structured Data: Parse JSON instead of regex-parsing human-readable output

AI Agent Integration Example:

<?php
// Parse JSON output in your AI agent
$output = shell_exec('./bin/compile src/ --lint --format=json 2>&1');
$result = json_decode($output, true);

if (!$result['success']) {
    foreach ($result['errors'] as $error) {
        // Extract exact location
        $file = $error['file'];
        $line = $error['line'];
        $column = $error['column'];

        // Understand context
        $isJSX = $error['context'] !== 'PHP';

        // Get fix suggestion
        $hint = $error['hint'];

        // Use expected tokens to generate fix
        $expectedTokens = $error['expected'];

        // Your AI can now:
        // 1. Navigate to exact location using source maps
        // 2. Understand JSX vs PHP context
        // 3. Apply hint-based fixes
        // 4. Generate corrections based on expected tokens
    }
}

CI/CD Integration:

# GitHub Actions example
- name: Validate PHPX with JSON output
  run: |
    RESULT=$(./bin/compile src/ --lint --format=json)
    echo "$RESULT" | jq '.errors[] | "Error in \(.file):\(.line) - \(.hint)"'

Benefits for AI/LLM Tools:

  • Reliable Parsing: JSON structure never changes, unlike human-readable output
  • Source Map Integration: Line/column data maps to your generated code
  • Context-Aware Fixes: Know if you're fixing JSX or PHP syntax
  • Batch Processing: Process multiple errors programmatically
  • CI/CD Friendly: Easy integration with automated pipelines

Error Messages

PHPX provides Rust-style error messages with source context and helpful hints:

error: Syntax error, unexpected '{', expecting ')'
 --> example.php:3:22

  |
1 | <?php
2 |
3 | function hello($name {
  |                      ^ unexpected '{'
4 |     echo "Hello, $name!";
5 | }
  |

  = hint: Did you forget to close the parenthesis?

Features:

  • Source context: Shows 2 lines before and after the error
  • Exact location: Points to the error with a caret (^)
  • Helpful hints: Suggests fixes for common mistakes
  • Color-coded: Terminal output uses colors for better readability
  • File location: Shows file:line:column format

Architecture

PHPX consists of two main parts:

  1. Parser: Converts PHPX syntax into PHP components
  2. Runtime: Handles component rendering and state management

Frontend (WebAssembly)

When targeting the frontend, PHPX components are compiled to WebAssembly, allowing them to run efficiently in the browser while maintaining the same syntax and component structure.

Server-Side Rendering

For server-side rendering, PHPX components are rendered directly on the server, providing fast initial page loads and SEO benefits.

Event System

The PHPX compiler includes a powerful event system that allows you to hook into the compilation process. This is useful for building custom tooling, monitoring compilation, or implementing custom logging.

Quick Example

<?php

use Syntaxx\PHPX\Events\EventManager;
use Syntaxx\PHPX\Events\EventNames;

// Register a custom listener
EventManager::on(EventNames::FILE_WRITTEN, function($eventName, $data) {
    echo "Compiled: {$data['file']}{$data['output_path']}\n";
});

// Compile normally
$files = new Files($inputDir);
$compiler = new Compiler();
$compiler->compile($files, $outputDir);

Available Events

The compiler dispatches events for every compilation phase:

  • Discovery: discovery.started, discovery.file_found, discovery.completed
  • Compilation: compilation.started, compilation.completed, compilation.error
  • File Processing: file.parsing_started, file.parsed, file.parse_error
  • Transformation: transformation.started, transformation.jsx_element, transformation.completed
  • Generation: file.generating, file.generated, file.writing, file.written

Documentation

For detailed documentation, examples, and best practices, see:

Documentation

For comprehensive guides and advanced topics, see the docs/ directory:

📚 Core Guides

  • PHPX Guide - 🚀 Start here! Complete introduction to PHPX concepts and development
  • Syntax Reference - Complete technical reference for PHPX syntax
  • Examples - Real-world component examples and patterns

🔧 Compiler Features

📖 Full Index

Roadmap

Check out our Roadmap to see what's coming next!

  • 🚀 Short-term goals: Incremental compilation, source maps, IDE integration
  • 🔮 Long-term vision: HMR, SSG, server components, framework adapters
  • 📅 Release timeline and priorities

We welcome feedback and contributions!

Requirements

  • PHP 8.1 or higher
  • Composer

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages