nim-ownership-hooks
Skill4 starsChanged 3 months agoMITView on GitHub
Implement and review Nim ARC/ORC ownership hooks for types that manually manage resources, including move-only, deep-copy, refcounted, and copy-on-write patterns. Use when a Nim type owns pointers, buffers, file descriptors, or custom heap memory and you need correct `=destroy`, `=copy`, `=dup`, `=sink`, or move semantics.
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- planetis-m/skillsedited, first seen Jul 16, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- planetis-m/skills★ 5991% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository18 other files it gives its agents.
- atlas-package-clonerSkill
- buildSkill
- docs-genSkill
- format-codeSkill
- nim-api-designSkill
- nim-c-bindingsSkill
- nim-code-organizationSkill
- nim-c-wrappersSkill
- nim-debuggingSkill
- nim-defect-analysisSkill
- nim-doc-commentsSkill
- nim-error-handlingSkill
- nim-fuzzingSkill
- nim-mcp-toolsSkill
- nimonypluginsSkill
- nim-style-guideSkill
- nim-testingSkill
- run-testsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. About 0 are common, 5 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
Do not write hooks unless the type owns a resource the compiler cannot release on its own.
- Very specific: line 23
Check the moved-from sentinel (nil or default handle) before touching fields.
- Distinctive: line 24
When the type owns raw storage containing elements with their own hooks, destroy each element before freeing the raw storage pointer.
- Very specific: line 26
Use the signature =destroy(x: T), not var T.
- Very specific: line 33
Do not write a custom =sink by default.
- Very specific: line 34
When a custom =sink is required: call =destroy(dest), then =wasMoved(dest), then transfer source fields.
- Very specific: line 35
Do not use copyMem or whole-object raw moves — they bypass child hook semantics.
- Very specific: line 39
After the guard: =destroy(dest), =wasMoved(dest), then rebuild from source.
- Distinctive: line 53
Only when all three conditions hold: the type manually owns storage, stored values can participate in ORC cycles, and ORC needs to traverse …
- Very specific: line 57
Use lent T for immutable accessors that should borrow from a container instead of copying.
- Distinctive: line 65
Only templates may safely appear between the type definition and the hooks.
- Very specific: line 72
When the compiler cannot prove a sink argument is last use, it inserts =copy or =dup before passing.
- Very specific: line 83
Thread-aware allocation: When a refcounted payload may cross thread boundaries, switch between allocShared/deallocShared and alloc/dealloc …
- Very specific: line 101
Follow the hook-by-hook rules in section 2.
- Distinctive: line 113
Test these scenarios for every custom-hook type:
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Nim Ownership Hooks
Start by classifying the type's ownership model. Then implement exactly the hook set that model requires — no more, no less. Do not force one ownership model onto another: a shared handle should not become move-only just because it has a destructor, and a deep-owning container should not pretend copies are cheap shares.
Rules
When to write hooks
Do not write hooks unless the type owns a resource the compiler cannot release on its own.
The compiler auto-manages destruction for primitives, string, seq[T], ref T, array, tuples, closures, and objects whose fields are all auto-managed. Hooks lift through nesting: if a field's type already has custom hooks, the enclosing type gets correct compiler-generated hooks for free.
Custom hooks are needed only for non-managed resources: raw pointers (ptr T) to manually allocated memory, OS file descriptors, socket handles, distinct types whose base has no hooks, or similar. distinct types whose base already has hooks lift them automatically.
Hook-by-hook rules
=destroy
- Check the moved-from sentinel (
nilor default handle) before touching fields. Release only resources the type still owns. - When the type owns raw storage containing elements with their own hooks, destroy each element before freeing the raw storage pointer.
=destroyis implicitly.raises: []. Keep destructor behavior non-raising.- Use the signature
=destroy(x: T), notvar T. Both compile, butTprevents accidental field mutation.
=wasMoved
- Reset every field that
=destroychecks, so that=destroybecomes a no-op on the same variable. For pointer fields, set tonil. - The compiler eliminates a
=destroycall that follows=wasMovedon the same variable.
=sink
- Do not write a custom
=sinkby default. The compiler synthesizes one from=destroyplus a raw move, and that is usually sufficient. - When a custom
=sinkis required: call=destroy(dest), then=wasMoved(dest), then transfer source fields. No self-assignment check — the compiler eliminatesx = xbefore reaching your hook. - Do not use
copyMemor whole-object raw moves — they bypass child hook semantics.
=copy
- Deep-copy types: protect against self-assignment (
if dest.data == src.data: return). Without it,x = xdestroys the source before copying. - After the guard:
=destroy(dest),=wasMoved(dest), then rebuild from source. Check that source data is non-nil before allocating. - For move-only types, use
{.error.}(bare pragma, no custom message — the compiler ignores custom error strings). - For refcounted types:
=copydoes destroy-then-share. No pointer self-assignment guard needed — the counter increment balances the destroy.
=dup
- Move-only types: add
=dup {.error.}. - Deep-owning raw-storage containers: mark
=dupwith{.nodestroy.}. The copied elements are written into raw memory that does not hold valid old values yet.{.nodestroy.}prevents implicit hook calls on those destination slots. Use child=dupfor elements with hooks. - Refcounted types: increment the counter and share the pointer. No
{.nodestroy.}needed unless the hook writes into raw uninitialized storage.
=trace
- Only when all three conditions hold: the type manually owns storage, stored values can participate in ORC cycles, and ORC needs to traverse them.
- Forward-declare
=destroyand=tracealongside each other to prevent the mutual-use generation conflict.
lent T
- Use
lent Tfor immutable accessors that should borrow from a container instead of copying.
Declaration order
Declare all custom hooks before any proc, converter, iterator, closure, or generic instantiation that mentions the type. The compiler eagerly generates implicit hooks and will error if a custom hook appears afterward.
Safe order: type definition, then =destroy, =wasMoved, =copy, then =dup.
Only templates may safely appear between the type definition and the hooks. If a hook body needs a shared helper, write it as a template directly before the hooks.
importc procs are opaque and do not trigger implicit hook generation — they may appear before hooks.
Move semantics
sinkparameters are affine, not linear: the callee may consume the value once, or not at all.- When the compiler cannot prove a sink argument is last use, it inserts
=copyor=dupbefore passing. Seenim-api-designfor the caller-facing rules on whenmove()is required. move(x)leaves the source alive and moved-from; the source's=destroystill runs.ensureMove(x)makes the source dead: later use is a compile error, and the source's=destroyis skipped. Use it for return positions and must-fail-instead-of-copy cases, not routine sink arguments.=wasMoved(x)followed by=destroy(x)cancel: the destroy is eliminated.
Edge cases
- Zero-length allocations: Guard against
alloc(0)in constructors and=copy. Only allocate when length is positive.alloc(0)may return nil or an invalid pointer. - Thread-aware allocation: When a refcounted payload may cross thread boundaries, switch between
allocShared/deallocSharedandalloc/deallocusingwhen compileOption("threads").
Workflow
Step 1: Classify the ownership model
Match the type to exactly one model. Use the hook set that model requires.
| Model | Hooks needed |
| Plain / auto-managed | None |
| Borrowing / view | None. Use lent T for accessors. |
| Move-only owner | =destroy, =wasMoved, =copy as {.error.}, =dup as {.error.} |
| Deep-owning container | =destroy, =wasMoved, =copy, =dup |
| Shared / refcounted | =destroy, =wasMoved, =dup, =copy |
Step 2: Implement the minimal hook set
Follow the hook-by-hook rules in section 2. See references/ for complete examples of each model.
Step 3: Verify with --expandArc
nim c --expandArc:nameOfFunction yourfile.nimConfirm the compiler inserts the hooks you expect. Check that synthesized hooks match intent.
Step 4: Run stress tests
Test these scenarios for every custom-hook type:
- Move into another variable
- Overwrite existing owned data
- Copy independence (mutating copy does not affect original)
- Dup independence
- Destroy-after-move (destroy is a no-op)
- Self-copy (
x = xdoes not crash) - Sink from temporaries
- Zero-length initialization (if the type has constructors)
Common Mistakes
| Mistake | Why it is wrong |
=destroy with var T | Both compile, but T prevents accidental field mutation inside the destructor. |
Setting fields to nil inside =destroy | Use =wasMoved for field reset. The compiler eliminates the subsequent destroy. |
Missing self-assignment guard in deep-copy =copy | Destroys source data before reading it. |
Self-assignment check in =sink | Compiler already eliminates simple x = x. The check is dead code. |
Missing {.nodestroy.} on raw-storage =dup | The compiler can run hooks on destination slots that do not hold valid values yet. |
Custom =sink when synthesized is fine | Adds unnecessary complexity with no benefit. |
copyMem in =sink or =dup | Bypasses child hook semantics and breaks the ownership chain for elements that have their own hooks. |
| Missing zero-length guard | alloc(0) may return nil; subsequent indexing crashes. |
Using move when ensureMove would compile | Later reads of the source still compile and silently return its default value. |
alloc in multi-threaded code | Must use allocShared/deallocShared instead. |
Custom error string in {.error: "msg"} on =copy | The compiler ignores custom error messages. Use bare {.error.}. |
Skipping =dup on a move-only type | Add =dup {.error.}. Without it the compiler synthesizes one that produces nil instead of erroring. |
References
references/move_only_owner.md— Hooks for exclusive ownership with copying forbidden.references/deep_owning_container.md— Destroy, copy, and duplicate hooks for raw storage with independent copies.references/shared_refcounted.md— Separate-counter and genericSharedPtrpatterns for shared ownership.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

