@@ -45,7 +45,7 @@ From "can run" to "runs well", from "feature-complete" to "excellent UX".
4545
4646** Philosophy** : ** Generic patterns, not unconstrained generics.**
4747
48- > "泛型如果服务 design patterns,是加分;泛型如果隐藏 cell ownership,是灾难。 "
48+ > "Generics that serve design patterns are valuable; generics that hide cell ownership are disastrous. "
4949
5050** Problem** : 0.12 supports several schema/ABI dynamic vector paths, but runtime
5151collection helpers and cell-backed collection ownership remain intentionally
@@ -108,6 +108,145 @@ CKB/Spora's core is **NOT** account storage or native object packages. It's:
108108- ✅ ** Spora** : AMM/Registry/OrderBook need generic collections
109109- ⚠️ ** CKB raw scripts** : Don't use generics (Rust -> RISC-V handles it)
110110
111+ ** v0.13 Goal** : ** Bounded generics / reusable pattern layer** , NOT full Rust/Sway-style generics.
112+
113+ > "0.13 引入受限泛型,用来复用 CKB 设计模式,但不把 cell-backed / linear ownership 问题偷偷藏进泛型里。"
114+
115+ ** What v0.13 WILL do** (bounded generics):
116+
117+ ** 1. Value-level generics only** (no linear ownership)
118+ ``` cellscript
119+ fn require_eq<T: FixedWidth>(a: T, b: T)
120+ fn contains<T: FixedWidth>(xs: Vec<T>, x: T) -> bool
121+ ```
122+ Supported types:
123+ - ` u8 ` , ` u64 `
124+ - ` Hash `
125+ - ` Address `
126+ - fixed bytes
127+ - simple ABI/schema-backed values
128+
129+ ** DOES NOT support** : ` T: CellBacked ` or ` T: Linear `
130+
131+ ---
132+
133+ ** 2. Phantom-style asset tags** (Move-inspired, CKB-native)
134+ ``` cellscript
135+ resource Token<phantom Asset>
136+ ```
137+ Use cases:
138+ ``` cellscript
139+ Token<USDI>
140+ Token<MyDAO>
141+ Token<LPToken>
142+ ```
143+ Benefits:
144+ - Helps UDT / xUDT / custom asset patterns
145+ - Does NOT require generic runtime collections fully working
146+
147+ ---
148+
149+ ** 3. Generic interfaces / templates** (most valuable for 0.13)
150+ ``` cellscript
151+ interface FungibleToken<Asset>
152+ interface Pool<TokenA, TokenB>
153+ interface Timelock<Asset>
154+ ```
155+ Benefits:
156+ - Directly serves cookbooks / AI-assisted workflows / reusable CKB patterns
157+ - More valuable than generic functions
158+
159+ ---
160+
161+ ** 4. Minimal trait constraints**
162+
163+ ** Allowed in 0.13** (with explicit definitions):
164+
165+ ``` text
166+ FixedWidth: value has statically known ABI width.
167+ Hashable: value has a canonical hash representation.
168+ MoleculeSchema: value has a schema-backed serialization layout.
169+ NonLinear: value does not carry consume/transfer/destroy obligations.
170+ ```
171+
172+ ** Why NonLinear is critical** : It is the safety valve that separates generics from ownership semantics. Without it, ` Vec<T> ` could accidentally become ` Vec<LinearResource<T>> ` , blurring consumption/transfer boundaries.
173+
174+ ** NOT allowed in 0.13** (too risky, drags into ownership/builder verification):
175+ ```
176+ Consumable
177+ CellBacked
178+ Store
179+ ResourceCollection
180+ ```
181+
182+ ---
183+
184+ ** 5. Bounded generic collections**
185+ Allowed in 0.13:
186+ ``` cellscript
187+ Vec<T: FixedWidth>
188+ Option<T: FixedWidth>
189+ ```
190+
191+ ** NOT supported in 0.13** (continue fail-closed or experimental):
192+ ``` cellscript
193+ Vec<Cell<T>>
194+ HashMap<Hash, Token<T>>
195+ Vec<Linear<T>>
196+ HashMap<K, V> // full generic
197+ ```
198+
199+ ---
200+
201+ ** What v0.13 WILL NOT do** :
202+
203+ - ❌ arbitrary generic collections
204+ - ❌ generic linear resources
205+ - ❌ generic cell-backed maps
206+ - ❌ higher-order trait jungle
207+ - ❌ fancy type inference
208+ - ❌ ` T: CellBacked ` / ` T: Linear ` constraints
209+ - ❌ full generic ` HashMap<K, V> `
210+ - ❌ ` Vec<Cell<T>> ` / ` HashMap<Hash, Resource<T>> `
211+
212+ ---
213+
214+ ** 6. Inspectable monomorphization** (MANDATORY - Release Gate)
215+
216+ ** Release gate requirement** :
217+ > 0.13 must expose every generic instantiation in ABI/metadata/constraints output.
218+ > No generic instantiation may silently change witness layout, schema commitment, or lock/type lowering.
219+
220+ ** Core principle** :
221+ > ** We support generics without hiding what they become on-chain.**
222+
223+ ** Mandatory tooling** :
224+ ``` bash
225+ cellc explain-generics # Show what T instantiates to
226+ cellc abi # Show witness ABI changes
227+ cellc constraints # Show code size impact
228+ ```
229+
230+ ** Must expose** :
231+ - What ` T ` was instantiated to
232+ - Which specialized functions were generated
233+ - How witness ABI changed
234+ - How schema hash / ABI hash changed
235+ - How much code size increased
236+ - Which generic instantiations were rejected
237+
238+ ** Otherwise generics will break inspectability** (a core CellScript principle).
239+
240+ ** v0.13 Character** :
241+ > reusable patterns, visible lowering, bounded ownership semantics.
242+
243+ ** Translation** :
244+ > Not "adding generics to show off", but "adding reusable templates for CKB design patterns".
245+
246+ This aligns with AI-assisted workflows / cookbooks: AI needs ** bounded cookbook primitives** , not unrestricted generics.
247+
248+ ---
249+
111250** v0.12 Boundary** (from ` CELLSCRIPT_0_12_COMPREHENSIVE_PLAN.md ` ):
112251> "0.12 does not claim full generic ` HashMap<K, V> ` runtime support."
113252> "Kept generic runtime collection support bounded and explicit."
@@ -119,62 +258,110 @@ CKB/Spora's core is **NOT** account storage or native object packages. It's:
119258- ❌ Cannot return or mutate ` Vec<Resource> ` without a linear collection ownership model
120259- ❌ Cannot claim production support for unsupported generic helpers without fail-closed metadata
121260
122- ** Effort** : 5-7 days
123- ** Risk** : ** HIGH** (see Risk 4 below)
261+ ** Effort** : 7-10 days
262+ ** Risk** : ** HIGH** (but bounded - see strategy below)
124263
125264** Risk Assessment** :
126265
127- ** Risk 4: Generics Monomorphization May Cause Code Bloat** 🔴
266+ ** Risk 4: Generics May Break Cell/Resource Semantics** 🔴
267+
268+ ** Scenario** : Generic collections blur ownership boundaries:
269+ ``` cellscript
270+ // Dangerous: Who owns these cells?
271+ Vec<Cell<T>> → Each cell must be consumed/transferred
272+ HashMap<Hash, Token<T>> → What happens on hash collision?
273+ Option<LinearAsset<T>> → Is the asset consumed when None?
274+ ```
275+
276+ ** Mitigation** : ** Strictly bounded to value-level generics in 0.13**
277+ - ✅ ` Vec<T: FixedWidth> ` - Safe (no ownership)
278+ - ✅ ` Vec<Address> ` , ` Vec<Hash> ` - Safe (value types)
279+ - ❌ ` Vec<Cell<T>> ` - NOT allowed in 0.13
280+ - ❌ ` T: Linear ` constraints - NOT allowed in 0.13
281+
282+ ---
283+
284+ ** Risk 5: Generic Lowering Becomes Opaque** 🔴
128285
129- ** Scenario** : Each type instantiation generates separate code:
286+ ** Scenario** : ` transfer<T>() ` hides too much magic:
287+ - Some ` T ` lowers to lock script
288+ - Some ` T ` lowers to type script
289+ - Some ` T ` depends on builder
290+ - Some ` T ` depends on witness ABI
291+
292+ ** Per discussion with Matt** : "language should not hide too much magic"
293+
294+ ** Mitigation** : ** Mandatory inspectable lowering**
295+ ``` bash
296+ cellc explain-generics # Show exactly what T lowers to
297+ cellc abi # Show witness ABI changes
298+ ```
299+
300+ ---
301+
302+ ** Risk 6: Codegen/ABI Explosion** 🔴
303+
304+ ** Scenario** : Monomorphization creates too many specialized versions:
130305``` cellscript
131- Vec<Address> → generates vec_address_push/pop/len
132- Vec<Token> → generates vec_token_push/pop/len
133- Vec<Signature> → generates vec_signature_push/pop/len
306+ Vec<Address> → vec_address_push/pop/len
307+ Vec<Token> → vec_token_push/pop/len
308+ Vec<Signature> → vec_signature_push/pop/len
309+ Vec<Pool> → vec_pool_push/pop/len
310+ ...
134311```
135312
136- ** Potential Impact** :
313+ ** Impact** :
137314- ELF size increase: 2-3x per type instantiation
138315- Compile time increase: 1.5-2x
139316- Audit difficulty: Each monomorphized instance needs verification
317+ - ** Recent branch relaxation/codegen bloat issue (Jan's review) shows this risk is real**
140318
141- ** Mitigation Strategy** :
142- 1 . ** Monomorphize only actually used types** (not all possible types)
143- 2 . ** Use DCE to eliminate unused instances** (v0.13 P1 feature #6 )
144- 3 . ** Set monomorphization count limit** (warn at 5, fail at 10)
145- 4 . ** Consider runtime type erasure** for simple operations (push/pop/len)
146- - Store as ` Vec<u8> ` + type metadata
147- - Only specialize on access (get/set)
319+ ** Mitigation** :
320+ 1 . ** Minimal trait constraints** (only 4 in 0.13: FixedWidth, Hashable, MoleculeSchema, NonLinear)
321+ 2 . ** Monomorphize only actually used types** (not all possible types)
322+ 3 . ** Use DCE to eliminate unused instances** (v0.13 P1 feature #6 )
323+ 4 . ** Set monomorphization count limit** (warn at 5, fail at 10)
324+ 5 . ** Consider type-erased collections** for simple operations (push/pop/len)
148325
149- ** Alternative Approach** (Lower Risk):
150- - Implement ** type-erased collections** first (lower performance, smaller code)
151- - Add monomorphization later as optimization (if needed)
326+ ---
152327
153- ** Type-Erased Approach Example** :
154- ``` cellscript
155- // Store all as Vec<u8> with type metadata
156- struct VecAny {
157- type_tag: u8, // 0=Address, 1=Token, 2=Signature...
158- element_size: u16, // Size of each element
159- data: Vec<u8>, // Raw bytes
160- }
328+ ** Risk 7: Ecosystem Standardizes Too Early** 🟡
161329
162- // Operations work on raw bytes
163- fn vec_any_push(vec: &mut VecAny, element: &[u8]);
164- fn vec_any_get(vec: &VecAny, index: usize) -> &[u8];
165- ```
330+ ** Scenario** : If 0.13 claims "generic collections supported", it becomes a promise that's hard to change.
331+
332+ ** Mitigation** : ** Clear boundary documentation**
333+ - ✅ Document what's supported: ` Vec<T: FixedWidth> ` , ` Option<T: FixedWidth> `
334+ - ✅ Document what's NOT supported: ` Vec<Cell<T>> ` , ` HashMap<K, V> `
335+ - ✅ Continue fail-closed for unsupported generic patterns
336+ - ✅ Explicit metadata for bounded generic support
337+
338+ ---
339+
340+ ** Phased Approach** (Recommended):
341+
342+ ** Phase 1 (v0.13)** : Value-level generics only
343+ - ` Vec<T: FixedWidth> ` , ` Option<T: FixedWidth> `
344+ - Phantom-style asset tags (` Token<phantom Asset> ` )
345+ - Generic interfaces/templates (` interface FungibleToken<Asset> ` )
346+ - Minimal trait constraints (FixedWidth, Hashable, MoleculeSchema, NonLinear)
347+
348+ ** Phase 2 (v0.14)** : Interface/package-level generics
349+ - Generic interfaces with more constraints
350+ - Schema-level type parameters
351+ - Move-style phantom types for CKB-native asset patterns
352+
353+ ** Phase 3 (v0.15+)** : Constrained generics with capabilities
354+ - ` T: CellBacked ` (only after ownership model is mature)
355+ - ` T: Consumable ` (only after builder verification is stable)
356+ - ` T: Store ` (only after linear ownership is proven)
166357
167- ** Pros** :
168- - ✅ Single implementation for all types
169- - ✅ Small code size (no monomorphization)
170- - ✅ Fast compilation
358+ ** Phase 4 (Future)** : Linear/cell-backed collection generics
359+ - ` Vec<Cell<T>> ` / ` HashMap<Hash, Resource<T>> `
360+ - Must wait for: ownership model, consume_each, membership proof, builder verification, witness proof
171361
172- ** Cons** :
173- - ⚠️ Runtime type checking overhead
174- - ⚠️ No compile-time type safety
175- - ⚠️ 10-20% slower than monomorphized
362+ ** v0.13 One-Sentence Goal** :
176363
177- ** Recommendation ** : ** Start with type-erased approach for v0.13, measure performance, then decide if monomorphization is needed for v0.14 **
364+ > CellScript 0.13 introduces bounded generics for reusable CKB design patterns, while keeping linear/cell-backed ownership explicit and fail-closed.
178365
179366---
180367
0 commit comments