Skip to content

Latest commit

 

History

History
68 lines (56 loc) · 11.1 KB

ARCHITECTURE.md

File metadata and controls

68 lines (56 loc) · 11.1 KB

kphp — System Architecture (ARCHITECTURE.md)

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).

1. Module & Target Matrix

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

2. Canonical Symbol Contract & High-Performance Runtime (:runtime)

  1. 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 \). KphpLowercaseContractValidator validates registrar and extension compliance across all 12 built-in extensions and consumer plugins.
    • PHP 8 Exact Case-Sensitive Constants: PhpIdentifiers.normalizeConstantName lowercases ONLY the namespace prefix (ns$$) while preserving exact casing of the leaf constant name (ns$$CONST_NAME or CONST_NAME), with no legacy case-insensitive define() flag. PhpEngine.registerConstant performs single-insertion registration into constants, defines, and constantOriginalNames.
  2. Zero-Copy & Low-Allocation Data Structures (PhpValue, PhpContext, PhpEngine):
    • Lazy Zero-Alloc Call Frames (PhpFrameMetadata & PhpTraceSnapshot): PhpContext pushes onto parallel primitive arrays (frameMeta, frameLines, frameArgs, frameFiles, frameReceivers, etc.) with zero PhpScope or string allocation per call; PhpTraceSnapshot materializes OriginalNs\OriginalClass::originalMethod frames lazily only when debug_backtrace(), getTrace(), or getTraceAsString() is called.
    • PhpOverlayMap: Zero-copy per-request mutable overlay over shared read-only PhpEngine maps (constants, constantDefines, constantOriginalNames, functions, classes, interfaces, traits, enums, internalVars, env), allocating local storage/tombstones lazily only on request-local writes.
    • PhpInt Cache (-256..4096): Pre-allocated singleton PhpInt instances (CACHE_MIN = -256L to CACHE_MAX = 4096L) via PhpInt.of(...).
    • Dual-Mode PhpArray: Starts in packed mode (Array<PhpValue?> for 0..N-1 lists with O(1) append/cursor/pop and zero-copy foreach), automatically promoting to map mode (LinkedHashMap<Key, Entry>) on sparse integer keys, string keys, or out-of-order removals; supports shallow COW share() and fromTemplate().
    • PhpString Preencoded Bytes: PhpString.fromPreencodedBytes(bytes, utf8String, precomputeMetadata) wraps immutable module-pool UTF-8/binary buffers without defensive copying and precomputes cachedHashCode and numeric-prefix/strict-numeric flags at load time.

