Token导航 LogoToken导航

Agent Skill · 研究检索

nim-metaprogramming(nim 元编程)

nim-metaprogramming 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

nim-metaprogramming 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,第三方扫描有提醒项,按安装量在研究检索类的 73,675 个 Skill 里排第 18,400。

总安装 6,109周安装 218GitHub Stars 142下载 2,011核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:nim-metaprogramming(nim 元编程)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/nim-metaprogramming
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill 'Nim Metaprogramming'
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill 'Nim Metaprogramming'

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于查找 Nim 元编程相关的技术资料和最佳实践。适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词快速定位信息。可配合来源仓库和 README 核验具体内容,但需注意权限范围。安装方式:通过 npx 从 GitHub 仓库添加,建议先确认网络访问权限。

注意:搜索结果的真实性需人工复核,避免依赖过时资料。

来源仓库内路径:skills/nim-metaprogramming

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/thebushidocollective/han --skill 'Nim Metaprog…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

nim-metaprogramming 怎么安装?

在终端执行 npx skills add https://github.com/thebushidocollective/han --skill 'Nim Metaprogramming'。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

nim-metaprogramming 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

nim-metaprogramming 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

nim-metaprogramming 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

nim-metaprogramming 用的人多吗?

公开数据是累计安装 6,109 次,近一周安装 218 次,下载 2,011 次,GitHub 142 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

nim-metaprogramming 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
nim-metaprogramming

nim 元编程 · 本页

6,109142需要联网MIT有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Nim Metaprogramming

Introduction

Nim's metaprogramming system provides powerful compile-time code generation and manipulation through templates, macros, and compile-time evaluation. This enables zero-overhead abstractions, domain-specific languages, and optimizations performed at compile time rather than runtime.

The system operates on Nim's abstract syntax tree (AST), allowing inspection and transformation of code structure. Templates provide hygienic macro-like substitution, while macros enable full AST manipulation. Compile-time evaluation executes Nim code during compilation for constant folding and validation.

This skill covers templates for code substitution, macros for AST transformation, compile-time evaluation with static blocks, AST inspection and manipulation, code generation patterns, DSL creation, and metaprogramming best practices.

Templates

Templates provide hygienic code substitution with type safety and inline expansion.

# Basic template
template max(a, b: untyped): untyped =
  if a > b: a else: b

echo max(5, 10)  # Expands inline

# Template with multiple statements
template withFile(filename: string, body: untyped): untyped =
  let file = open(filename, fmRead)
  try:
    body
  finally:
    file.close()

withFile("data.txt"):
  for line in file.lines:
    echo line

# Template with inject
template defineProperty(name: untyped, typ: typedesc): untyped =
  var `name Value`: typ

  proc `get name`(): typ {.inject.} =
    `name Value`

  proc `set name`(value: typ) {.inject.} =
    `name Value` = value

defineProperty(age, int)
setAge(30)
echo getAge()  # 30

# Template accepting block
template benchmark(name: string, code: untyped): untyped =
  let start = cpuTime()
  code
  let elapsed = cpuTime() - start
  echo name, ": ", elapsed, " seconds"

benchmark "computation":
  var sum = 0
  for i in 1..1000000:
    sum += i

# Template with typed parameters
template swap(a, b: typed): untyped =
  let tmp = a
  a = b
  b = tmp

var x = 5
var y = 10
swap(x, y)
echo x, " ", y  # 10 5

# Template for DSL
template html(body: untyped): string =
  var result = ""
  template tag(name: string, content: untyped): untyped =
    result.add "<" & name & ">"
    content
    result.add "</" & name & ">"

  body
  result

let page = html:
  tag "html":
    tag "body":
      tag "h1":
        result.add "Hello World"

# Template with generic constraints
template findMax[T: Ordinal](items: openArray[T]): T =
  var maxVal = items[0]
  for item in items:
    if item > maxVal:
      maxVal = item
  maxVal

echo findMax([1, 5, 3, 9, 2])

# Template forwarding
template forward(call: untyped): untyped =
  echo "Before call"
  call
  echo "After call"

proc myProc() =
  echo "Inside proc"

forward myProc()

# Template for custom operators
template `~=`(a, b: float): bool =
  abs(a - b) < 0.0001

echo 1.0 ~= 1.00001  # true

# Template with immediate parameter
template log(msg: string): untyped =
  when defined(debug):
    echo "[LOG] ", msg

