ETS2Panda Driver Knowledge Base
Document Version: v1.0 Last Updated: 2026-05-28 Scope:
ets_frontendfrontend compiler knowledge base entry Before modifying, please read:AGENTS.md, the corresponding compiler routeAGENTS.md, and the nearest directory-levelAGENTS.md
Overview
build_system is the core module of the driver layer. It translates the BuildConfig passed in by hvigor or the CLI into compilation tasks for ArkTS 1.2 source files, drives ets2panda to complete the full build pipeline from .ets/.ts sources to bytecode (.abc), and supports declgen declaration file generation, plugin transforms, and obfuscation config generation. dependency_analyzer is a C++ dependency analysis sub-module in the driver layer that analyzes import dependencies between ArkTS files and outputs a file list sorted by dependency order.
Directory Structure and Code Map
- Upstream: hvigor (passes
BuildConfigobject via thebuild()API) / CLI (passes a JSON file vianode entry.js build_config.json) - Downstream: ets2panda compiler (invoked via koala-wrapper / libarkts API), ark_link linker, arkguard obfuscation tool
Directory Explanation
build_system/src/— Core TypeScript source codeentry.ts— Exposes thebuild()entry function; dispatches toBuildModeorBuildFrameworkModetypes.ts— Core type definitions (BuildConfig,ES2PANDA_MODE,WorkerMessageType,BUILD_MODE,OHOS_MODULE_TYPE, etc.)logger.ts— Logger singleton (Logger); supports hvigor console logger integrationpre_define.ts— Predefined constants (paths, file names, SDK directory structure, etc.)build/— Compilation mode implementations:BaseMode(core logic),BuildMode(mode dispatch),BuildFrameworkMode(framework mode), worker processes/threads (compile_process_worker.ts,compile_thread_worker.ts,declgen_process_worker.ts),generate_arktsconfig.ts(generatesarktsconfig.json)init/— Config initialization:process_build_config.ts(initBuildConfig(), path normalization, cache comparison),init_koala_modules.ts(loads koala-wrapper)util/— Utilities:error.ts(ErrorCodeenum andDriverError),ets2panda.ts(Ets2pandasingleton, wraps parse/check/declgen/emit calls),graph.ts(Graph/GraphNode, DAG dependency graph),TaskManager.ts(multi-process/multi-thread task scheduling),statsRecorder.ts(performance statistics),utils.ts(general utilities),worker_exit_handler.ts(worker exit handling)plugins/— Plugin system:PluginDriver(singleton, manages loading and execution hooks for AST transform plugins),KitImportTransformerobfuscation/— Obfuscation config processing
build_system/test/— Test directory:ut/(unit tests),e2e/(end-to-end tests),e2e_obfuscation/(obfuscation E2E tests), demo projects (demo_hap/,demo_mix_hap/, etc.)build_system/docs/— Config documentation:build-config.en.md(BuildConfigfield descriptions),target-build.en.md(multi-target sourceRoots build documentation)dependency_analyzer/— C++ file dependency analyzer:dep_analyzer.h/dep_analyzer.cpp(core implementation, analyzes import dependencies, outputs file path list sorted by import priority),main.cpp(CLI entry point)docs/— Driver layer architecture documentation
Key Files and Responsibilities
src/entry.ts— Exposes thebuild(BuildConfig)entry point: handles backward-compatibility adaptation, dispatches to the appropriate mode based onframeworkModeandenableDeclgenEts2Tssrc/types.ts— Defines all core types:BuildConfig(containing sub-structuresBuildBaseConfig,DeclgenConfig,ModuleConfig,PathConfig,FrameworkConfig, etc.),ES2PANDA_MODE(RUN_PARALLEL/RUN_CONCURRENT/RUN_SIMULTANEOUS/RUN),WorkerMessageType,OHOS_MODULE_TYPE(hap/har/feature/shared/entry)src/init/process_build_config.ts—initBuildConfig(): fully normalizes the input config (SDK path derivation, dependency module Map reconstruction, config cache comparison and write, platform-specific config, environment initialization, alias config, interop SDK info, obfuscation config initialization)src/build/base_mode.ts—BaseModeabstract class: implements core build logic including collecting module info (collectModuleInfos), generating arktsconfigs (generateArktsconfigs), processing entry files, running parallel/concurrent/simultaneous/sequential modes, triggering declgen v1 and v2, running the linker (ark_link), and managing declFileMapsrc/build/build_mode.ts—BuildMode: dispatches torunParallel/runConcurrent/runSimultaneous/runbased onES2PANDA_MODE, and records statisticssrc/build/generate_arktsconfig.ts—ArkTSConfigGenerator: generatesarktsconfig.jsonfor each module, handling paths (including sourceRoots multi-target priority mapping) and dependencies (two-phase transformed/remaining parsing of interop dependencies)src/util/ets2panda.ts—Ets2pandasingleton: wraps the full ets2panda compiler API call chain (parse → plugin(parse) → declgen → check → plugin(check) → emit)src/util/error.ts—ErrorCodeenum (11410001–11410039) andDriverErrorclass, defining all errors reportable by the build systemsrc/util/graph.ts—Graph/GraphNode: DAG directed graph for representing module dependency relationships and topological schedulingsrc/util/TaskManager.ts—TaskManager: multi-process/multi-thread task scheduling, manages worker pool and task queuesrc/util/statsRecorder.ts—StatisticsRecorder: event-level performance timing, outputsbs_record_perf.csvreportsrc/plugins/plugins_driver.ts—PluginDriversingleton: manages loading of external AST transform plugins (BUILDSYSTEM_LOAD_PLUGIN_FAIL11410008) and hook executiondependency_analyzer/dep_analyzer.h—DepAnalyzerclass: analyzesdirectDependencies_,directDependants_,outputMatching_, and outputs the file path list
Responsibility Boundaries
- Responsible for:
BuildConfigparsing and normalization, module info collection,arktsconfig.jsongeneration (including paths/dependencies/sourceRoots), multi-mode parallel/concurrent/simultaneous/sequential compilation scheduling, triggering declgen v1/v2 and managingdeclFileMap, bytecode linking (ark_link), obfuscation config generation (arkguard), plugin driving (PluginDriver), build cache management, performance statistics - Not responsible for: ets2panda static semantics (type checker core), compiler IR and lowering logic, bytecode format itself, runtime behavior
Core Data Flow / Control Flow
hvigor / CLI
→ build(BuildConfig) [entry.ts]
→ initBuildConfig() [process_build_config.ts]
(path normalization, cache comparison, obfuscation config initialization)
→ BuildMode / BuildFrameworkMode [build_mode.ts / build_framework_mode.ts]
→ collectModuleInfos() [base_mode.ts]
→ generateArktsconfigs() [generate_arktsconfig.ts]
(paths, sourceRoots priority mapping, interop dependencies)
→ DependencyAnalyzer [dependency_analyzer/dep_analyzer]
(inter-file import dependency analysis, build compilation order graph)
→ TaskManager / workers [TaskManager.ts, *_worker.ts]
→ Ets2panda.compile() [ets2panda.ts → libarkts]
(parse → plugin → declgen → check → plugin → emit)
→ Ets2panda.declgen() [ets2panda.ts → libarkts]
→ ark_link (link multi-module .abc files)
→ PluginDriver hooks [plugins_driver.ts]
→ StatisticsRecorder.write() [statsRecorder.ts]
Knowledge Routing
BuildConfigfield meanings and required fields →docs/build-config.en.md- sourceRoots multi-target build and paths generation algorithm →
docs/target-build.en.md - Inter-file import dependency analysis →
dependency_analyzer/README.md - Compilation errors (type/semantic errors) → checker Knowledge Base
- declgen declaration output issues →
DeclGen_ETS2TS_Knowledge_Base.md - Plugin-related issues →
src/plugins/ - ErrorCode quick reference →
src/util/error.ts - Performance analysis toggle and reports →
src/util/statsRecorder.tsand README.md
Expert Tips
- First verify whether input
BuildConfigfields are incorrect before investigating compiler core issues; setenableDebugOutput: trueto print the full config - The
isBuildConfigModifiedflag affects incremental cache hits; if behavior is unexpected after a config change, check whetherproject_build_config.jsonundercachePathhas been correctly updated ES2PANDA_MODEchoice directly impacts compilation performance:RUN_PARALLEL(multi-process, suitable for full builds of large projects),RUN_CONCURRENT(multi-thread + AST cache, suitable for HAR incremental compilation),RUN_SIMULTANEOUS(special simultaneous mode, used for BuildFrameworkMode),RUN(sequential, suitable for debugging)- During local development, environment variables
USE_KOALA_LIBARKTS,USE_KOALA_UI_PLUGIN,USE_KOALA_MEMO_PLUGINcontrol the source of koala plugins; before testing, correctly configurekoalaWrapperPathininitKoalaWrapper - declgen v1 is triggered via
enableDeclgenEts2Ts: true+buildMode.generateDeclarationV1Parallel(); v2 is triggered via thedeclgenV2OutPathconfig
Anti-Patterns
- Adding semantic special-casing inside the driver (type or semantic errors should be fixed at the checker layer, not worked around in the driver)
- Bypassing
initBuildConfig()and using rawprojectConfigdirectly (paths are not normalized, cache comparison logic breaks) - Modifying compilation parameters to work around obfuscation config errors instead of fixing the obfuscation config file
- Calling non-thread-safe singletons from workers without protection
Debugging and Verification
- Unit tests:
npm run ut_test(test/ut/, Jest-based) - E2E tests:
TEST=${test_script_name} npm run build_system_Etest(test/e2e/) - Full local test steps: see
README.md(mock SDK → mock koala-wrapper →npm run build→npm run demo_hap:gen_abc) - Dependency graph visualization: set
dumpDependencyGraph: true, then render the.dotfiles generated incachePathwith Graphviz - dependency_analyzer tests:
es2panda_depanalyz_tests
Debugging Methods
- Enable
enableDebugOutput: trueto print the fullBuildConfigand per-phase event logs - Inspect
project_build_config.jsonundercachePathto confirm whether the config has been correctly persisted - Use the
ErrorCodecarried byDriverError(seesrc/util/error.ts) to quickly pinpoint the failing phase - Performance analysis: change
recordTypetoON_TYPE, or setdumpPerf: truein the build config, to outputbs_record_perf.csvand the--dump-perf-metricsflag dumpDependencyGraph: truegenerates.dotfiles for visualizing module dependency relationships
Common Issues
BUILDSYSTEM_SDK_NOT_EXIST_FAIL(11410010):pandaSdkPath/buildSdkPathmisconfigured or SDK not installedBUILDSYSTEM_LOAD_PLUGIN_FAIL(11410008): koala-wrapper path is wrong or koala plugin is not properly configuredBUILDSYSTEM_DEPENDENT_MODULE_INFO_NOT_CORRECT_FAIL(11410006):packageName/moduleType/sourceRootsfields missing or inconsistent in the dependency module'sDependencyModuleConfigBUILDSYSTEM_SOURCEROOTS_NOT_SET_FAIL(11410003):sourceRootsfield is not set or is emptyBUILDSYSTEM_DEPENDENCY_ANALYZE_FAIL(11410015): circular dependency detected or imported file not found during dependency analysisBUILDSYSTEM_DECLGEN_FAIL(11410013) /BUILDSYSTEM_DECLGEN_FAILED_IN_WORKER(11410027): declgen phase failed; check whether the input AST has reached the CHECKED state- Incremental cache not invalidated after config change: check
isBuildConfigModifiedand the contents ofproject_build_config.json
Related Documents
AGENTS.md-- repository-level routing and constraintsets2panda/AGENTS.md-- ets2panda-wide frontend rulesets2panda/driver/docs/build-config.en.md-- full BuildConfig field descriptionsets2panda/driver/docs/target-build.en.md-- sourceRoots multi-target build and paths generation algorithmets2panda/driver/build_system/README.md-- local run and test stepsdocs/ets2panda/DeclGen_ETS2TS_Knowledge_Base.md-- declaration-generation downstream behavior