From fbce88be38b6a9a08447f7b8b382d20880425223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mamy=20Andr=C3=A9-Ratsimbazafy?= Date: Mon, 8 Jul 2019 13:31:00 +0200 Subject: [PATCH] Add an alias template --- lib/pure/sugar.nim | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/lib/pure/sugar.nim b/lib/pure/sugar.nim index c4c99121420f3..8bd781fa523bd 100644 --- a/lib/pure/sugar.nim +++ b/lib/pure/sugar.nim @@ -238,3 +238,22 @@ macro distinctBase*(T: typedesc): untyped = while typeSym.typeKind == ntyDistinct: typeSym = getTypeImpl(typeSym)[0] typeSym.freshIdentNodes + +template alias*(name: untyped, bodyOrExpr: untyped): untyped = + ## Syntax sugar to create aliases. + ## + ## Notes: + ## Contrary to `let`, aliases are not allocated in memory. + ## This is useful to access deep nested object fields + ## without incurring the cost of allocation. + runnableExamples: + type Node = ref object + left, right: Node + val: int + + let t = Node(left: Node(left: Node(left: Node(val: 10)))) + alias(t3, t.left.left.left) + + doAssert t3.val == 10 + + template name(): untyped {.dirty.} = bodyOrExpr