ircmaxell/php-c-parser
Parse C source files into an AST in PHP (PHP 8.4+), including preprocessing resolution. Use a Context to set #define values (ints, strings, identifiers) before parsing. Great for analysis tools, code inspection, and experimentation.
clang). Ideal for:
#define, #include, and conditional compilation is a critical advantage over shelling out to clang.Reflection APIs (if transforming to PHP constructs).Context class enables dynamic preprocessor directive injection, useful for:
#define).clang -ast-dump for your codebase.clang. Profile with:
clang -cc1 -ast-dump example implies potential reliance on Clang’s output. Clarify:
clang for diagnostics.php-cpp, libclang bindings) that could complement or replace this?#define injection (e.g., for feature flags)?clang: More mature but adds subprocess overhead.libclang via pyclang (if PHP isn’t a hard requirement).composer require ircmaxell/php-c-parser
phpunit or pest).ext-ffi or rubix/ml-ffi for generated bindings.stdio.h).#define, #include).clang -ast-dump for accuracy.clang-based solution for critical paths.__attribute__((packed))), Microsoft extensions.#define FOO(x) BAR(x) where BAR is also a macro.#ifdef blocks with complex logic.#pragma once and #ifndef/#define/#endif are handled.ext-json), verify:
ZEND_FUNCTION macros).clang for comparison).Dockerfile snippet:
FROM php:8.4-cli
RUN apt-get update && apt-get install -y clang
namespace App\Services;
use PHPCParser\CParser;
use PHPCParser\Context;
class CParserService {
public function parse(string $filePath, ?Context $context = null): object {
$parser = new CParser();
return $parser->parse($filePath, $context);
}
public function parseWithDefaults(string $filePath): object {
$context = new Context();
$context->defineInt('DEBUG', 1); // Example: Inject a define
return $this->parse($filePath, $context);
}
}
// app/Providers/AppServiceProvider.php
public function register(): void {
$this->app->singleton(CParserService::class);
}
class CFunctionExtractor {
public function extractFunctions(object $ast): array {
// Traverse AST to find function declarations
// Return array of function signatures
}
}
$ast = $parserService->parse('path/to/header.h');
$functions = (new CFunctionExtractor())->extractFunctions($ast);
$ffiBindings = $this->generateFFIBindings($functions);
try {
$ast = $parserService->parse($filePath);
} catch (\PHPCParser\Exception $e) {
throw new \RuntimeException(
"Failed to parse C file: {$e->getMessage()}",
0,
$e
);
}
\Log::info('Parsed C file', [
'file' => $filePath,
'ast_size' => $this->countASTNodes
How can I help you explore Laravel packages today?