Spec-Zone.ru › Nim

std/genasts

Source Edit

Этот модуль реализует генерацию AST с использованием захваченных переменных для макросов.

Импорты

macros

Типы

GenAstOpt = enum
  kDirtyTemplate, kNoNewLit
Source Edit

Макросы

macro genAstOpt(options: static set[GenAstOpt]; args: varargs[untyped]): untyped
Принимает список захваченных переменных a=b или a и блок, и возвращает AST, представляющий его. Локальные {.inject.} символы (например, процедуры) захватываются, если kDirtyTemplate in options.

Пример:

# This example shows how one could write a simplified version of `unittest.check`.
import std/[macros, strutils]
macro check2(cond: bool): untyped =
  assert cond.kind == nnkInfix, "$# not implemented" % $cond.kind
  result = genAst(cond, s = repr(cond), lhs = cond[1], rhs = cond[2]):
    # each local symbol we access must be explicitly captured
    if not cond:
      raiseAssert "'$#'' failed: lhs: '$#', rhs: '$#'" % [s, $lhs, $rhs]
let a = 3
check2 a*2 == a+3
if false: check2 a*2 < a+1 # would error with: 'a * 2 < a + 1'' failed: lhs: '6', rhs: '4'

Пример:

# This example goes in more details about the capture semantics.
macro fun(a: string, b: static bool): untyped =
  let c = 'z'
  var d = 11 # implicitly {.gensym.} and needs to be captured for use in `genAst`.
  proc localFun(): auto = 12 # implicitly {.inject.}, doesn't need to be captured.
  genAst(a, b, c = true):
    # `a`, `b` are captured explicitly, `c` is a local definition masking `c = 'z'`.
    const b2 = b # macro static param `b` is forwarded here as a static param.
    # `echo d` would give: `var not init` because `d` is not captured.
    (a & a, b, c, localFun()) # localFun can be called without capture.
assert fun("ab", false) == ("abab", false, true, 12)
Source Edit

Шаблоны

template genAst(args: varargs[untyped]): untyped
Обёртка для удобства над genAstOpt. Source Edit

© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/genasts.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API