3. Two-Stage Optimizer, Extensible Passes, & C ABI v2

  1. Stage 1 (PhpIntraFileOptimizer) & PhpBuiltinOptFuns CTFE:
    • Collects userland declarations (PhpDeclaredSymbolCollector) to prevent shadowing, then bottom-up folds magic constants (__FILE__, __DIR__, etc.), PhpEngineCompileConfig constants, synchronous PhpAstOptFun evaluators (PhpBuiltinOptFuns covering introspection, math, strings, arrays, base64/hex, JSON/crypto/pack helpers, plus extension-registered withAstOptimizer hooks), literal offsets, unary/binary/short-circuit/ternary/match, and prunes dead if/switch/while(false).
  2. Stage 2 (PhpWholeProgramOptimizer) & Standalone No-Op Dismissal:
    • Evaluates branch conditions BEFORE traversing bodies so dead require/include targets are never parsed or linked; propagates define()/const across files with sound branch-merge joins; elides duplicate *_once includes; enforces STRICT vs HYBRID_BOUNDARY policies; reduces side-effect-free standalone accesses via PhpStandaloneNoopAnalyzer to PhpSharedNoopUnit.
  3. Extensible Optimization SPI (KphpOptimizationRegistrar & KphpDefaultOptimizationRegistrar):
    • Extensions implement KphpOptimizingExtension or register via KphpOptimizationRegistrar (KphpDefaultOptimizationRegistrar) to contribute:
      • KphpAstOptimizationPass: Pluggable PHP AST passes ordered by (priority, id).
      • DynamoIrOptimizationPass + DynamoPureIntrinsicEvaluator: Custom jitdynamo IR passes and CTFE evaluators wired into KphpCompiler's O3 DynamoOptimizationPipeline.
      • Function Effects & Artifact Materializers: DynamoFunctionEffects and KphpArtifactMaterializer for LOAD_PRECOMPILED_OBJECT.
    • Built-In Extension IR Passes:
      • PcreIrOptimizationPass (:extensions:pcre, POST_IPSCCP): Folds constant preg_quote, preg_match, preg_match_all, preg_replace/preg_filter, preg_split, and hoists kphp.pcre.pattern LOAD_PRECOMPILED_OBJECT descriptors to __kphp_pcre_*_precompiled.
      • JsonIrOptimizationPass (:extensions:json, POST_IPSCCP): Folds constant json_encode, scalar json_decode, json_validate, and hoists kphp.json.plan descriptors to __kphp_json_*_planned.
      • HashIrOptimizationPass (:extensions:hash, POST_IPSCCP): Folds constant md5, sha1, crc32, hash, hash_hmac, and hoists pre-validated kphp.hash.algo descriptors to __kphp_hash*_planned.
  4. Consumer Extension ABI (:extension-abi, C ABI v2 kphp_extension_abi.h):
    • Kotlin/JVM Consumer Extensions: Implement KphpExtensionProvider (packaged in a JAR with META-INF/services/com.nexustools.kphp.abi.KphpExtensionProvider or loaded via KphpExtensionLoader.loadJvmPlugin(...)).
    • Native .dll/.so/.dylib Consumer Extensions (KPHP_EXTENSION_ABI_VERSION 2): Export kphp_extension_init(const KphpHostAbiTable* abi) / kphp_extension_shutdown(void) (or kphp_ext_<name>_init), using register_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) and register_optimization_descriptor(...) alongside v1 constant/function/INI callbacks.

4. Direct Class Lowering, Scopes, Caching, & Composer Frontend (:compiler, :gradle-plugin)

  1. Direct PHP -> JVM/Kotlin Class Lowering (PhpToDynamoIrLowerer):
    • Lowers PHP classes, interfaces, enums, and flattened traits directly into DynamoClassDecl / DynamoInterfaceDecl / DynamoEnumDecl units for JVM bytecode, Native JIT, and 1:1 Kotlin/Java wrappers.
    • Emits DYN_INSTANCEOF targeting resolved JVM/Kotlin class FQNs (lowering to native JVM 0xC1 instanceof and Kotlin is checks) and KphpDynamoRuntimeHooks bridges for dynamic reflection/builtins.
  2. Scoped Lifecycle & Reclamation (PhpEngine, PhpContext, KphpClassLoaderHandle):
    • PhpEngine, PhpContext, and KphpClassLoaderHandle implement AutoCloseable.
    • On JVM, KphpClassLoaderHandle manages JvmDynamoEngine (O3 default) and JvmCompiledModule handles backed by unloadable DynamoClassLoaders. On Desktop Native, KphpClassLoaderHandle manages NativeJitEngine (O3 default) and NativeCompiledModule W^X executable memory. Calling evictModule, invalidateFile, or close() deterministically unloads classes and frees native W^X pages.
  3. 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 metadata stat without re-reading or re-parsing.
    • PhpWholeProgramCache (Layer 2): Keyed by (entryFile, configSignature) tracking transitive includedFiles fingerprints, missingIncludeProbes, and noopUnitPaths. On any transitive include/require modification or PhpEngine.invalidateFiles(...) notification, superseded PhpWholeProgramCacheEntry instances are evicted and closed (releasing their DynamoClassLoader / NativeCompiledModule), while only modified files are evicted from PhpPerFileIrCache.
  4. Composer Gradle Frontend (KphpComposerFrontendProvider):
    • Implements JitDynamoLibraryFrontendProvider (id = "composer", manifestFileNames = {"composer.json"}) in :gradle-plugin, resolving PSR-4 namespaces and autoloaded PHP files through KphpCompiler Stage 2 at DynamoOptimizationLevel.O3 into 1:1 Kotlin/Java DynamoModule packages.