Def / custom type → .pyi type stubs: feasibility analysis (analysis only, no implementation)
Source: user request on 2026-10-16 — "Can the extension generate
.pyifiles for the utype-defined types, producing type hints automatically; is that realistic?" This round only settles design and conclusions, no implementation code is written; every judgment carries afile:line, and corpus limitations are stated as they are. 2026-10-17 reconciliation update: the type surface is now implemented — thekbengine.python.exportTypeStubscommand plus a silent auto-export ofkbe_types.pyat activation (a real.py, i.e. option A, reusing thekbengine.python.stubExportswitch and thestubDirthree-tier directory, with the extraPaths managed segment joining the same directory); the types.xml watcher auto-regeneration mentioned in §4 is implemented (2026-10-17 batch 146: silent re-export on save/create/delete, no debouncing and no extra setting, upheld by the zero-write discipline); the §7 to-verify list is unchanged.
0. Verdict summary
| # | Question | Verdict | Effort |
|---|---|---|---|
| 1 | Can the existing parsers read a utype definition | Yes, but not in the entityMapping/PythonClassIndex track — definitions are parsed by databaseSchema.parseTypeAliases (types.xml); .def/PythonClassIndex only store references and Python classes | Small (wiring) |
| 2 | utype → Python annotation mapping | Realistic: scalars/ARRAY/aliases translate directly, FIXED_DICT → TypedDict; deep nesting needs a real project to verify | Small–medium |
| 3 | Generated artifact + Pylance wiring | Realistic only with a precondition: reuse the existing stubDir+extraPaths facilities; but a pure .pyi module cannot be import-ed at runtime, so choose a real .py (TypedDict) or a TYPE_CHECKING convention; and never generate a same-named .pyi that shadows a project .py | Medium |
| 4 | Timing and updates | Realistic: the auto-export-on-activation + manual command precedents exist, and a debounced .def/types.xml watcher has a precedent; default-dir artifacts are not committed | Small–medium |
| 5 | Making self.x statically knowable to Pylance (without changing user code) | Not realistic (the only Pylance path is shadowing a project .py, which breaks implementation semantics); today kode's own providers fill this surface | — |
| — | Overall | Realistic with a precondition: "generate a type module for the type surface" = doable at medium effort; "self-annotation of entities" = not realistic without changing user code or keeping the kode providers | Medium |
1. Current state: how far the existing parsers reach
1.1 The entityMapping / PythonClassIndex track cannot read utype definitions
src/backend/defParser.ts:58parseDefDocumentis a generic XML parser (fxp,parseTagValue:falsesee:55), it carries no type semantics.src/entityMapping.ts:152builds its index only fromfindFiles('**/*.def'); the index structure:107-123(EntityMappingIndex) only hasmethodDefinitions,properties: { [name]: { defFile, line } }etc. — it stores reference landing points, passing the Type string through verbatim, storing no type definitions.src/backend/pythonClassIndex.ts:40parsePythonFileonly parses classes/methods of.py, scan surface:247findFiles('**/*.py', ...)— it never looks at .def.
→ Conclusion: neither of the two indexes named in the question contains utype definitions; the definitions live in entity_defs/types.xml, parsed by a different line below.
1.2 The three places that actually parse type definitions (already in this repo, reusable)
- types.xml alias definitions (= the utype definitions themselves):
src/databaseSchema.ts:724parseTypeAliases→Map<name, { kind: 'fixedDict'|'array'|'builtin'|'unresolved', ... }>; the comment aligns with the engine'sDataTypes::loadTypes(alias = entry tag,FIXED_DICT/ARRAYgo structural, the rest reuse registered types as text), see:96,:742-747; wiring at:246. FIXED_DICT keys and element types are kept on the XMLnode, so sub-parsing can continue. - Type strings in
.def(including inline ARRAY):src/kbengineMetadata.ts:11-12notes the engine'sentitydef.cppspecial case for the property<Type>ARRAY<of>…</of></Type>form,:41lands it in the completion docs;src/definitionSemantics.ts:74-88structures the<Arg>sequence (ARRAY via the<of>chain, recursive nesting,:627,:693comments align withFixedArrayType::initialize);src/clientSdkGenerator.ts:116-118,:197read the<Type>direct text and the<of>element type in two columns per the engine convention.
- The existing "utype → target language" precedent (closest finished artifact to this need):
src/clientSdkGenerator.ts:152aliases: ReadonlyMap<string,string>;:272-295"language-neutral type table: builtin table per language, aliases and FIXED_DICT share the same origin as the project types.xml";:301-321resolution chain builtin → FIXED_DICT name → alias recursion → fallback; FIXED_DICT companion classes emitted at:559(TS),:571(C#),:667(separate file). This isomorphic problem has already been solved once in the TS/C# generator;.pyiis a third emission target.
1.3 Terminology: this repo's "utype" has two layers (don't mix them)
- Message-layer utype = type/method number, not a custom type:
src/backend/messageTable.ts:130"this-level type utype (ARRAY level = the inline array type's own utype)"; engine sidekbe/res/sdk_templates/client/ue4/Source/KBEnginePlugins/Engine/Bundle.h:133(uint16 utype),EntityCall.cpp:67(methodUtype). - This request's "utype" = custom type alias / composite type, i.e. types.xml alias entries +
.defreferences. The.def<Aliases>section has 0 hits in this repo's corpus (grep '<Aliases>' --include='*.def'is empty repo-wide); alias definitions actually all live intypes.xml.
1.4 Real samples (corpus stated as is)
Sample 1 — definition (composite type), D:\workspaces\kbengine\.tmp\kbengine_typing_fixed_dict_fixture\scripts\entity_defs\types.xml (13 lines total):
2: <AVATAR_INFO> FIXED_DICT
3: <Properties>
4: <name><Type> STRING </Type></name>
7: <level><Type> UINT32 </Type></level>
10: </Properties>
11: </AVATAR_INFO>
12: <AVATAR_INFO_LIST> ARRAY <of> AVATAR_INFO </of> </AVATAR_INFO_LIST>Sample 2 — reference (a .def using a utype), the same fixture's scripts/entity_defs/Avatar.def:
4: <Type> AVATAR_INFO </Type> <!-- profile 属性 -->
8: <Type> AVATAR_INFO_LIST </Type> <!-- history 属性 -->
14: <Arg> AVATAR_INFO </Arg> <!-- BaseMethods.updateProfile -->
19: <Arg> AVATAR_INFO_LIST </Arg> <!-- CellMethods.syncSnapshots -->Sample 3 — inline ARRAY form (engine special case): the doc text registered at src/kbengineMetadata.ts:41 — "inline form <Type>ARRAY<of>element type</of></Type>, the element type goes in the <of> child node", per the property-loading special case in kbe/src/lib/entitydef/entitydef.cpp (:11-12).
Corpus limits (stated as is):
- Non-third-party
.deffiles in the whole repo: 18 (mostly.tmptype fixtures + SDK templates + BigWorld samples); visible<Type>values are onlySTRING/INT32/INT16/INT8plus the two fixture utypes above. - The SDK template
types.xmlis an empty shell (2 lines); complex type distributions (multi-level nesting, VECTOR3 keys, mixed ARRAY) have no real samples in this repo; the type surface of a real game project must be re-verified once available (see §7). - The word "utype" actually appears in this repo only in the message/method-number context (§1.3); there is no
.defstructure named utype.
2. Mapping feasibility: utype → Python type annotations
| utype form | Real example | Target annotation | Tier |
|---|---|---|---|
| Scalar | STRING/INT32 (Avatar.def:4 same shape on the reference surface) | str / int; FLOAT/DOUBLE→float; BOOL→bool | Direct (small) |
PYTHON / PY / unrecognized | outside the corpus, engine semantics = arbitrary object | typing.Any (lossy but legal) | Direct (small) |
| Alias → registered type | types.xml third form (parseTypeAliases 'builtin' arm databaseSchema.ts:750) | AVATAR_NAME = str (type alias) | Direct (small) |
| ARRAY element type | AVATAR_INFO_LIST (types.xml:12) | list[AVATAR_INFO]; nested list[list[T]] (recursion chain already in definitionSemantics.ts:75) | Direct (small) |
| FIXED_DICT | AVATAR_INFO (types.xml:2-11) | class AVATAR_INFO(TypedDict): name: str; level: int | Needs a generated class (small–medium) |
| Nested FIXED_DICT / vector keys | no real sample in this repo | nested TypedDict recursion; key types reference the vector class (see §7 to verify) | Medium (needs a real project) |
| Fixed-length array (FIXEDARRAY) | engine DB layer kbe/src/lib/db_interface/entity_table.h:24, FixedArrayType (entity_table_mysql.cpp:1261) | In Python it is just a list → folds into the ARRAY direct translation; it is a DB storage structure, not a new Python shape | Direct (small) |
| Message/method utype number | src/backend/messageTable.ts:130, Bundle.h:133 | Unrelated to type hints, not generated | Excluded |
Verdict: the mapping surface is realistic — all three tiers are present, and the hardest part ("alias recursion + FIXED_DICT structure") already has an implementation path proven by clientSdkGenerator.ts:301-321 to copy the convention from; the uncertainty is concentrated in real projects' composite depth (no samples in this repo).
3. Artifact form and Pylance wiring
3.1 Where it goes: reuse stubDir, never same-named with a .def
- The three-tier directory resolution already exists: setting
kbengine.python.stubDir(package.json:1001) > env varKBENGINE_STUB_DIR> default convention.kbengine/stubs(src/pythonStubExport.ts:24/:31/:37-39, docsdocs/guide/configuration.md:277). - A
.defhas no same-named.pymodule, so "same-named with the .def" has nothing to hang on; suggested single-module concentration:kbe_types.pyiorkbe_types.py(see 3.2), living alongside the existingKBEngine.pyi(pythonStubExport.ts:21).
3.2 Getting Pylance to use it (existing wiring + one hard precondition)
- The wiring already exists:
python.analysis.extraPathsis written bysrc/pythonExtraPaths.ts:24(the comment at:4states Pylance resolves through it); the default stub directory sits in the managed segment (:8-9"merged only when the setting is on and KBEngine.pyi is on disk"; boundary atconfiguration.md:281). Auto-sync on activationextension.ts:972-975, manual commandextension.ts:964-971(kbengine.python.exportStubs). - Hard precondition (the whole line collapses without it): a pure
.pyimodule cannot beimport-ed at runtime — Python's importer has no.pyiloader, so user code writingfrom kbe_types import AVATAR_INFOfails at runtime withModuleNotFoundError, and is only safe inside aTYPE_CHECKINGbranch. Two viable landing options:- Option A (recommended): generate a real
.py(content =TypedDict/type aliases, usable at runtime) — holds for both Pylance and runtime; reuse thestubDirdirectory and the "content-identical zero-write" discipline (pythonStubExport.ts:5-7/:58). - Option B: keep a pure
.pyi, convention: users writeif TYPE_CHECKING: from kbe_types import ...plus string annotations — zero runtime dependency, but requires changing user code and writing it into the docs.
- Option A (recommended): generate a real
python.analysis.stubPath: Pylance's other stub path, 0 hits in this repo (not wired), listed as a to-verify option, not a dependency.- Red line: never generate a
.pyisame-named with a project.py(entity-class stubs). Under extraPaths/stub precedence, a same-named.pyishadows the project implementation file, and Pylance would stop seeing the real method bodies (completion/navigation semantics replaced by the stub) — more harm than good → explicitly excluded.
3.3 Coexisting with the existing navigation index
- Everything reads
.def/types.xmlread-only; writes only land instubDir(default dir is kode-managed, content-identical zero-write, suggest gitignore:configuration.md:279; theKBEngine.pyiheader also carries that suggestion itself,kbeModuleIndex.ts:831). entityMapping(:152) andPythonClassIndex(:247) do not read.pyi— mutually unaffected; kode's own hover/completion/navigation (languageProviders, data source =.def) does not depend on Pylance — the two are complementary, not conflicting: Pylance gets type names, kode gets project semantics (RPC, DB storage, navigation).
4. Timing and updates
- The precedent trio is complete: auto-export on activation (
extension.ts:972-975,{ silent: true }) + manual command (:964-971) + content-identical zero-write / stale-only rewrite (pythonStubExport.ts:5-7/:58). .def/types.xml change → regenerate: a debounced watcher has a ready precedent (src/hotReload.ts:5builds a watcher, debounce-merges successive saves,:38-44debounceMs convention) → suggested same approach; the minimal start can be manual command + activation only, the watcher as phase two (small → medium).- Whether artifacts are committed: the default
.kbengine/stubsis already characterized as "kode-managed, suggest.gitignore, artifacts follow the index" (configuration.md:279,kbeModuleIndex.ts:831) → not committed; a user-configured directory = user assets, kode only scans, never overwrites (configuration.md:279).
5. Per-item conclusions and effort
- Reading a utype definition — realistic (small): no new parser; reuse
parseTypeAliases(databaseSchema.ts:724) + theclientSdkGeneratorresolution chain (:301-321); the only gap is joining the.defreference surface (entityMapping.ts:107-123Type strings) with the types.xml definitions into one type table. - Mapping — realistic (small–medium): three direct-translation tiers +
FIXED_DICT→TypedDictcovers every sample-level shape; deep nesting needs re-verification on a real project (uncertainty = medium, not effort). - Artifact and wiring — realistic only with a precondition (medium): precondition A picks "real
.py(TypedDict)" or precondition B establishes theTYPE_CHECKINGconvention (§3.2); keep the "don't shadow a project.py" red line. Once satisfied, reusestubDir+extraPaths+the zero-write facility; the incremental work is mostly an emitter + type table. - Making the entity property
self.xstatically knowable to Pylance — not realistic: a stub cannot hang annotations anywhere without rewriting the user's.py; the only Pylance path is same-name shadowing (already excluded). That surface keeps being filled by kode's own providers (languageProvidershover/completion/navigation); if it is ever to be truly done, it is a "in-code annotation generation" new requirement (modifies user files, separate ignition). - Auto-update — realistic (small–medium): the precedent trio is complete, the debounced watcher has the
hotReloadconvention. - Overall: realistic with a precondition (total effort "medium") — "type module generation" is doable and reuses mostly existing pieces; "entity self-annotation surface" is not realistic without changing user code or keeping the kode providers.
6. Design points (for the next ignition round, not produced this round)
2026-10-17 implementation record: every recommended item in this section was taken — a separate command, a real
.py(option A), the default directory kode-managed with user directories never overwritten, deterministic content for the zero-write discipline; watcher auto-regeneration landed as phase two the same day (batch 146, changes silently re-export).
- Type table:
types.xmlaliases (parseTypeAliases) + the.defreference surface (entityMappingType strings) compose aMap<type name, type description>; alias-recursion cycle protection follows theclientSdkGenerator.ts:301convention. - Emission: direct translation for the scalar/ARRAY/type-alias three tiers; FIXED_DICT emits a
TypedDict(key order follows the types.xml document order,databaseSchema.ts:724node traversal); afrom __future__ import annotationsheader, zero runtime dependency. - Landing: default
.kbengine/stubs/kbe_types.py(±.pyi), the same zero-write discipline asKBEngine.pyi; header states "generated artifact, suggest gitignore". - Wiring: the file joins the
extraPathsmanaged segment (aligned with the join condition atpythonExtraPaths.ts:8-9); either add one more emit on thekbengine.python.exportStubssurface or add a separatekbengine.python.exportTypeStubs.
7. To-verify list (cannot be asserted within this repo)
python.analysis.stubPathhit precedence overextraPathsfor.pyi— not wired in this repo (0 hits), measure before implementing.- Type distribution of a real game project (multi-level nested FIXED_DICT, VECTOR3 keys, mixed ARRAY) — this repo's corpus only has fixture-level samples (§1.4); the SDK template
types.xmlis an empty shell. - Availability of the vector type (
VECTOR3) insideKBEngine.pyi— resolved by gen-def-1b/1c:src/kbeModuleIndex.tsKBE_SYMBOLSnow carriesclass Vector2/3/4entries (full method bodies,cppClassNameScriptVectorN), and theVECTOR2/3/4→KBEngine.Vector2/3/4annotation mapping is locked bytests/kbeModuleIndex.test.ts+tests/entityTypeStubs.test.ts.
8. 增补:2026-10-27 pyi ④(Any 消灭与分件合并)
任务书 kode-pyi-stubs.md 任务2。本节只记真实落地的取舍;每条都有 vitest 锁。
8.1 分件单位从「源文件」改成「镜像目录」(合并 types.xml + alias.xml)
- 病根:
scripts/entity_defs/下的types.xml与alias.xml镜像落点相同 (<stubs>/scripts/entity_defs/kbe_types.pyi)。按源文件各写一份时,后写组 覆盖先写组——谁存活取决于组内首个类型名的字典序,纯内容运气;且两组各查 各的类型表,types.xml引用alias.xml的名字(如 FIXED_DICT 属性引SKILL_FLAGS)一律解析不到落Any。 - 取舍:模块身份 = 镜像目录,不是源文件。同目录两源合并成一个
kbe_types.pyi(groupCustomTypesByModule),互相引用自然同表可解析; 逐条# source:注释带源文件标签(types.xml/alias.xml)区分来源。 - 同名两源都在:引擎口径
addDataType对重复名报错并拒注册 (datatypes.cpp:198-203,types.xml 先注册、alias.xml 后到)——存根同样 types.xml 先见保留、alias.xml 后到作废,作废条目进 plan.skipped 写明缘由, 绝不双发射。 - 跨镜像目录引用(两个不同 types.xml 树):本模块查不到的名字若在别的 kbe_types 分件已发射,按名引用并在头部补
from <模块> import <名字>; 类型桩不执行,模块间循环引用对 Pylance 无害。跨模块同名各自本地优先, 实体桩导入面按镜像序先见——真实项目罕见,如实记边界不硬造。
8.2 内建表注册面核对(补全缺项的结论:不缺)
- 对照面是 C++ 注册面,不是 types.xml——kbengine 仓里没有默认
kbe/res/server/types.xml(该路径只有 kbengine_defaults.xml 等四个文件), 内建类型全部在kbe/src/lib/entitydef/datatypes.cppDataTypes::initialize(56-79 行)注册,共 21 个:UINT8..64/INT8..64/STRING/UNICODE/FLOAT/DOUBLE/ PYTHON/PY_DICT/PY_TUPLE/PY_LIST/ENTITYCALL/BLOB/VECTOR2/3/4。本地检出/home/cui/workspaces/kbengine与上游 master 逐名核对,PYTHON_BUILTIN_TYPE_ANNOTATIONS21 个全在,无缺项;表内唯一注册面之外的条目是BOOL(BigWorld 迁移 遗产的礼貌容错,def 层仍按幻影类型诊断),无自创条目。vitest 注册面锁 (21 名单列 + 只许 BOOL 一条例外)防未来漂移。
8.3 诚实 Any 的最终边界(消灭后剩下的都有名有据)
- 裸 ARRAY(def 直接写
ARRAY无自定义类型、types.xml<Type>ARRAY</Type>缺<of>)→List[Any];裸PYTHON(def 未声明impl)→Any(引擎侧 任意可 pickle 对象);ALIAS 占位/指引为空/成环 → poisoned 不发射,引用处 Any;BigWorld 专有类型名(kbengine 注册面外)→ Any。以上全部保留,不属于 「可避免 Any」。GEN-DEF-1c 已把ENTITYCALL→KBEngine.EntityCall、PY_DICT/PY_TUPLE/PY_LIST→dict/tuple/list(按<Default>字面量 精化)、PYTHON有impl时→impl 类、BLOB→bytes、VECTOR2/3/4→KBEngine.Vector2/3/4移出本边界(裸 PYTHON 仍留)。 - 元素型 ARRAY 的消灭(
ARRAY <of> X→List[X],of 套 of 递归)在 B 单 已落地(pythonTypeStubs.test.ts 嵌套/缺 of/ALIAS 占位三例),本次未改。 2026-10-29 补:FIXED_DICT 属性面内联<Type>ARRAY<of>X</of></Type>同样 消灭——definitionWorkspace.parseCustomTypeProperties 现随 typeName 一并 产出 typeStructure(与类型条目顶层同一解析器),存根 propertyAnnotation 据此解析元素型;树缺失/解析失败才落List[Any](用户报 AVATAR_SHOW_INFO roleInfoList 收口)。
8.4 实体存根继承与 mailbox 面(任务1,最小可用取舍)
- 继承:
entity_types.pyi每个实体类从class Avatar:升为class Avatar(Entity):,头部from KBEngine import Entity(生成桩 KBEngine.pyi 的符号目录本来就有 Entity)。继承属类身份,不属方法面:kbengine.python.entityStubMethods=false时方法面让位,继承头仍在。 - mailbox:有方法面的实体配一个
<Entity>MB(EntityCall)句柄类, 方法签名与实体类方法面同链同源(methodArgAnnotation → 注册表解析),.def三段(Base/Cell/Client)方法全部合并其上,逐条带# source:注释。实体类上base/cell/client: Union[<Entity>MB, None]三条收窄—— 引擎语义上三属性恒存在(无远端时 None),收窄只认类型不断言存在性。 - 为什么不在 KBEngine.pyi 的 Entity 基类上标 MB 类型:KBEngine.pyi 是 全局静态符号目录,逐实体的 MB 类型只存在于本工作区的 entity_types.pyi, 静态基类引用不到——所以收窄放实体类属性覆写(基类对这三属性本无声明, 覆写不冲突)。这是一期取舍;若未来 KBEngine.pyi 走生成式合并可再议。
- 开关与边界:mailbox 面整体随
kbengine.python.entityStubMethods让位(=false 时无 MB 类、无 EntityCall 导入、无三条覆写);纯属性实体 不配 MB(无方法面可装,实体属性继承基类语义)。MB 类名<Entity>MB与他实体撞名的场景(实体本名就叫XMB)未做防御,真实项目罕见,如实 记边界。 - 方法形参导入面修复:头部 kbe_types 导入扫描此前只扫属性注解,方法 形参注解引用自定义类型名(如
respawn(arg1: ITEM_INFO))会悬挂裸名—— 本批补扫方法形参(MB 面与实体方法面共用同一批注解,一处补扫两处受益)。