Skip to content
nim-api-design logo

Nim API Design

nim-api-design

Design clear public Nim APIs for libraries and modules, including exported types, constructors, lookup functions, error contracts, and container-style interfaces. Use when creating or reviewing a Nim library API, designing an exported module surface, or deciding how callers should construct, acce...

planetis-m/skills0installs59stars

SKILL.md

Full skill instructions

Nim API Design

Preamble

Use this skill when designing or reviewing a public Nim API. Default to plain data, one clear surface, and names that match the standard library. Reference examples live in references/.

Rules

Public shape

  • Prefer plain object types for public data models.
  • Use ref object only when identity, aliasing, shared mutation, graph structure, or handle lifetime is part of the contract.
  • Export one primary public representation per concept.
  • Prefer procs, overloads, generics, and iterators. Do not default to methods or runtime dispatch for ordinary APIs.
  • Use named object types for public semantic data.
  • Use tuples only for local glue or iterator yields such as (key, val).
  • Reuse stdlib names when the behavior matches: len, contains/hasKey, [], []=, items/mitems, pairs/mpairs, incl/excl, push/pop.

Contracts

  • Keep constraints in types. Use Natural, Positive, ranges, enums, sets, and distinct types instead of weakening to int and re-checking manually.
  • Use distinct when two values share a base type but must not mix.
  • Use func for pure query operations when purity is part of the public contract.
  • Use {.raises.} only when it keeps the public exception surface clear and easy to maintain.

Constructors and conversions

  • Value types use initX() and return T.
  • Ref types use newX() and return ref T.
  • Use one toX() name for common conversions. Overload on input type.
  • Accept openArray for batch inputs when callers naturally have arrays, seqs, or literals.
  • Keep the zero-argument path simple with sensible defaults.

Lookup surface

  • Separate required lookup from optional lookup.
  • A required lookup raises one specific catchable exception. It does not return a silent default.
  • An optional lookup uses an explicit safe path such as contains, hasKey, getOrDefault, or Option[T].
  • If several accessors fail the same way, route the failure through one private {.noinline, noreturn.} helper.

Borrowed and mutable access

  • Use lent T for read accessors that return storage owned by the receiver.
  • Add var T, mitems, or mpairs only when caller mutation is part of the API.
  • Do not expose scalar var accessors such as var int, var bool, or enum fields from internal state.
  • In lent and var accessors, return directly from storage. Do not route through a temp local.

Public boundary

  • Export only the stable surface. Keep helpers private.
  • Use descriptive public names.
  • In user code, gate version-specific API with when (NimMajor, NimMinor) >= (x, y). Do not use stdlib-internal {.since.}.
  • Treat paired value/​ref APIs and patterns like withValue as opt-in compatibility choices, not defaults.

Workflow

  1. Choose the representation. Start with a plain object. Switch to ref object only if the contract needs identity or aliasing.
  2. Name the public types. Use named objects for semantic results and distinct or range types for domain constraints.
  3. Name the constructor surface. Use initX, newX, and toX in the stdlib style.
  4. Design the lookup surface. Provide one strict path for required data and one explicit safe path for optional data.
  5. Add borrowed and mutable access. Use lent for reads into owned storage. Add mutable access only where the caller must edit stored data.
  6. Verify the contract. Compile normally. If you use lent or var accessors, verify the borrow compiles. If you use func, make sure the body stays pure. If you gate by Nim version, use when guards.

Common Mistakes

MistakeWhy it is wrong
Starting with ref object for plain dataIt adds aliasing and shared mutation where the API does not need them
Defaulting to methods or runtime dispatchIt hides behavior behind runtime polymorphism when a proc surface is simpler and clearer
Weakening Natural or Positive to int and re-checking manuallyIt throws away a stronger type-level contract
Returning a silent default for required dataIt hides missing-data bugs
Exporting scalar var accessorsIt leaks mutable internal state
Returning a lent or var result through a temp localORC rejects the borrow because the temp escapes

References

  • references/​representation_default.md — Plain object default and ref object only when aliasing is required
  • references/​constructors.md — initX, newX, and toX constructor patterns
  • references/​collection_accessors.md — One coherent container surface with stdlib-style names
  • references/​accessor_pair.md — Minimal borrowed and mutable accessor pair with one shared error helper
  • references/​distinct_types.md — Domain types with distinct and borrowed operations
  • references/​parameter_and_result_shapes.md — Parameter defaults, options objects, and named result objects

Changelog

  • 2026-04-08: Initial verified skill.
  • 2026-04-11: Added value-vs-ref claims and func purity tests.

More skills from planetis-m

tts-tool logo
planetis-m/tts-tool

tts-tool

Generate a natural-sounding `.opus` audio file from text or markdown. Use when a user wants spoken audio, especially for content with markdown, URLs, formulas, paths, or technical notation that should be rewritten for speech.

3 0
View
ocr-tool logo
planetis-m/ocr-tool

ocr-tool

Extract raw text from PDF files with OCR, including full-document extraction, selected page ranges, and reuse of cached pages. Use when a user asks to OCR a PDF, extract text from a scanned PDF, or read selected PDF pages.

1 0
View
nim-c-wrappers logo
planetis-m/skills

nim-c-wrappers

Turn low-level C FFI bindings into an idiomatic Nim API, with safer types, cleaner module boundaries, resource management, callbacks, enums, bitflags, and exception-based error handling. Use when building a high-level Nim wrapper around a C library or improving the usability of existing raw bindi...

59 0
View
nim-style-guide logo
planetis-m/skills

nim-style-guide

Write clear, consistent Nim code in a simple stdlib-aligned style, covering imports, naming, proc vs func vs template choices, local variables, constructors, formatting, and control flow. Use when writing new Nim code or reviewing a Nim module for readability, consistency, and low-noise style dec...

59 0
View
rag-tool logo
planetis-m/rag-tool

rag-tool

Store and search text or markdown as semantic chunks in a reusable local vector store. Use when a user wants to ingest documents or retrieve relevant passages from previously stored material.

1 0
View
study-assistant logo
planetis-m/study-assistant

study-assistant

Study assistant workflow for turning provided study material into exam-focused deliverables such as verbatim transcriptions, study notes, lecture-style explanations, ELI5 explanations, flashcards, Mermaid mind maps, quizzes, and essay questions.

5 0
View
nim-code-organization logo
planetis-m/skills

nim-code-organization

Organize Nim code into clear modules and multi-step workflows, with explicit state, top-level helper procs, narrow exports, and easy-to-follow orchestration. Use when refactoring a large Nim file, splitting logic across modules, designing parser-style stateful code, or cleaning up nested helpers ...

59 0
View
nim-ownership-hooks logo
planetis-m/skills

nim-ownership-hooks

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`, ...

59 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View