Pure-Kotlin PHP 8.5 engine, two-stage multistate optimizer, jitdynamo-backed multi-target compiler (O3 default), extensible optimization & C ABI v2 framework, and SAPI suite (com.nexustools.kphp).
| Module | Targets | Responsibility |
|---|---|---|
:parser |
Portable (JVM, Android, iOS, Desktop Native) | Pure-Kotlin PhpLexer + PhpParser + AST (PhpProgram, PHP 7.4–8.5 grammar, hooks, enums, traits, attributes, alternate syntax, |>), pre-canonicalized lowercase symbol keys (ns$$sub$$name), accurate spans |
:optimizer |
Portable | Stage 1 PhpIntraFileOptimizer + Stage 2 PhpWholeProgramOptimizer -> PhpLinkedProgram + PhpOptimizationReport, PhpBuiltinOptFuns CTFE (PhpCompileTimeCrypto, PhpCompileTimePack, PhpCompileTimeValue), PhpStandaloneNoopAnalyzer |
:extension-abi |
Portable | KphpExtensionProvider, KphpOptimizingExtension, KphpExtensionRegistrar, KphpOptimizationRegistrar / KphpDefaultOptimizationRegistrar, KphpAstOptimizationPass, KphpLowercaseContractValidator, KphpExtensionDescriptor, KphpExtensionLoader (LoadLibrary/dlopen/ServiceLoader/URLClassLoader), C ABI v2 kphp_extension_abi.h + KphpNativeHostAbiBridge |
:runtime |
Portable + knode |
PhpValue (DynamoForeignValue; PhpInt -256..4096 cache; PhpString fromPreencodedBytes; dual-mode packed/map COW PhpArray; PhpObject: DynamoShapeObject), PhpIdentifiers, PhpOverlayMap, PhpFrameMetadata + PhpTraceSnapshot, PhpReference, PhpContext (AutoCloseable), PhpEngine (AutoCloseable, single-insertion constants), trait composition, reflection, 15 stdlib modules |
:compiler |
Portable + jitdynamo (:jvm on jvmMain, :native on desktopNativeMain) |
PhpScopeUsageAnalyzer, PhpToDynamoIrLowerer (direct PHP->JVM/Kotlin classes, flattened traits, 0xC1 instanceof), KphpDynamoRuntimeHooks, PhpSharedNoopUnit, PhpPerFileIrCache, PhpWholeProgramCache, PhpDynamicUnitCache, KphpClassLoaderHandle (AutoCloseable), KphpCompiler (O3 default, JVM bytecode, Native JIT, 1:1 Kotlin/Java wrappers, single-binary builder) |
:extensions:<name> + :extensions |
Portable + knode |
12 modular extension subprojects (curl, gd, hash [HashIrOptimizationPass], json [JsonIrOptimizationPass], mbstring, mysqli, openssl, pcre [PcreIrOptimizationPass], pdo, session, spl, xml) emitting kphp-ext-<name>.dll/.so/.dylib on desktop native and embedding in single JAR/APK/framework elsewhere |
:sapi |
JVM + Desktop Native | KphpCli (php), KphpFastCgiServer (php-fpm), KphpHttpServer, KphpCompileCli (kphp-compile) |
:gradle-plugin |
Gradle JVM (com.nexustools.kphp) |
KphpGradlePlugin, KphpComposerFrontendProvider (JitDynamoLibraryFrontendProvider), KphpComposerManifest, KphpNativeSharedLibraryCatalog, KphpBuildNativeSharedLibsTask, KphpTranspileTask |
:tests |
JVM + Desktop Native | KJest unit, stdlib, modular & consumer .dll/JVM extension ABI, optimizer, class-wrapper, SAPI, and unmodified WordPress 8-step E2E suites |
- Mandatory Lowercase Canonical Keys (
PhpIdentifiers&KphpLowercaseContractValidator):- All function, class, interface, trait, enum, method, extension, INI default, and optimization registrar keys are pre-lowercased at parse/registration time using
$$namespace separators (ns$$sub$$name, never leading\).KphpLowercaseContractValidatorvalidates registrar and extension compliance across all 12 built-in extensions and consumer plugins. - PHP 8 Exact Case-Sensitive Constants:
PhpIdentifiers.normalizeConstantNamelowercases ONLY the namespace prefix (ns$$) while preserving exact casing of the leaf constant name (ns$$CONST_NAMEorCONST_NAME), with no legacy case-insensitivedefine()flag.PhpEngine.registerConstantperforms single-insertion registration intoconstants,defines, andconstantOriginalNames.
- All function, class, interface, trait, enum, method, extension, INI default, and optimization registrar keys are pre-lowercased at parse/registration time using
- Zero-Copy & Low-Allocation Data Structures (
PhpValue,PhpContext,PhpEngine):- Lazy Zero-Alloc Call Frames (
PhpFrameMetadata&PhpTraceSnapshot):PhpContextpushes onto parallel primitive arrays (frameMeta,frameLines,frameArgs,frameFiles,frameReceivers, etc.) with zeroPhpScopeor string allocation per call;PhpTraceSnapshotmaterializesOriginalNs\OriginalClass::originalMethodframes lazily only whendebug_backtrace(),getTrace(), orgetTraceAsString()is called. PhpOverlayMap: Zero-copy per-request mutable overlay over shared read-onlyPhpEnginemaps (constants,constantDefines,constantOriginalNames,functions,classes,interfaces,traits,enums,internalVars,env), allocating local storage/tombstones lazily only on request-local writes.PhpIntCache (-256..4096): Pre-allocated singletonPhpIntinstances (CACHE_MIN = -256LtoCACHE_MAX = 4096L) viaPhpInt.of(...).- Dual-Mode
PhpArray: Starts in packed mode (Array<PhpValue?>for0..N-1lists with O(1) append/cursor/pop and zero-copyforeach), automatically promoting to map mode (LinkedHashMap<Key, Entry>) on sparse integer keys, string keys, or out-of-order removals; supports shallow COWshare()andfromTemplate(). PhpStringPreencoded Bytes:PhpString.fromPreencodedBytes(bytes, utf8String, precomputeMetadata)wraps immutable module-pool UTF-8/binary buffers without defensive copying and precomputescachedHashCodeand numeric-prefix/strict-numeric flags at load time.
- Lazy Zero-Alloc Call Frames (
- Stage 1 (
PhpIntraFileOptimizer) &PhpBuiltinOptFunsCTFE:- Collects userland declarations (
PhpDeclaredSymbolCollector) to prevent shadowing, then bottom-up folds magic constants (__FILE__,__DIR__, etc.),PhpEngineCompileConfigconstants, synchronousPhpAstOptFunevaluators (PhpBuiltinOptFunscovering introspection, math, strings, arrays, base64/hex, JSON/crypto/pack helpers, plus extension-registeredwithAstOptimizerhooks), literal offsets, unary/binary/short-circuit/ternary/match, and prunes deadif/switch/while(false).
- Collects userland declarations (
- Stage 2 (
PhpWholeProgramOptimizer) & Standalone No-Op Dismissal:- Evaluates branch conditions BEFORE traversing bodies so dead
require/includetargets are never parsed or linked; propagatesdefine()/constacross files with sound branch-merge joins; elides duplicate*_onceincludes; enforcesSTRICTvsHYBRID_BOUNDARYpolicies; reduces side-effect-free standalone accesses viaPhpStandaloneNoopAnalyzertoPhpSharedNoopUnit.
- Evaluates branch conditions BEFORE traversing bodies so dead
- Extensible Optimization SPI (
KphpOptimizationRegistrar&KphpDefaultOptimizationRegistrar):- Extensions implement
KphpOptimizingExtensionor register viaKphpOptimizationRegistrar(KphpDefaultOptimizationRegistrar) to contribute:KphpAstOptimizationPass: Pluggable PHP AST passes ordered by(priority, id).DynamoIrOptimizationPass+DynamoPureIntrinsicEvaluator: CustomjitdynamoIR passes and CTFE evaluators wired intoKphpCompiler'sO3DynamoOptimizationPipeline.- Function Effects & Artifact Materializers:
DynamoFunctionEffectsandKphpArtifactMaterializerforLOAD_PRECOMPILED_OBJECT.
- Built-In Extension IR Passes:
PcreIrOptimizationPass(:extensions:pcre,POST_IPSCCP): Folds constantpreg_quote,preg_match,preg_match_all,preg_replace/preg_filter,preg_split, and hoistskphp.pcre.patternLOAD_PRECOMPILED_OBJECTdescriptors to__kphp_pcre_*_precompiled.JsonIrOptimizationPass(:extensions:json,POST_IPSCCP): Folds constantjson_encode, scalarjson_decode,json_validate, and hoistskphp.json.plandescriptors to__kphp_json_*_planned.HashIrOptimizationPass(:extensions:hash,POST_IPSCCP): Folds constantmd5,sha1,crc32,hash,hash_hmac, and hoists pre-validatedkphp.hash.algodescriptors to__kphp_hash*_planned.
- Extensions implement
- Consumer Extension ABI (
:extension-abi, C ABI v2kphp_extension_abi.h):- Kotlin/JVM Consumer Extensions: Implement
KphpExtensionProvider(packaged in a JAR withMETA-INF/services/com.nexustools.kphp.abi.KphpExtensionProvideror loaded viaKphpExtensionLoader.loadJvmPlugin(...)). - Native
.dll/.so/.dylibConsumer Extensions (KPHP_EXTENSION_ABI_VERSION 2): Exportkphp_extension_init(const KphpHostAbiTable* abi)/kphp_extension_shutdown(void)(orkphp_ext_<name>_init), usingregister_function_with_effects(..., effect_flags)(KPHP_FN_PURE,KPHP_FN_NO_THROW,KPHP_FN_IDEMPOTENT,KPHP_FN_READ_ONLY,KPHP_FN_NO_ALLOC,KPHP_FN_LEAF) andregister_optimization_descriptor(...)alongside v1 constant/function/INI callbacks.
- Kotlin/JVM Consumer Extensions: Implement
- Direct PHP -> JVM/Kotlin Class Lowering (
PhpToDynamoIrLowerer):- Lowers PHP classes, interfaces, enums, and flattened traits directly into
DynamoClassDecl/DynamoInterfaceDecl/DynamoEnumDeclunits for JVM bytecode, Native JIT, and 1:1 Kotlin/Java wrappers. - Emits
DYN_INSTANCEOFtargeting resolved JVM/Kotlin class FQNs (lowering to native JVM0xC1 instanceofand Kotlinischecks) andKphpDynamoRuntimeHooksbridges for dynamic reflection/builtins.
- Lowers PHP classes, interfaces, enums, and flattened traits directly into
- Scoped Lifecycle & Reclamation (
PhpEngine,PhpContext,KphpClassLoaderHandle):PhpEngine,PhpContext, andKphpClassLoaderHandleimplementAutoCloseable.- On JVM,
KphpClassLoaderHandlemanagesJvmDynamoEngine(O3default) andJvmCompiledModulehandles backed by unloadableDynamoClassLoaders. On Desktop Native,KphpClassLoaderHandlemanagesNativeJitEngine(O3default) andNativeCompiledModuleW^X executable memory. CallingevictModule,invalidateFile, orclose()deterministically unloads classes and frees native W^X pages.
- Two-Layer Incremental Caching (
PhpPerFileIrCache&PhpWholeProgramCache):PhpPerFileIrCache(Layer 1): Keyed by canonical path and verified against(canonicalPath, mtimeMs, byteLength, contentSha256)+ Stage-1 signature; unchanged disk files validate via metadatastatwithout re-reading or re-parsing.PhpWholeProgramCache(Layer 2): Keyed by(entryFile, configSignature)tracking transitiveincludedFilesfingerprints,missingIncludeProbes, andnoopUnitPaths. On any transitiveinclude/requiremodification orPhpEngine.invalidateFiles(...)notification, supersededPhpWholeProgramCacheEntryinstances are evicted and closed (releasing theirDynamoClassLoader/NativeCompiledModule), while only modified files are evicted fromPhpPerFileIrCache.
- Composer Gradle Frontend (
KphpComposerFrontendProvider):- Implements
JitDynamoLibraryFrontendProvider(id = "composer",manifestFileNames = {"composer.json"}) in:gradle-plugin, resolving PSR-4 namespaces and autoloaded PHP files throughKphpCompilerStage 2 atDynamoOptimizationLevel.O3into 1:1 Kotlin/JavaDynamoModulepackages.
- Implements