log "Debug message"  # Only in debug builds

Templates provide compile-time code substitution with hygiene and type safety.

Macros and AST Manipulation

Macros transform AST at compile time, enabling powerful code generation and domain-specific languages.

import macros

# Basic macro
macro debug(n: varargs[typed]): untyped =
  result = newStmtList()
  for arg in n:
    result.add quote do:
      echo astToStr(`arg`), " = ", `arg`

let x = 5
let y = 10
debug x, y, x + y

# Macro examining AST
macro inspect(node: untyped): untyped =
  echo node.treeRepr
  result = node

inspect:
  let x = 5 + 3

# Building AST manually
macro makeProc(name: untyped, body: untyped): untyped =
  result = newProc(
    name = name,
    params = [newEmptyNode()],
    body = body
  )

makeProc greet:
  echo "Hello!"

greet()

# Macro for property generation
macro property(name: untyped, typ: typedesc): untyped =
  let
    fieldName = ident($name & "Field")
    getName = ident("get" & $name)
    setName = ident("set" & $name)

  result = quote do:
    var `fieldName`: `typ`

    proc `getName`(): `typ` =
      `fieldName`

    proc `setName`(value: `typ`) =
      `fieldName` = value

property(count, int)
setCount(42)
echo getCount()

# Case statement macro
macro switch(value: typed, branches: varargs[untyped]): untyped =
  result = nnkCaseStmt.newTree(value)

  for branch in branches:
    expectKind(branch, nnkCall)
    let pattern = branch[0]
    let body = branch[1]
    result.add nnkOfBranch.newTree(pattern, body)

switch(5):
  1: echo "one"
  2: echo "two"
  5: echo "five"

# Builder pattern macro
macro build(typ: typedesc, fields: varargs[untyped]): untyped =
  result = nnkObjConstr.newTree(typ)

  for field in fields:
    expectKind(field, nnkExprEqExpr)
    result.add field

type Person = object
  name: string
  age: int

let p = build(Person, name = "Alice", age = 30)

# Compile-time assertion macro
macro staticAssert(condition: bool, message: string): untyped =
  if not condition.boolVal:
    error(message.strVal)
  result = newEmptyNode()

staticAssert sizeof(int) >= 4, "int must be at least 4 bytes"

# Unrolling loop macro
macro unroll(count: static[int], body: untyped): untyped =
  result = newStmtList()
  for i in 0..<count:
    let iNode = newLit(i)
    result.add body.replace(ident("it"), iNode)

unroll 5:
  echo "Iteration: ", it

# Pattern matching macro
macro match(value: typed, patterns: varargs[untyped]): untyped =
  result = nnkIfStmt.newTree()

  for pattern in patterns:
    expectMinLen(pattern, 2)
    let condition = pattern[0]
    let body = pattern[1]

    let check = quote do:
      `value` == `condition`

    result.add nnkElifBranch.newTree(check, body)

Macros enable compile-time code transformation and generation through AST manipulation.

Compile-Time Evaluation

Nim executes code at compile time for constants, optimizations, and validations.

# Compile-time constants
const maxSize = 100
const computed = maxSize * 2 + 10  # Evaluated at compile time

# Compile-time function evaluation
proc factorial(n: int): int =
  if n <= 1: 1 else: n * factorial(n - 1)

const fact10 = factorial(10)  # Computed at compile time

# Static block
static:
  echo "This runs at compile time"
  echo "Factorial of 10 is: ", factorial(10)

# Compile-time type information
proc sizeInfo[T](x: T): string =
  static:
    "Size of " & $T & " is " & $sizeof(T) & " bytes"

echo sizeInfo(5)
echo sizeInfo(5.0)

# Compile-time conditional compilation
when sizeof(int) == 8:
  proc printSize() = echo "64-bit platform"
else:
  proc printSize() = echo "32-bit platform"

# Compile-time string operations
const
  version = "1.0.0"
  parts = version.split('.')
  major = parts[0].parseInt

when major >= 1:
  echo "Version 1.0 or later"

# Compile-time file reading
const configData = staticRead("config.txt")

proc getConfig(): string =
  configData

# Compile-time HTTP requests (with stdlib)
const apiResponse = staticExec("curl -s https://api.example.com/data")

