Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
BL22: 155 any declarations down to 79: Python returns read from their own source, sequence items from Blender's C
shinyobjectz65074df06e9e
diff --git a/docs/blender.feature b/docs/blender.featureindex 7539f2b8..59831b71 100644--- a/docs/blender.feature+++ b/docs/blender.feature@@ -90,15 +90,27 @@ Feature: Blender as a measured workshop step: an asset passes through it on itsScenario: BL22. The whole API is typed from Blender's own: tools/gen.sh dumps Blender's RNA and docstrings, gen writes src/genGiven Blender 5.2.1: 1809 structs (bpy.types), 2498 operators in 77 bpy.ops modules, and 41 modules outside RNA(mathutils' submodules, bmesh, gpu, bpy.utils, bpy.path, bpy.props, bpy.msgbus, bpy_extras, aud, imbuf, idprop)- Then 51 of bpy.types' 16 684 declarations are typed `any` (0.3%; 127 before 11-11): Python methods that return a- value their docstring doesn't type, and Python properties with no `:type:`. A function written in Python whose- source returns no value anywhere (dump.py returns_none) returns nothing, as Python's None, and operators have no- `any` at all; the modules outside RNA have 104 of 1 461 (423 before 11-11), mostly Python helpers in bpy_extras- and bpy.utils and bpy.props' property definitions+ Then 32 of bpy.types' 16 684 declarations are typed `any` (0.2%; 127 before 11-11), and 47 of the 1 440 of the+ modules outside RNA (423 before 11-11); operators have none. What's left is dynamic by nature (bpy_struct.get,+ path_resolve, an ID property group's get), context managers and draw handlers' handles, and Python helpers+ whose source returns another call's result+ And a function written in Python returns what its own source shows: nothing, as Python's None, where it returns+ no value anywhere (dump.py returns_none); else the type every `return` gives, when each shows one+ (tools/returns.py: a literal, a comparison, a builtin's result, a local only ever bound to such):+ CyclesPreferences.has_active_device() a boolean, Mesh.edge_keys an array, BoneCollection.bones_recursive a set.+ test/returns.test.ts runs its cases and reads every member it types on live meshes, bone collections and+ Cycles' preferences in Blender (11-11)+ And a sequence whose name doesn't give its items has them from Blender's C: bm.select_history[i] a vertex, edge+ or face, a BMElemSeq's any element, a layer collection's BMLayerItems, a deform vertex's [group] a weight, an+ IDPropertyArray's numbers or booleans; BMVert[layer] and an ID property group (by name, through `$`) take no+ number+ And Python's own names a Blender module imports (anim_utils' Mapping, Sequence, typing aliases) are left out, and+ bpy.props' functions give _PropertyDeferred, the private class their docstrings nameAnd where a C method's or property's docstring gives no type, tools/cret.sh reads it from the bindings' own C- source (tools/cret.json: 274 method and 122 property names, each where every C function bound to that name- agrees): None, bool, int, float, str, or a tuple a Py_BuildValue format makes; test/cret.test.ts reads every- property so typed on live bmesh, aud, imbuf and mathutils objects in Blender and gets that type (11-11)+ source (tools/cret.json: 284 method and 123 property names, each where every C function bound to that name+ agrees, a returned local by its every assignment): None, bool, int, float, str, or a tuple a Py_BuildValue+ format makes; test/cret.test.ts reads every property so typed on live bmesh, aud, imbuf and mathutils objects+ in Blender and gets that type (11-11)And two dumps of one Blender write the same src/gen (sets sorted, no memory addresses)And tsc rejects a read-only property set, an enum value Blender doesn't have, a member that isn't there, a wrongargument type, and arithmetic on an unawaited path (test/typing.ts)diff --git a/sdk/blender/src/gen/py/bmesh_types.ts b/sdk/blender/src/gen/py/bmesh_types.tsindex b15ad2cc..a48fcded 100644--- a/sdk/blender/src/gen/py/bmesh_types.ts+++ b/sdk/blender/src/gen/py/bmesh_types.ts@@ -53,7 +53,7 @@ export interface Api {/** bmesh.types.BMDeformVert */export interface BMDeformVert {- readonly [index: number]: any;+ readonly [index: number]: H.Ref<number>;/*** Return the group indices used by this vertex* (matching Python's dict.keys() functionality).@@ -124,7 +124,6 @@ export interface BMDeformVertClass {* bmesh.types.BMEdge*/export interface BMEdge {- readonly [index: number]: any;/*** Set the selection.* This is different from the *select* attribute because it updates the selection state of associated geometry.@@ -444,8 +443,8 @@ export interface BMEditSelIterClass {}/** bmesh.types.BMEditSelSeq */-export interface BMEditSelSeq extends AsyncIterable<any> {- readonly [index: number]: any;+export interface BMEditSelSeq extends AsyncIterable<P.bmesh_types.BMVert | P.bmesh_types.BMEdge | P.bmesh_types.BMFace> {+ readonly [index: number]: H.Ptr<P.bmesh_types.BMVert | P.bmesh_types.BMEdge | P.bmesh_types.BMFace>;/** Ensures all elements in the selection history are selected. */validate(...args: any[]): H.Ref<void>;/** Empties the selection history. */@@ -510,8 +509,8 @@ export interface BMEditSelSeqClass {** bmesh.types.BMElemSeq*/-export interface BMElemSeq extends AsyncIterable<any> {- readonly [index: number]: any;+export interface BMElemSeq extends AsyncIterable<P.bmesh_types.BMVert | P.bmesh_types.BMEdge | P.bmesh_types.BMFace | P.bmesh_types.BMLoop> {+ readonly [index: number]: H.Ptr<P.bmesh_types.BMVert | P.bmesh_types.BMEdge | P.bmesh_types.BMFace | P.bmesh_types.BMLoop>;/*** Initialize the index values of this sequence.*@@ -547,7 +546,6 @@ export interface BMElemSeqClass {* bmesh.types.BMFace*/export interface BMFace {- readonly [index: number]: any;/*** Set the selection.* This is different from the *select* attribute because it updates the selection state of associated geometry.@@ -1059,8 +1057,8 @@ export interface BMLayerAccessVertClass {** bmesh.types.BMLayerCollection*/-export interface BMLayerCollection extends AsyncIterable<any> {- readonly [index: number]: any;+export interface BMLayerCollection extends AsyncIterable<P.bmesh_types.BMLayerItem> {+ readonly [index: number]: H.Ptr<P.bmesh_types.BMLayerItem>;/*** Create a new layer or return an existing active layer* @returns The newly created layer, or the existing active layer.@@ -1195,7 +1193,6 @@ export interface BMLayerItemClass {* bmesh.types.BMLoop*/export interface BMLoop {- readonly [index: number]: any;/*** Copy values from another element of matching type.* @param other Another element of the same type to copy from.@@ -1382,7 +1379,6 @@ export interface BMLoopUVClass {* bmesh.types.BMVert*/export interface BMVert {- readonly [index: number]: any;/*** Set the selection.* This is different from the *select* attribute because it updates the selection state of associated geometry.diff --git a/sdk/blender/src/gen/py/bpy_extras_anim_utils.ts b/sdk/blender/src/gen/py/bpy_extras_anim_utils.tsindex c4b0c348..625288a3 100644--- a/sdk/blender/src/gen/py/bpy_extras_anim_utils.ts+++ b/sdk/blender/src/gen/py/bpy_extras_anim_utils.ts@@ -12,31 +12,9 @@ export interface Api {readonly AutoKeying: AutoKeyingClass;/** BakeOptions(only_selected: bool, do_pose: bool, do_object: bool, do_visual_keying: bool, do_constraint_clear: bool, do_parents_clear: bool, do_clean: bool, do_location: bool, do_rotation: bool, do_scale: bool, do_bbone: bool, do_custom_props: bool) */readonly BakeOptions: BakeOptionsClass;- /**- * Built-in immutable sequence.- *- * If no argument is given, the constructor returns an empty tuple.- * If iterable is specified the tuple is initialized from iterable's items.- *- * If the argument is a tuple, the return value is the same object.- */- FCurveKey(iterable?: readonly any[]): any;- /** Deprecated alias to collections.abc.Iterable. */- Iterable(...args: any[]): any;/** A buffer for keyframe Co unpacked values per ``FCurveKey``. ``FCurveKeys`` are added using */readonly KeyframesCo: KeyframesCoClass;- /**- * Built-in mutable sequence.- *- * If no argument is given, the constructor creates a new empty list.- * The argument must be an iterable if specified.- */- ListKeyframes(iterable?: readonly any[]): any;- /** A Mapping is a generic container for associating key/value */- readonly Mapping: MappingClass;readonly PoseBone: PoseBoneClass;- /** All the operations on a read-only sequence. */- readonly Sequence: SequenceClass;/*** Ensure a layer and a keyframe strip exists, then ensure that strip has a channelbag for the slot.* @returns The channelbag for *slot* in the first keyframe strip.@@ -232,32 +210,6 @@ export interface Api {/** Options for baking. */bake_options: P.bpy_extras_anim_utils.BakeOptions;}): H.Ref<any[]>;- /**- * Add dunder methods based on the fields defined in the class.- *- * Examines PEP 526 __annotations__ to determine fields.- *- * If init is true, an __init__() method is added to the class. If repr- * is true, a __repr__() method is added. If order is true, rich- * comparison dunder methods are added. If unsafe_hash is true, a- * __hash__() method is added. If frozen is true, fields may not be- * assigned to after instance creation. If match_args is true, the- * __match_args__ tuple is added. If kw_only is true, then by default- * all fields are keyword-only. If slots is true, a new class with a- * __slots__ attribute is returned.- */- dataclass(kw?: {- init?: boolean;- repr?: boolean;- eq?: boolean;- order?: boolean;- unsafe_hash?: boolean;- frozen?: boolean;- match_args?: boolean;- kw_only?: boolean;- slots?: boolean;- weakref_slot?: boolean;- }): any;rna_idprop_value_to_python(value: any): any;rna_idprop_value_to_python(kw: { value: any }): any;}@@ -591,45 +543,9 @@ export interface KeyframesCoClass {(): H.Own<KeyframesCo>;}-/**- * A Mapping is a generic container for associating key/value- * pairs.- *- * This class provides concrete generic implementations of all- * methods except for __getitem__, __iter__, and __len__.- *- * bpy_extras.anim_utils.Mapping- */-export interface Mapping {- readonly [index: number]: any;- /** D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. */- get(key: any, default_?: any): any;- /** D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. */- get(key: any, kw: { default?: any }): any;- /** D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. */- get(kw: { key: any; default?: any }): any;- /** D.keys() -> a set-like object providing a view on D's keys */- keys(): any;- /** D.items() -> a set-like object providing a view on D's items */- items(): any;- /** D.values() -> an object providing a view on D's values */- values(): any;-}-/** The class bpy_extras.anim_utils.Mapping: called, a new one. */-export interface MappingClass {- /**- * A Mapping is a generic container for associating key/value- * pairs.- *- * This class provides concrete generic implementations of all- * methods except for __getitem__, __iter__, and __len__.- */- (): H.Own<Mapping>;-}-/** bpy_extras.anim_utils.PoseBone */export interface PoseBone {- get children(): any;+ get children(): H.Ref<any[]>;}/** The class bpy_extras.anim_utils.PoseBone: called, a new one. */export interface PoseBoneClass {@@ -637,53 +553,3 @@ export interface PoseBoneClass {/** = <bpy_struct, Struct("PoseBone")> */readonly bl_rna: H.Ref<any>;}--/**- * All the operations on a read-only sequence.- *- * Concrete subclasses must override __new__ or __init__,- * __getitem__, and __len__.- *- * bpy_extras.anim_utils.Sequence- */-export interface Sequence extends AsyncIterable<any> {- readonly [index: number]: any;- /**- * S.index(value, [start, [stop]]) -> integer -- return first index of value.- * Raises ValueError if the value is not present.- *- * Supporting start and stop arguments is optional, but- * recommended.- */- index(value: any, start?: number, stop?: any): any;- /**- * S.index(value, [start, [stop]]) -> integer -- return first index of value.- * Raises ValueError if the value is not present.- *- * Supporting start and stop arguments is optional, but- * recommended.- */- index(value: any, kw: { start?: number; stop?: any }): any;- /**- * S.index(value, [start, [stop]]) -> integer -- return first index of value.- * Raises ValueError if the value is not present.- *- * Supporting start and stop arguments is optional, but- * recommended.- */- index(kw: { value: any; start?: number; stop?: any }): any;- /** S.count(value) -> integer -- return number of occurrences of value */- count(value: any): any;- /** S.count(value) -> integer -- return number of occurrences of value */- count(kw: { value: any }): any;-}-/** The class bpy_extras.anim_utils.Sequence: called, a new one. */-export interface SequenceClass {- /**- * All the operations on a read-only sequence.- *- * Concrete subclasses must override __new__ or __init__,- * __getitem__, and __len__.- */- (): H.Own<Sequence>;-}diff --git a/sdk/blender/src/gen/py/bpy_extras_io_utils.ts b/sdk/blender/src/gen/py/bpy_extras_io_utils.tsindex 769949a9..cff48cce 100644--- a/sdk/blender/src/gen/py/bpy_extras_io_utils.ts+++ b/sdk/blender/src/gen/py/bpy_extras_io_utils.ts@@ -67,7 +67,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new enumerator property definition.* @returns Opaque type used for registration.@@ -132,7 +132,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new enumerator property definition.* @returns Opaque type used for registration.@@ -223,7 +223,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;readonly ExportHelper: ExportHelperClass;readonly ImportHelper: ImportHelperClass;/**@@ -305,7 +305,7 @@ export interface Api {* so only disable this flag if it's not likely to cause performance issues.*/search_options?: H.In<Set<string>>;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Each argument is an axis* where the first 2 are a source and the second 2 are the target.diff --git a/sdk/blender/src/gen/py/bpy_extras_object_utils.ts b/sdk/blender/src/gen/py/bpy_extras_object_utils.tsindex f1635e10..f46d0a43 100644--- a/sdk/blender/src/gen/py/bpy_extras_object_utils.ts+++ b/sdk/blender/src/gen/py/bpy_extras_object_utils.ts@@ -72,7 +72,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new enumerator property definition.* @returns Opaque type used for registration.@@ -163,7 +163,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new vector float property definition.* @returns Opaque type used for registration.@@ -240,7 +240,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Return a matrix using the operator settings and view context.* @returns the matrix from the context and settings.diff --git a/sdk/blender/src/gen/py/bpy_props.ts b/sdk/blender/src/gen/py/bpy_props.tsindex 63275daa..4d98d35a 100644--- a/sdk/blender/src/gen/py/bpy_props.ts+++ b/sdk/blender/src/gen/py/bpy_props.ts@@ -71,7 +71,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new vector boolean property definition.* @returns Opaque type used for registration.@@ -134,7 +134,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new collection property definition.* @returns Opaque type used for registration.@@ -153,7 +153,7 @@ export interface Api {override?: H.In<Set<string>>;/** Enumerator of tags that are defined by parent class. */tags?: H.In<Set<string>>;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new collection property definition.* @returns Opaque type used for registration.@@ -174,7 +174,7 @@ export interface Api {override?: H.In<Set<string>>;/** Enumerator of tags that are defined by parent class. */tags?: H.In<Set<string>>;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new enumerator property definition.* @returns Opaque type used for registration.@@ -239,7 +239,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new enumerator property definition.* @returns Opaque type used for registration.@@ -330,7 +330,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new float (single precision) property definition.* @returns Opaque type used for registration.@@ -405,7 +405,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new vector float property definition.* @returns Opaque type used for registration.@@ -482,7 +482,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new int property definition.* @returns Opaque type used for registration.@@ -553,7 +553,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new vector int property definition.* @returns Opaque type used for registration.@@ -626,7 +626,7 @@ export interface Api {* .. note:: The callback is responsible to ensure that value limits (min/max, length...) are respected. Otherwise a ValueError exception is raised.*/set_transform?: any;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;/*** Returns a new pointer property definition.*@@ -816,6 +816,38 @@ export interface Api {* so only disable this flag if it's not likely to cause performance issues.*/search_options?: H.In<Set<string>>;- }): any;+ }): H.Ptr<P.bpy_props._PropertyDeferred>;+ /** Intermediate storage for properties before registration. */+ readonly _PropertyDeferred: _PropertyDeferredClass;}+/**+ * Intermediate storage for properties before registration.+ *+ * .. note::+ *+ * This is not part of the stable API and may change between releases.+ *+ * bpy.props._PropertyDeferred+ */+export interface _PropertyDeferred {+ /** Call self as a function. */+ (...args: any[]): any;+ /** The property registration function (e.g. :func:`bpy.props.IntProperty`). */+ get function(): any;+ set function(v: any);+ /** The keyword arguments passed to the property registration function. */+ get keywords(): H.Ref<Map<string, any>>;+ set keywords(v: H.In<H.DictIn<any>>);+}+/** The class bpy.props._PropertyDeferred: called, a new one. */+export interface _PropertyDeferredClass {+ /**+ * Intermediate storage for properties before registration.+ *+ * .. note::+ *+ * This is not part of the stable API and may change between releases.+ */+ (): H.Own<_PropertyDeferred>;+}diff --git a/sdk/blender/src/gen/py/bpy_utils.ts b/sdk/blender/src/gen/py/bpy_utils.tsindex 3c07c779..5b5ce9a2 100644--- a/sdk/blender/src/gen/py/bpy_utils.ts+++ b/sdk/blender/src/gen/py/bpy_utils.ts@@ -171,7 +171,7 @@ export interface Api {keyconfig_set(filepath: H.In<string>, kw?: {/** An optional callable for reporting errors. */report?: any;- }): any;+ }): H.Ref<boolean>;/*** Load and activate a key configuration from a file.* @param filepath The file path to the key configuration preset.@@ -181,7 +181,7 @@ export interface Api {filepath: H.In<string>;/** An optional callable for reporting errors. */report?: any;- }): any;+ }): H.Ref<boolean>;/** Load scripts and run each modules register function. */load_scripts(kw?: {/**@@ -527,9 +527,9 @@ export interface Api {use_system_environment?: H.In<boolean>;}): H.Ref<string[]>;/** Returns a list of user preference script directories. */- script_paths_pref(): any;+ script_paths_pref(): H.Ref<any[]>;/** Returns a list of system script directories from environment variables. */- script_paths_system_environment(): any;+ script_paths_system_environment(): H.Ref<any[]>;/*** Returns an SMPTE formatted string from the *frame*:* ``HH:MM:SS:FF``.diff --git a/sdk/blender/src/gen/py/gpu_types.ts b/sdk/blender/src/gen/py/gpu_types.tsindex 406fd688..93a02de3 100644--- a/sdk/blender/src/gen/py/gpu_types.ts+++ b/sdk/blender/src/gen/py/gpu_types.ts@@ -800,7 +800,7 @@ export interface GPUShaderCreateInfo {* to be performed.* @param value Depth write value. :UNCHANGED: disables depth write in a fragment shader and execution of the fragments can be optimized away. :ANY: enables depth write in a fragment shader for any fragments :GREATER: enables depth write in a fragment shader for depth values that are greater than the depth value in the output buffer. :LESS: enables depth write in a fragment shader for depth values that are less than the depth value in the output buffer.*/- depth_write(value: H.In<"UNCHANGED" | "ANY" | "GREATER" | "LESS">): any;+ depth_write(value: H.In<"UNCHANGED" | "ANY" | "GREATER" | "LESS">): H.Ref<void>;/*** Specify a depth write behavior when modifying gl_FragDepth.*@@ -826,7 +826,7 @@ export interface GPUShaderCreateInfo {* :LESS: enables depth write in a fragment shader for depth values that are less than the depth value in the output buffer.*/value: H.In<"UNCHANGED" | "ANY" | "GREATER" | "LESS">;- }): any;+ }): H.Ref<void>;/*** Specify a fragment output corresponding to a framebuffer target slot.* @param slot The attribute index.@@ -836,7 +836,7 @@ export interface GPUShaderCreateInfo {fragment_out(slot: H.In<number>, type: H.In<"FLOAT" | "VEC2" | "VEC3" | "VEC4" | "MAT3" | "MAT4" | "UINT" | "UVEC2" | "UVEC3" | "UVEC4" | "INT" | "IVEC2" | "IVEC3" | "IVEC4" | "BOOL">, name: H.In<string>, kw?: {/** Dual Source Blending Index. */blend?: H.In<"NONE" | "SRC_0" | "SRC_1">;- }): any;+ }): H.Ref<void>;/*** Specify a fragment output corresponding to a framebuffer target slot.* @param slot The attribute index.@@ -852,14 +852,14 @@ export interface GPUShaderCreateInfo {name: H.In<string>;/** Dual Source Blending Index. */blend?: H.In<"NONE" | "SRC_0" | "SRC_1">;- }): any;+ }): H.Ref<void>;/*** Specify a uniform variable whose type can be one of those declared in :meth:`gpu.types.GPUShaderCreateInfo.typedef_source`.* @param slot The uniform variable index.* @param type_name Name of the data type. It can be a struct type defined in the source passed through the :meth:`gpu.types.GPUShaderCreateInfo.typedef_source`.* @param name The uniform variable name.*/- uniform_buf(slot: H.In<number>, type_name: H.In<string>, name: H.In<string>): any;+ uniform_buf(slot: H.In<number>, type_name: H.In<string>, name: H.In<string>): H.Ref<void>;/*** Specify a uniform variable whose type can be one of those declared in :meth:`gpu.types.GPUShaderCreateInfo.typedef_source`.* @param slot The uniform variable index.@@ -873,7 +873,7 @@ export interface GPUShaderCreateInfo {type_name: H.In<string>;/** The uniform variable name. */name: H.In<string>;- }): any;+ }): H.Ref<void>;/*** Specify an image resource used for arbitrary load and store operations.* @param slot The image resource index.@@ -931,7 +931,7 @@ export interface GPUShaderCreateInfo {* @param name Name of the constant.* @param size If not zero, indicates that the constant is an array with the specified size.*/- push_constant(type: H.In<"FLOAT" | "VEC2" | "VEC3" | "VEC4" | "MAT3" | "MAT4" | "UINT" | "UVEC2" | "UVEC3" | "UVEC4" | "INT" | "IVEC2" | "IVEC3" | "IVEC4" | "BOOL">, name: H.In<string>, size?: H.In<number>): any;+ push_constant(type: H.In<"FLOAT" | "VEC2" | "VEC3" | "VEC4" | "MAT3" | "MAT4" | "UINT" | "UVEC2" | "UVEC3" | "UVEC4" | "INT" | "IVEC2" | "IVEC3" | "IVEC4" | "BOOL">, name: H.In<string>, size?: H.In<number>): H.Ref<void>;/*** Specify a global access constant.* @param type The data type of the constant.@@ -941,7 +941,7 @@ export interface GPUShaderCreateInfo {push_constant(type: H.In<"FLOAT" | "VEC2" | "VEC3" | "VEC4" | "MAT3" | "MAT4" | "UINT" | "UVEC2" | "UVEC3" | "UVEC4" | "INT" | "IVEC2" | "IVEC3" | "IVEC4" | "BOOL">, name: H.In<string>, kw: {/** If not zero, indicates that the constant is an array with the specified size. */size?: H.In<number>;- }): any;+ }): H.Ref<void>;/*** Specify a global access constant.* @param type The data type of the constant.@@ -955,7 +955,7 @@ export interface GPUShaderCreateInfo {name: H.In<string>;/** If not zero, indicates that the constant is an array with the specified size. */size?: H.In<number>;- }): any;+ }): H.Ref<void>;/*** Vertex shader source code written in GLSL.*diff --git a/sdk/blender/src/gen/py/idprop_types.ts b/sdk/blender/src/gen/py/idprop_types.tsindex fc3cc32d..03245d80 100644--- a/sdk/blender/src/gen/py/idprop_types.ts+++ b/sdk/blender/src/gen/py/idprop_types.ts@@ -31,7 +31,7 @@ export interface Api {* idprop.types.IDPropertyArray*/export interface IDPropertyArray {- readonly [index: number]: any;+ readonly [index: number]: H.Ref<number | boolean>;/*** Return the array as a list.* @returns The array as a list.@@ -56,8 +56,7 @@ export interface IDPropertyArrayClass {** idprop.types.IDPropertyGroup*/-export interface IDPropertyGroup extends AsyncIterable<any> {- readonly [index: number]: any;+export interface IDPropertyGroup extends AsyncIterable<string> {/*** Remove an item from the group, returning a Python representation.*diff --git a/sdk/blender/src/gen/rna/B.ts b/sdk/blender/src/gen/rna/B.tsindex 656ec009..38ff4c97 100644--- a/sdk/blender/src/gen/rna/B.ts+++ b/sdk/blender/src/gen/rna/B.ts@@ -1743,7 +1743,7 @@ export interface BlendDataLibraries {fake_user?: H.In<boolean>;/** When True, write a compressed blend file. */compress?: H.In<boolean>;- }): any;+ }): H.Ref<void>;/*** Write data-blocks into a blend file.*@@ -1770,7 +1770,7 @@ export interface BlendDataLibraries {fake_user?: H.In<boolean>;/** When True, write a compressed blend file. */compress?: H.In<boolean>;- }): any;+ }): H.Ref<void>;}/**@@ -4031,7 +4031,7 @@ export interface BoneCollection extends R.bpy_struct {bone: R.AnyType;}): H.Ref<boolean>;/** A set of all bones assigned to this bone collection and its child collections. */- get bones_recursive(): any;+ get bones_recursive(): H.Ref<Set<any>>;}/**diff --git a/sdk/blender/src/gen/rna/C.ts b/sdk/blender/src/gen/rna/C.tsindex 05f6cd27..cdefefdb 100644--- a/sdk/blender/src/gen/rna/C.ts+++ b/sdk/blender/src/gen/rna/C.ts@@ -6075,7 +6075,7 @@ export interface CyclesPreferences extends R.AddonPreferences {*/get kernel_optimization_level(): H.Ref<"OFF" | "INTERSECT" | "FULL">;set kernel_optimization_level(v: H.In<"OFF" | "INTERSECT" | "FULL">);- default_device(): any;+ default_device(): H.Ref<number>;draw(context: any): H.Ref<void>;draw(kw: { context: any }): H.Ref<void>;draw_impl(layout: any, context: any): H.Ref<void>;@@ -6085,18 +6085,18 @@ export interface CyclesPreferences extends R.AddonPreferences {get_compute_device_type(): any;get_device_list(compute_device_type: any): any;get_device_list(kw: { compute_device_type: any }): any;- get_device_types(context: any): any;- get_device_types(kw: { context: any }): any;+ get_device_types(context: any): H.Ref<any[][]>;+ get_device_types(kw: { context: any }): H.Ref<any[][]>;get_devices(compute_device_type?: string): H.Ref<void>;get_devices(kw: { compute_device_type?: string }): H.Ref<void>;- get_devices_for_type(compute_device_type: any, device_list?: any): any;- get_devices_for_type(compute_device_type: any, kw: { device_list?: any }): any;- get_devices_for_type(kw: { compute_device_type: any; device_list?: any }): any;- get_num_gpu_devices(): any;- has_active_device(): any;- has_multi_device(): any;- has_oidn_gpu_devices(): any;- has_optixdenoiser_gpu_devices(): any;+ get_devices_for_type(compute_device_type: any, device_list?: any): H.Ref<any[]>;+ get_devices_for_type(compute_device_type: any, kw: { device_list?: any }): H.Ref<any[]>;+ get_devices_for_type(kw: { compute_device_type: any; device_list?: any }): H.Ref<any[]>;+ get_num_gpu_devices(): H.Ref<number>;+ has_active_device(): H.Ref<boolean>;+ has_multi_device(): H.Ref<boolean>;+ has_oidn_gpu_devices(): H.Ref<boolean>;+ has_optixdenoiser_gpu_devices(): H.Ref<boolean>;refresh_devices(): H.Ref<void>;update_device_entries(device_list: any): H.Ref<void>;update_device_entries(kw: { device_list: any }): H.Ref<void>;diff --git a/sdk/blender/src/gen/rna/E.ts b/sdk/blender/src/gen/rna/E.tsindex d9657db7..c4444a21 100644--- a/sdk/blender/src/gen/rna/E.ts+++ b/sdk/blender/src/gen/rna/E.ts@@ -265,7 +265,7 @@ export interface EditBone extends R.bpy_struct {** .. note:: Takes ``O(len(bones))`` time.*/- get children(): any;+ get children(): H.Ref<any[]>;/*** Align this bone to another by moving its tail and settings its roll* the length of the other bone is not used.diff --git a/sdk/blender/src/gen/rna/M.ts b/sdk/blender/src/gen/rna/M.tsindex 39ad9ab9..958c1c62 100644--- a/sdk/blender/src/gen/rna/M.ts+++ b/sdk/blender/src/gen/rna/M.ts@@ -1426,7 +1426,7 @@ export interface Mesh extends R.ID {count_selected_items(): H.Arr<number>;/** Edge crease values for subdivision surface, corresponding to the "crease_edge" attribute. */get edge_creases(): any;- get edge_keys(): any;+ get edge_keys(): H.Ref<any[]>;/** Vertex crease values for subdivision surface, corresponding to the "crease_vert" attribute. */get vertex_creases(): any;/** Mask values for sculpting and painting, corresponding to the ".sculpt_mask" attribute. */@@ -1847,7 +1847,7 @@ export interface MeshLoopTriangle extends R.bpy_struct {get use_smooth(): H.Ref<boolean>;/** The midpoint of the face. */get center(): any;- get edge_keys(): any;+ get edge_keys(): H.Ref<any[]>;}/**@@ -1926,7 +1926,7 @@ export interface MeshPolygon extends R.bpy_struct {get index(): H.Ref<number>;/** Invert winding of this face (flip its normal) */flip(): H.Ref<void>;- get edge_keys(): any;+ get edge_keys(): H.Ref<any[]>;get loop_indices(): any;}diff --git a/sdk/blender/src/gen/rna/P.ts b/sdk/blender/src/gen/rna/P.tsindex b22b1ca0..4b4cbaf7 100644--- a/sdk/blender/src/gen/rna/P.ts+++ b/sdk/blender/src/gen/rna/P.ts@@ -2318,7 +2318,7 @@ export interface PoseBone extends R.bpy_struct {/** Apply roll and curve offsets from bone properties */offsets?: H.In<boolean>;}): H.Ref<[M.Vector, number, M.Vector, number]>;- get children(): any;+ get children(): H.Ref<any[]>;}/**diff --git a/sdk/blender/test/returns.test.ts b/sdk/blender/test/returns.test.tsnew file mode 100644index 00000000..ae4ee0a5--- /dev/null+++ b/sdk/blender/test/returns.test.ts@@ -0,0 +1,113 @@+// BL22: what tools/returns.py reads from a Python function's own source (the type dump.py gives a function or property+// written in Python that its docstring doesn't type), against small cases and against what Blender gives: every+// Python property and query it types on live meshes, bone collections and Cycles' preferences is read in Blender, and+// its value must be that Python type.+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { join } from "node:path";+import { findBlender, start, type Blender } from "../src";++const has = findBlender() !== null;+let b: Blender;+beforeAll(async () => {+ if (has) b = await start();+});+afterAll(async () => {+ await b?.close();+});++const TOOLS = join(import.meta.dir, "../tools");+const READER = `+import sys+sys.path.insert(0, ${JSON.stringify(TOOLS)})+from returns import returns+`;++// source -> what the reader gives (null: it can't tell, so gen leaves any)+const CASES: [string, string | null][] = [+ ["def f(x):\n return x > 1\n", "bool"],+ ["def f(x):\n if x:\n return 'a'\n", "str | None"],+ ["def f(x):\n if x:\n return 'a'\n else:\n return f'{x}'\n", "str"],+ ["def f(x):\n return x\n", null],+ ["def f():\n out = []\n out.append(1)\n return out\n", "list"],+ ["def f():\n n = 0\n for i in range(3):\n n += 1\n return n\n", "int"],+ ["def f():\n def g():\n return 1\n print(g())\n", "None"],+ ["def f():\n yield 1\n", null],+ ["def f(a):\n return (a, 1)\n", "tuple"],+ ["def f():\n return (1, 'a')\n", "tuple[int, str]"],+ ["def f():\n return ', '.join(['a'])\n", "str"],+ ["def f(len):\n return len(3)\n", null],+ ["def f(x):\n while True:\n if x:\n return 1\n", "int"],+ ["def f(x):\n try:\n return 1\n except Exception:\n return None\n", "int | None"],+ ["def f(x):\n a, b = x\n return a\n", null],+ ["def f():\n x = 1\n x = 'a'\n return x\n", null],+ ["def f():\n return 1 / 2\n", "float"],+ ["import functools\[email protected]\ndef f():\n return 1\n", null],+];++const LIVE = `${READER}+import bpy, inspect+PY = {"bool": bool, "int": int, "float": float, "str": str, "bytes": bytes, "list": list, "tuple": tuple, "dict": dict, "set": set}+def ok(t, v):+ alts = [a.strip() for a in t.split(" | ")]+ if len(alts) > 1:+ return any(ok(a, v) for a in alts)+ if t == "None":+ return v is None+ kind, _, inner = t.partition("[")+ if not isinstance(v, PY[kind]) or (kind == "int" and isinstance(v, bool)):+ return False+ if not inner:+ return True+ items = [x.strip() for x in inner[:-1].split(",")]+ if kind == "tuple":+ return len(v) == len(items) and all(ok(i, x) for i, x in zip(items, v))+ return all(ok(items[0], x) for x in v)+me = bpy.data.meshes.new("returns-probe")+me.from_pydata([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [], [(0, 1, 2, 3)])+me.calc_loop_triangles()+arm = bpy.data.armatures.new("returns-probe")+bones = arm.collections.new("c")+cycles = bpy.context.preferences.addons["cycles"].preferences+live = [me, me.polygons[0], me.loop_triangles[0], me.edges[0], bones]+result = []+for o in live:+ for name, a in vars(type(o)).items():+ t = returns(a.fget) if isinstance(a, property) and a.fget else None+ if t:+ result.append([type(o).__name__, name, t, ok(t, getattr(o, name)), repr(getattr(o, name))[:60]])+# queries: no arguments past self, nothing set+for name in ("has_active_device", "has_multi_device", "get_num_gpu_devices", "default_device"):+ f = getattr(type(cycles), name)+ t = returns(getattr(f, "__func__", f))+ v = getattr(cycles, name)()+ result.append(["CyclesPreferences", name, t or "?", bool(t) and ok(t, v), repr(v)[:60]])+bpy.data.meshes.remove(me)+bpy.data.armatures.remove(arm)+`;++describe.skipIf(!has)("Python members typed from their own source", () => {+ test("the reader types what a source shows and leaves the rest", async () => {+ const got = await b.py.exec<(string | null)[]>(+ `${READER}+import linecache+def read(i, src):+ name = "<returns case %d>" % i+ linecache.cache[name] = (len(src), None, src.splitlines(True), name)+ ns = {}+ exec(compile(src, name, "exec"), ns)+ return returns(ns["f"])+result = [read(i, s) for i, s in enumerate(cases)]`,+ { cases: CASES.map((c) => c[0]) },+ );+ expect(got).toEqual(CASES.map((c) => c[1]));+ });++ test("each typed member reads as that Python type in Blender", async () => {+ const rows = await b.py.exec<[string, string, string, boolean, string][]>(LIVE);+ const wrong = rows.filter((r) => !r[3]).map(([cls, name, t, , v]) => `${cls}.${name}: typed ${t}, Blender gives ${v}`);+ expect(wrong).toEqual([]);+ expect(rows.map((r) => `${r[0]}.${r[1]}`)).toEqual(+ expect.arrayContaining(["Mesh.edge_keys", "MeshPolygon.edge_keys", "MeshLoopTriangle.edge_keys", "BoneCollection.bones_recursive", "CyclesPreferences.has_active_device"]),+ );+ });+});diff --git a/sdk/blender/tools/cret.json b/sdk/blender/tools/cret.jsonindex 648e5e98..9a16ee12 100644--- a/sdk/blender/tools/cret.json+++ b/sdk/blender/tools/cret.json@@ -48,6 +48,7 @@"vert_splice": "None"},"getters": {+ "__doc__": "str","hide": "bool","index": "int","is_boundary": "bool",@@ -96,6 +97,7 @@"depth_mask_set": "None","depth_test_get": "str","depth_test_set": "None",+ "depth_write": "None","device_type_get": "str","dispatch": "None","draw": "None",@@ -108,6 +110,7 @@"face_culling_set": "None","filter_mode": "None","flat": "None",+ "fragment_out": "None","fragment_source": "None","free": "None","front_facing_set": "None",@@ -145,6 +148,7 @@"program_point_size_set": "None","program_set": "None","push": "None",+ "push_constant": "None","push_projection": "None","renderer_get": "str","reset": "None",@@ -161,6 +165,7 @@"uniform_block": "None","uniform_block_from_name": "int","uniform_bool": "None",+ "uniform_buf": "None","uniform_float": "None","uniform_from_name": "int","uniform_int": "None",@@ -196,6 +201,7 @@"conjugate": "None","determinant": "float","distance_point_to_plane": "float",+ "dot": "float","fractal": "float","hetero_terrain": "float","hybrid_multi_fractal": "float",@@ -305,6 +311,7 @@"driver_remove": "bool","file_path_foreach": "None","find": "int",+ "help_text": "str","id_free_weakref_cb": "None","id_properties_clear": "None","idname": "str",@@ -327,6 +334,7 @@"property_overridable_library_set": "bool","property_unset": "None","publish_rna": "None",+ "region_as_string": "str","region_from_string": "None","register": "None","register_class": "None",@@ -335,10 +343,13 @@"subscribe_rna": "None","target_set_handler": "None","target_set_value": "None",+ "to_string": "str",+ "to_value": "float","unregister": "None","unregister_class": "None","unregister_cli_command": "None",- "update": "None"+ "update": "None",+ "write": "None"},"getters": {"autoexec_fail": "bool",diff --git a/sdk/blender/tools/dump.py b/sdk/blender/tools/dump.pyindex d9f65ab0..636dcc01 100644--- a/sdk/blender/tools/dump.py+++ b/sdk/blender/tools/dump.py@@ -16,6 +16,7 @@ import _rna_info as rna_infosys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))from refine import refine # noqa: E402 (beside this file)+from returns import returns # noqa: E402def prop(p):@@ -124,11 +125,21 @@ def returns_none(fn):def written(fn, d):"""Marks a function written in Python (`py`: what it returns is read from its own source, never tools/cret.json's- reading of C), and `none` when that source returns no value."""+ reading of C): `none` when that source returns no value, else `ret`, the type its returns show (tools/returns.py)."""if inspect.isfunction(fn):d["py"] = Trueif returns_none(fn):d["none"] = True+ else:+ shown(fn, d)+ return d+++def shown(fget, d):+ """`ret`: the type a Python function or property getter's own returns show, when they show one."""+ t = returns(fget) if inspect.isfunction(fget) else None+ if t and t != "None":+ d["ret"] = treturn d@@ -153,7 +164,7 @@ def struct(s):pyprops = []for name, attr in s.get_py_properties():if name in s.py_class.__dict__:- pyprops.append({"id": name, "doc": doc(attr), "ro": attr.fset is None})+ pyprops.append(shown(attr.fget, {"id": name, "doc": doc(attr), "ro": attr.fset is None}))pyfuncs = [pyfunc(n, py.__dict__.get(n, a)) for n, a in s.get_py_functions() if n in py.__dict__]cfuncs = [{"id": n, "doc": doc(a)} for n, a in s.get_py_c_functions() if n in py.__dict__]if pyprops:@@ -187,6 +198,7 @@ def member(name, obj, depth):m["value"] = value(a)if kind == "property" and isinstance(a, property):m["ro"] = a.fset is None+ shown(a.fget, m)own.append(m)bases = [b.__module__ + "." + b.__qualname__ for b in obj.__bases__ if b is not object]return {"id": name, "kind": "class", "doc": doc(obj), "sig": sig(obj), "bases": bases, "members": own}@@ -195,10 +207,24 @@ def member(name, obj, depth):return {"id": name, "kind": "data", "type": type(obj).__name__, "value": value(obj), "doc": ""}+STDLIB = sys.stdlib_module_names - {"builtins"} # Blender's C types say "builtins"+++def python_own(obj):+ """Python's own, imported into a Blender module (bpy_extras.anim_utils): a typing alias (FCurveKey =+ tuple[float, float], Iterable), or a class or function of the standard library (Mapping, dataclass)."""+ if isinstance(obj, (types.GenericAlias, types.UnionType)) or type(obj).__module__ == "typing":+ return True+ named = inspect.isclass(obj) or inspect.isfunction(obj)+ return named and (getattr(obj, "__module__", None) or "").split(".")[0] in STDLIB++def members(mod, depth=0):out = []+ # a private class the module's functions say they return is part of its API (bpy.props' _PropertyDeferred)+ said = {n for f in vars(mod).values() if callable(f) for n in re.findall(r":rtype: :class:`(_[A-Za-z]\w*)`", doc(f))}for name in sorted(dir(mod)):- if name.startswith("_"):+ if name.startswith("_") and name not in said:continuetry:obj = getattr(mod, name)@@ -206,6 +232,8 @@ def members(mod, depth=0):continueif isinstance(obj, types.ModuleType) and not obj.__name__.startswith(getattr(mod, "__name__", "")):continue # an import, not a submodule+ if python_own(obj):+ continueout.append(member(name, obj, depth))return outdiff --git a/sdk/blender/tools/gen/cret.ts b/sdk/blender/tools/gen/cret.tsindex 510c2558..7ac70aa9 100644--- a/sdk/blender/tools/gen/cret.ts+++ b/sdk/blender/tools/gen/cret.ts@@ -55,27 +55,38 @@ function value(v: string): string {return /^(nullptr|NULL|0)?$/.test(v) ? "" : UNKNOWN;}// a C function's body: the one type all its returns give-const BODY = /^(?:static\s+)?PyObject\s*\*\s*(\w+)\s*\([^)]*\)\s*\{([\s\S]*?)^\}/gm;+const BODY = /^(?:static\s+)?PyObject\s*\*\s*(\w+)\s*\(([^)]*)\)\s*\{([\s\S]*?)^\}/gm;const RET = /\bPy_RETURN_(NONE|TRUE|FALSE)\b|\breturn\b([^;]*);/g;-function kindOf(body: string): string {+function kindOf(params: string, body: string): string {const kinds = new Set<string>();for (const m of body.matchAll(RET)) {- const k = m[1] ? (m[1] === "NONE" ? "None" : "bool") : value((m[2] ?? "").trim());+ const v = (m[2] ?? "").trim();+ const k = m[1] ? (m[1] === "NONE" ? "None" : "bool") : /^\w+$/.test(v) && value(v) === UNKNOWN ? local(params, body, v) : value(v);if (k) kinds.add(k);}return kinds.size === 1 ? [...kinds][0] : UNKNOWN;}+// a local the function returns (`ret = Py_None;` ... `return ret;`, libraries.write): what all its assignments give;+// unknown for a parameter, or one whose address is passed (something else may set it)+function local(params: string, body: string, name: string): string {+ if (new RegExp(`\\b${name}\\b`).test(params) || new RegExp(`&\\s*${name}\\b`).test(body)) return UNKNOWN;+ const kinds = new Set<string>();+ for (const a of body.matchAll(new RegExp(`(?<![\\w.>])${name}\\s*=(?!=)\\s*([^;]*);`, "g"))) kinds.add(value(a[1].trim()));+ kinds.delete(""); // nullptr: an error+ return kinds.size === 1 ? [...kinds][0] : UNKNOWN;+}// a method or property entry, in a table or a definition of its own: the Python name, the C function (the getter),-// however it's cast, and the rest, where a method has its METH_ flags; any other entry is taken as a property's-// (a name some other kind of table also has only disagrees, and is left unknown)-const ENTRY = /\{\s*(?:\(char\s*\*\)\s*)?"(\w+)"\s*,\s*(?:\w+_cast<[^>]+>\(\s*(\w+)\s*\)|\(\s*\w+\s*\)\s*(?:\(\s*void\s*\*\s*\)\s*)?(\w+)|(\w+))([^}]*)\}/g;+// however it's cast (gpu.types.GPUShaderCreateInfo's `(PyCFunction)(void *)(name)` too), and the rest, where a method+// has its METH_ flags; any other entry is taken as a property's (a name some other kind of table also has only+// disagrees, and is left unknown)+const ENTRY = /\{\s*(?:\(char\s*\*\)\s*)?"(\w+)"\s*,\s*(?:\w+_cast<[^>]+>\(\s*(\w+)\s*\)|\(\s*\w+\s*\)\s*(?:\(\s*void\s*\*\s*\)\s*)?\(?\s*(\w+)\s*\)?|(\w+))([^}]*)\}/g;type Family = { methods: Record<string, string>; getters: Record<string, string> };const result: Record<string, Family> = {};for (const [family, dir] of Object.entries(FAMILIES)) {const files = sources(join(root, dir));const kinds = new Map<string, string>();- for (const src of files) for (const m of src.matchAll(BODY)) kinds.set(m[1], kindOf(m[2]));+ for (const src of files) for (const m of src.matchAll(BODY)) kinds.set(m[1], kindOf(m[2], m[3]));const methods = new Map<string, Set<string>>();const getters = new Map<string, Set<string>>();for (const src of files) {diff --git a/sdk/blender/tools/gen/dump.ts b/sdk/blender/tools/gen/dump.tsindex 9c0e0188..5f5a15aa 100644--- a/sdk/blender/tools/gen/dump.ts+++ b/sdk/blender/tools/gen/dump.ts@@ -64,7 +64,8 @@ export interface Struct {props: Prop[];funcs: Func[];nested?: string;- pyprops?: { id: string; doc: string; ro: boolean }[];+ /** ret: what the getter's own source returns (tools/returns.py), where its docstring has no :type: */+ pyprops?: { id: string; doc: string; ro: boolean; ret?: string }[];pyfuncs?: { id: string; sig: string | null; doc: string; static: boolean; py?: boolean; none?: boolean; ret?: string }[];cfuncs?: { id: string; doc: string; none?: boolean; ret?: string }[];}diff --git a/sdk/blender/tools/gen/pymod.ts b/sdk/blender/tools/gen/pymod.tsindex a147fa80..3895d800 100644--- a/sdk/blender/tools/gen/pymod.ts+++ b/sdk/blender/tools/gen/pymod.ts@@ -28,6 +28,32 @@ function propertyMember(m: PyMember, n: Names, self: string, mod: string): strinconst dataMember = (m: PyMember): string => `${jsdoc(m.doc || (m.value ? `= ${m.value}` : ""))} readonly ${key(m.id)}: H.Ref<${PYTYPE[m.type ?? ""] ?? "any"}>;`;+/**+ * What a class's `[i]` (`at`) and iteration (`each`) give where its name doesn't say (BMVertSeq's are BMVert's), as+ * Blender 5.2's C gives them. `at` null: its `[]` takes no number (BMVert[layer], IDPropertyGroup["name"] through `$`).+ * gpu.types.Buffer stays any: its item is a number or, in a buffer of more dimensions, a Buffer.+ */+const ELEM = "P.bmesh_types.BMVert | P.bmesh_types.BMEdge | P.bmesh_types.BMFace";+const ITEMS: Record<string, { at: string | null; each: string }> = {+ // bmesh_py_types_select.cc bpy_bmeditselseq_subscript_int: the history's vertex, edge or face+ "bmesh.types.BMEditSelSeq": { at: `H.Ptr<${ELEM}>`, each: ELEM },+ // bmesh_py_types.cc bpy_bmelemseq_subscript_int: BPy_BMElem_CreatePyObject, any element (a face's loops too)+ "bmesh.types.BMElemSeq": { at: `H.Ptr<${ELEM} | P.bmesh_types.BMLoop>`, each: `${ELEM} | P.bmesh_types.BMLoop` },+ // bmesh_py_types_customdata.cc: subscript_int and iter give BMLayerItems+ "bmesh.types.BMLayerCollection": { at: "H.Ptr<P.bmesh_types.BMLayerItem>", each: "P.bmesh_types.BMLayerItem" },+ // bmesh_py_types_meshdata.cc bpy_bmdeformvert_subscript: a vertex group's weight+ "bmesh.types.BMDeformVert": { at: "H.Ref<number>", each: "any" },+ // bmesh_py_types.cc bpy_bmelem_subscript: keyed by a BMLayerItem+ "bmesh.types.BMVert": { at: null, each: "any" },+ "bmesh.types.BMEdge": { at: null, each: "any" },+ "bmesh.types.BMFace": { at: null, each: "any" },+ "bmesh.types.BMLoop": { at: null, each: "any" },+ // idprop_py_api.cc BPy_IDArray_GetItem: float, double, int or bool+ "idprop.types.IDPropertyArray": { at: "H.Ref<number | boolean>", each: "number | boolean" },+ // idprop_py_api.cc: a group is keyed by name (BPy_IDGroup_Map_GetItem), and iterates its keys (BPy_IDGroup_iter)+ "idprop.types.IDPropertyGroup": { at: null, each: "string" },+};+/** A class: its instance interface and its class interface (Name, NameClass). */function emitClass(c: PyMember, mod: string, n: Names, classes: Set<string>): string {const self = n.py.get(`${mod}.${c.id}`)!;@@ -40,15 +66,18 @@ function emitClass(c: PyMember, mod: string, n: Names, classes: Set<string>): stif (t?.kind === "obj" && t.ts.startsWith("P.")) ext.push(t.ts);}const elemName = c.id.endsWith("Seq") ? c.id.slice(0, -3) : null;- const elem = elemName && classes.has(elemName) ? elemName : null;+ const named = elemName && classes.has(elemName) ? elemName : null;+ const items = ITEMS[`${mod}.${c.id}`];+ const at = items ? items.at : named ? `H.Ptr<${named}>` : "any";+ const each = items ? items.each : named ?? "any";for (const m of c.members ?? []) {if (m.id === "__init__" || m.id === "__len__") continue;if (m.id === "__getitem__") {- inst.push(` readonly [index: number]: ${elem ? `H.Ptr<${elem}>` : "any"};`);+ if (at) inst.push(` readonly [index: number]: ${at};`);continue;}if (m.id === "__iter__") {- ext.push(`AsyncIterable<${elem ?? "any"}>`);+ ext.push(`AsyncIterable<${each}>`);continue;}if (m.id === "__call__") {diff --git a/sdk/blender/tools/gen/rna.ts b/sdk/blender/tools/gen/rna.tsindex 2c9c360f..704e58e9 100644--- a/sdk/blender/tools/gen/rna.ts+++ b/sdk/blender/tools/gen/rna.ts@@ -127,9 +127,11 @@ function pyMembers(s: Struct, n: Names, skip: Set<string>): string[] {for (const p of s.pyprops ?? []) {if (skip.has(p.id)) continue;const d = readDoc(p.doc);- const t = d.type ? pyType(d.type, { names: n, role: "out", self }) : { ts: "any", kind: "any" as const };+ // no :type:: what the getter's own source returns (tools/returns.py), else any+ const type = d.type ?? p.ret;+ const t = type ? pyType(type, { names: n, role: "out", self }) : { ts: "any", kind: "any" as const };const get = `${jsdoc(d.text)} get ${key(p.id)}(): ${direct(t)};`;- out.push(p.ro ? get : `${get}\n set ${key(p.id)}(v: ${d.type ? input(pyType(d.type, { names: n, role: "in", self })) : "any"});`);+ out.push(p.ro ? get : `${get}\n set ${key(p.id)}(v: ${type ? input(pyType(type, { names: n, role: "in", self })) : "any"});`);}for (const f of [...(s.pyfuncs ?? []), ...(s.cfuncs ?? []).map((c) => ({ ...c, sig: null, static: false }))]) {if (skip.has(f.id)) continue;diff --git a/sdk/blender/tools/returns.py b/sdk/blender/tools/returns.pynew file mode 100644index 00000000..dce69520--- /dev/null+++ b/sdk/blender/tools/returns.py@@ -0,0 +1,206 @@+# What a function written in Python returns, read from its own source (BL22), for dump.py: "None" when no path+# returns a value, a Python type (bool, str, list[str], tuple[int, int] | None, ...) when every `return` gives one its+# expression shows, else nothing, and gen leaves it any. Only what the source shows for certain: a value passed in, a+# call to another function, an attribute or a subscript is unknown, and one unknown return leaves the whole function so.+import ast+import inspect+import textwrap++# builtins whose result's type doesn't depend on their arguments+CALLS = {"bool": "bool", "int": "int", "float": "float", "str": "str", "repr": "str", "len": "int", "isinstance": "bool",+ "issubclass": "bool", "hasattr": "bool", "callable": "bool", "any": "bool", "all": "bool", "list": "list",+ "tuple": "tuple", "dict": "dict", "set": "set", "frozenset": "set", "sorted": "list", "chr": "str", "ord": "int"}+# str's methods that give a str, called on a string the source writes+STR = {"join", "format", "replace", "strip", "lstrip", "rstrip", "lower", "upper", "title", "capitalize", "casefold"}+# os.path's functions, by their result+OSPATH = {"join": "str", "basename": "str", "dirname": "str", "abspath": "str", "normpath": "str", "realpath": "str",+ "expanduser": "str", "relpath": "str", "exists": "bool", "isfile": "bool", "isdir": "bool", "isabs": "bool"}+SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)+WRAPPERS = {"staticmethod", "classmethod", "property"}+++def join(a, b):+ """One type for two a name or the returns can give, or None where they don't agree."""+ if a == b:+ return a+ if {a, b} == {"int", "float"}:+ return "float"+ for kind in ("list", "tuple", "dict", "set"):+ if a.split("[")[0] == kind and b.split("[")[0] == kind:+ return kind+ return None+++def own(body):+ """Every node of a function body, leaving out nested functions and classes (their names and returns are theirs)."""+ todo = list(body)+ while todo:+ node = todo.pop()+ yield node+ if not isinstance(node, SCOPES):+ todo.extend(ast.iter_child_nodes(node))+++class Reader:+ def __init__(self, fn):+ self.binds = {} # name -> the expressions bound to it (None: bound some way the source can't type)+ for a in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs + [fn.args.vararg, fn.args.kwarg]:+ if a is not None:+ self.binds.setdefault(a.arg, []).append(None)+ for node in own(fn.body):+ if isinstance(node, ast.Assign):+ for t in node.targets:+ self.bind(t, node.value)+ elif isinstance(node, (ast.AnnAssign, ast.AugAssign)):+ self.bind(node.target, node.value if isinstance(node, ast.AnnAssign) else node)+ elif isinstance(node, ast.NamedExpr):+ self.bind(node.target, node.value)+ elif isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)):+ self.bind(node.target, None)+ elif isinstance(node, ast.withitem) and node.optional_vars is not None:+ self.bind(node.optional_vars, None)+ elif isinstance(node, ast.ExceptHandler) and node.name:+ self.binds.setdefault(node.name, []).append(None)+ elif isinstance(node, (ast.Import, ast.ImportFrom)):+ for a in node.names:+ self.binds.setdefault((a.asname or a.name).split(".")[0], []).append(None)+ elif isinstance(node, (ast.Global, ast.Nonlocal)):+ for name in node.names:+ self.binds.setdefault(name, []).append(None)+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ self.binds.setdefault(node.name, []).append(None)+ self.busy = set()++ def bind(self, target, value):+ if isinstance(target, ast.Name):+ self.binds.setdefault(target.id, []).append(value)+ else: # a, b = ...; x.y = ...; x[i] = ...: names inside are bound some way we don't type+ for n in ast.walk(target):+ if isinstance(n, ast.Name):+ self.binds.setdefault(n.id, []).append(None)++ def name(self, id):+ if id not in self.binds or id in self.busy:+ return None # a global, or a name whose type depends on itself+ self.busy.add(id)+ try:+ out = None+ for v in self.binds[id]:+ t = self.aug(v) if isinstance(v, ast.AugAssign) else self.type(v)+ out = t if out is None else join(out, t) if t else None+ if out is None:+ return None+ return out+ finally:+ self.busy.discard(id)++ def aug(self, node):+ # x += y keeps x's type when y's is the same kind (counts, strings, lists)+ t = self.type(node.value)+ return t if t in ("int", "float", "str") or (t or "").startswith(("list", "tuple")) else None++ def type(self, e):+ if e is None:+ return None+ if isinstance(e, ast.Constant):+ v = e.value+ return ("bool" if isinstance(v, bool) else "int" if isinstance(v, int) else "float" if isinstance(v, float)+ else "str" if isinstance(v, str) else "bytes" if isinstance(v, bytes) else "None" if v is None else None)+ if isinstance(e, ast.JoinedStr):+ return "str"+ if isinstance(e, ast.Compare) or (isinstance(e, ast.UnaryOp) and isinstance(e.op, ast.Not)):+ return "bool"+ if isinstance(e, ast.UnaryOp):+ t = self.type(e.operand)+ return t if t in ("int", "float") else None+ if isinstance(e, ast.BoolOp): # `a and b` gives one of its operands+ ts = [self.type(v) for v in e.values]+ return ts[0] if None not in ts and len(set(ts)) == 1 else None+ if isinstance(e, ast.IfExp):+ a, b = self.type(e.body), self.type(e.orelse)+ return join(a, b) if a and b else None+ if isinstance(e, ast.BinOp):+ a, b = self.type(e.left), self.type(e.right)+ if a in ("int", "float") and b in ("int", "float"):+ return "float" if isinstance(e.op, ast.Div) else join(a, b)+ if a == "str" and (b == "str" or isinstance(e.op, ast.Mod)):+ return "str"+ return None+ if isinstance(e, ast.Name):+ return self.name(e.id)+ if isinstance(e, (ast.List, ast.Set)):+ kind = "list" if isinstance(e, ast.List) else "set"+ ts = {self.type(x) for x in e.elts}+ return f"{kind}[{ts.pop()}]" if len(ts) == 1 and None not in ts and "None" not in ts else kind+ if isinstance(e, ast.ListComp):+ t = self.type(e.elt)+ return f"list[{t}]" if t and t != "None" else "list"+ if isinstance(e, (ast.SetComp, ast.Dict, ast.DictComp)):+ return "set" if isinstance(e, ast.SetComp) else "dict"+ if isinstance(e, ast.Tuple):+ ts = [self.type(x) for x in e.elts]+ return f"tuple[{', '.join(ts)}]" if ts and None not in ts and "None" not in ts else "tuple"+ if isinstance(e, ast.Call):+ f = e.func+ if isinstance(f, ast.Name) and f.id in CALLS and f.id not in self.binds:+ return CALLS[f.id]+ if isinstance(f, ast.Attribute):+ if f.attr in STR and self.type(f.value) == "str":+ return "str"+ if (isinstance(f.value, ast.Attribute) and f.value.attr == "path" and isinstance(f.value.value, ast.Name)+ and f.value.value.id == "os" and f.attr in OSPATH):+ return OSPATH[f.attr]+ return None+++def falls_through(stmts):+ """True when control can reach the end of these statements (and so the function return None there)."""+ if not stmts:+ return True+ last = stmts[-1]+ if isinstance(last, (ast.Return, ast.Raise)):+ return False+ if isinstance(last, ast.If):+ return falls_through(last.body) or falls_through(last.orelse)+ if isinstance(last, (ast.With, ast.AsyncWith)):+ return falls_through(last.body)+ if isinstance(last, ast.Try):+ if last.finalbody and not falls_through(last.finalbody):+ return False+ return falls_through(last.orelse or last.body) or any(falls_through(h.body) for h in last.handlers)+ if isinstance(last, ast.While) and isinstance(last.test, ast.Constant) and last.test.value is True:+ return any(isinstance(n, ast.Break) for n in own(last.body))+ return True+++def returns(fn):+ """What a function written in Python returns, as a Python type, "None", or None when its source doesn't show."""+ try:+ top = ast.parse(textwrap.dedent(inspect.getsource(fn))).body[0]+ except (OSError, TypeError, SyntaxError, IndexError):+ return None+ if not isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef)):+ return None+ deco = {d.id if isinstance(d, ast.Name) else d.attr if isinstance(d, ast.Attribute) else "" for d in top.decorator_list}+ if deco - WRAPPERS or isinstance(top, ast.AsyncFunctionDef):+ return None # a decorator can change what's returned; an async function gives a coroutine+ nodes = list(own(top.body))+ if any(isinstance(n, (ast.Yield, ast.YieldFrom)) for n in nodes):+ return None+ r = Reader(top)+ out, none = None, falls_through(top.body)+ for n in nodes:+ if not isinstance(n, ast.Return):+ continue+ t = "None" if n.value is None else r.type(n.value)+ if t is None:+ return None+ if t == "None":+ none = True+ continue+ out = t if out is None else join(out, t)+ if out is None:+ return None+ if out is None:+ return "None" if none else None+ return f"{out} | None" if none else out