File: underscored_calls.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (56 lines) | stat: -rw-r--r-- 1,557 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

#
#
#            Nim's Runtime Library
#        (c) Copyright 2020 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This is an internal helper module. Do not use.

import std/macros

proc underscoredCalls*(result, calls, arg0: NimNode)

proc underscoredCall(n, arg0: NimNode): NimNode =
  proc underscorePos(n: NimNode): int =
    for i in 1 ..< n.len:
      if n[i].eqIdent("_"): return i
    return 0

  if n.kind in nnkCallKinds:
    if n[0].kind in {nnkIdent, nnkSym} and n[0].eqIdent("with"):
      expectKind n[1], {nnkIdent, nnkSym}

      result = newStmtList()
      underscoredCalls(result, n[2 .. ^1].newStmtList, newDotExpr(arg0, n[1]))
    else:
      result = copyNimNode(n)
      result.add n[0]

      let u = underscorePos(n)
      for i in 1..u-1: result.add n[i]
      result.add arg0
      for i in u+1..n.len-1: result.add n[i]
  elif n.kind in {nnkAsgn, nnkExprEqExpr}:
    var field = n[0]
    if n[0].kind == nnkDotExpr and n[0][0].eqIdent("_"):
      # handle _.field = ...
      field = n[0][1]
    result = newDotExpr(arg0, field).newAssignment n[1]
  else:
    # handle e.g. 'x.dup(sort)'
    result = newNimNode(nnkCall, n)
    result.add n
    result.add arg0

proc underscoredCalls*(result, calls, arg0: NimNode) =
  expectKind calls, {nnkArgList, nnkStmtList, nnkStmtListExpr}

  for call in calls:
    if call.kind in {nnkStmtList, nnkStmtListExpr}:
      underscoredCalls(result, call, arg0)
    else:
      result.add underscoredCall(call, arg0)