# Compile-time code generation
proc generateAccessors(fields: seq[string]): string =
  result = ""
  for field in fields:
    result.add &"""
      proc get{field.capitalizeAscii}(): int = {field}
      proc set{field.capitalizeAscii}(val: int) = {field} = val
    """

const accessors = generateAccessors(@["x", "y", "z"])

# Static parameter constraints
proc processArray[T; N: static[int]](arr: array[N, T]) =
  static:
    echo "Array size: ", N
  for item in arr:
    echo item

processArray([1, 2, 3, 4, 5])

# Compile-time assertions
static:
  doAssert sizeof(int) >= 4, "int too small"
  doAssert sizeof(ptr) == sizeof(int), "pointer size mismatch"

# Compile-time regex compilation
import re

const emailPattern = re"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"

proc validateEmail(email: string): bool =
  email.match(emailPattern)

# Compile-time validation
proc validateConfig() =
  static:
    when not fileExists("config.txt"):
      {.fatal: "config.txt not found".}

# Compile-time optimization
proc optimizedPower(base: float, exp: static[int]): float =
  when exp == 0:
    1.0
  elif exp == 1:
    base
  elif exp mod 2 == 0:
    let half = optimizedPower(base, exp div 2)
    half * half
  else:
    base * optimizedPower(base, exp - 1)

echo optimizedPower(2.0, 10)

Compile-time evaluation enables zero-runtime-cost abstractions and build-time validations.

DSL Creation

Nim's metaprogramming enables creating domain-specific languages with natural syntax.

# HTML DSL
macro html(body: untyped): string =
  proc processNode(node: NimNode): NimNode =
    case node.kind
    of nnkCall, nnkCommand:
      let tag = node[0]
      let attrs = newSeq[NimNode]()
      var content = newStmtList()

      for i in 1..<node.len:
        if node[i].kind == nnkExprEqExpr:
          attrs.add node[i]
        else:
          content.add processNode(node[i])

      result = quote do:
        result.add "<" & `tag`.astToStr & ">"
        `content`
        result.add "</" & `tag`.astToStr & ">"
    of nnkStrLit:
      result = quote do:
        result.add `node`
    else:
      result = newStmtList()

  result = quote do:
    var result = ""
    `processNode(body)`
    result

let page = html:
  html:
    head:
      title: "My Page"
    body:
      h1: "Welcome"
      p: "Hello World"

# SQL DSL
macro select(fields: varargs[untyped]): string =
  var fieldList = ""
  for i, field in fields:
    if i > 0: fieldList.add ", "
    fieldList.add $field

  result = newLit("SELECT " & fieldList)

macro fromTable(table: untyped): string =
  newLit(" FROM " & $table)

let query = select(name, age) & fromTable(users)

# Test DSL
macro describe(name: string, tests: untyped): untyped =
  result = newStmtList()

  for test in tests:
    if test.kind == nnkCall and $test[0] == "it":
      let testName = test[1]
      let testBody = test[2]

      result.add quote do:
        echo "Testing: ", `testName`
        try:
          `testBody`
          echo "  ✓ Passed"
        except:
          echo "  ✗ Failed"

describe "Math operations":
  it "adds numbers":
    doAssert 1 + 1 == 2

  it "multiplies numbers":
    doAssert 2 * 3 == 6

# Configuration DSL
macro config(body: untyped): untyped =
  result = nnkObjConstr.newTree(ident("Config"))

  for stmt in body:
    if stmt.kind == nnkCall:
      let key = stmt[0]
      let value = stmt[1]
      result.add nnkExprColonExpr.newTree(key, value)

type Config = object
  host: string
  port: int
  debug: bool

let cfg = config:
  host("localhost")
  port(8080)
  debug(true)

# Builder DSL
macro builder(typ: typedesc, body: untyped): untyped =
  var assignments = newStmtList()

  for stmt in body:
    if stmt.kind == nnkCall:
      let field = stmt[0]
      let value = stmt[1]
      assignments.add quote do:
        result.`field` = `value`

  result = quote do:
    var result: `typ`
    `assignments`
    result

type Request = object
  url: string
  method: string
  headers: seq[string]

let req = builder(Request):
  url("https://api.example.com")
  method("GET")

DSLs enable domain-specific notation within Nim while maintaining type safety.

Code Generation Patterns

Metaprogramming enables automated code generation from specifications or runtime data.

