Implement an asArray macro

fixes #6563
This commit is contained in:
Fredrik Høisæther Rasch
2017-10-31 12:23:06 +01:00
committed by Andreas Rumpf
parent a583d686b4
commit 5dfbeab65f

View File

@@ -20,6 +20,8 @@
include "system/inclrtl"
import macros
when not defined(nimhygiene):
{.pragma: dirty.}
@@ -704,6 +706,29 @@ template newSeqWith*(len: int, init: untyped): untyped =
result[i] = init
result
macro asArray*(values: typed, targetType: typedesc): untyped =
## converts a static array to an array of type ``targetType`` by converting
## each value in the array to the specified type.
##
## Example:
##
## .. code-block::
## let x = asArray([0.1, 1.2, 2.3, 3.4], int)
## doAssert x is array[4, int]
##
## Short notation for:
##
## .. code-block::
## let x = [(0.1).int, (1.2).int, (2.3).int, (3.4).int]
let tNode = getType(targetType)[1]
values.expectKind(nnkBracket)
result = newNimNode(nnkBracket, lineInfoFrom=values)
for i in 0 ..< len(values):
var dot = newNimNode(nnkDotExpr, lineInfoFrom=values[i])
dot.add newPar(values[i])
dot.add tNode
result.add dot
when isMainModule:
import strutils
block: # concat test
@@ -992,5 +1017,9 @@ when isMainModule:
seq2D[0][1] = true
doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]]
block: # asArray tests
let x = asArray([1.2, 2.3, 3.4, 4.5], int)
doAssert x is array[4, int]
when not defined(testing):
echo "Finished doc tests"