# Generate enum from compile-time list
macro generateEnum(name: untyped, values: static[seq[string]]): untyped =
  result = nnkTypeSection.newTree(
    nnkTypeDef.newTree(
      name,
      newEmptyNode(),
      nnkEnumTy.newTree(newEmptyNode())
    )
  )

  for value in values:
    result[0][2].add ident(value)

generateEnum(Color, @["Red", "Green", "Blue"])

# Generate getters/setters
macro generateAccessors(typ: typedesc): untyped =
  let impl = typ.getImpl
  result = newStmtList()

  for field in impl[2][2]:
    let fieldName = field[0]
    let fieldType = field[1]

    let getter = ident("get" & ($fieldName).capitalizeAscii)
    let setter = ident("set" & ($fieldName).capitalizeAscii)

    result.add quote do:
      proc `getter`(obj: `typ`): `fieldType` =
        obj.`fieldName`

      proc `setter`(obj: var `typ`, value: `fieldType`) =
        obj.`fieldName` = value

type Person = object
  name: string
  age: int

generateAccessors(Person)

# Generate pattern matching
macro matchGen(value: typed, patterns: varargs[untyped]): untyped =
  result = nnkCaseStmt.newTree(value)

  for pattern in patterns:
    let condition = pattern[0]
    let body = pattern[1]
    result.add nnkOfBranch.newTree(condition, body)

# Generate state machine
macro stateMachine(states: varargs[untyped]): untyped =
  var stateEnum = nnkEnumTy.newTree(newEmptyNode())

  for state in states:
    stateEnum.add ident($state)

  result = nnkTypeSection.newTree(
    nnkTypeDef.newTree(
      ident("State"),
      newEmptyNode(),
      stateEnum
    )
  )

stateMachine Idle, Running, Stopped

# Generate serialization
macro deriveJson(typ: typedesc): untyped =
  result = newStmtList()

  # Generate toJson proc
  result.add quote do:
    proc toJson(obj: `typ`): JsonNode =
      result = newJObject()
      # Add fields...

# Generate validators
macro validate(typ: typedesc, rules: untyped): untyped =
  result = quote do:
    proc validate(obj: `typ`): bool =
      # Generated validation logic
      true

Code generation reduces boilerplate and ensures consistency across similar implementations.

Best Practices

  1. Use templates for simple substitutions to avoid macro complexity when AST manipulation isn't needed
  2. Prefer typed macro parameters over untyped when possible for better type checking
  3. Test macros thoroughly as compile-time errors are harder to debug than runtime errors
  4. Document macro usage with examples since expanded code isn't visible to users
  5. Use quote do for AST generation to write natural Nim code instead of manual AST construction
  6. Leverage compile-time evaluation for validations and optimizations without runtime cost
  7. Keep macros focused on single responsibilities for maintainability
  8. Use static blocks for compile-time side effects like logging or validation
  9. Provide error messages in macros using error() for clear compile-time failures
  10. Test macro expansions by examining generated code with dumpTree or expandMacros

Common Pitfalls

  1. Overusing macros for problems solvable with templates adds unnecessary complexity
  2. Not handling AST node kinds properly causes compilation failures on unexpected input
  3. Forgetting hygiene in templates can capture unintended identifiers from calling scope
  4. Creating overly complex macros makes code hard to understand and maintain
  5. Not validating macro inputs leads to confusing error messages at macro expansion
  6. Mixing runtime and compile-time code without static blocks causes errors
  7. Assuming AST structure without checking node kinds breaks on different inputs
  8. Not using result variable in templates returns last statement unexpectedly
  9. Creating DSLs that are too magical reduces code readability and maintainability
  10. Forgetting to return nodes from macros causes empty code generation

When to Use This Skill

Apply templates for zero-overhead abstractions replacing repetitive patterns.

Use macros when transforming or generating code based on compile-time information.

Leverage compile-time evaluation for constants, validations, and build-time optimizations.

Create DSLs for domain-specific problems requiring specialized notation.

Generate code for boilerplate like serialization, getters, or pattern matching.

Use metaprogramming for performance-critical abstractions with zero runtime cost.

Resources

平台分布

OpenCode

30.72%
按下载量换算618

Codex

21.58%
按下载量换算434

Claude Code

18.37%
按下载量换算369

windsurf

13.64%
按下载量换算274

Cursor

7.83%
按下载量换算157

Antigravity

3.42%
按下载量换算69

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。

继续浏览同类 Skills