From a2a2ef62ecb8a349eae0cd90df75c44f5e7e83a5 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Thu, 26 Jan 2017 13:13:18 -0800
Subject: [PATCH 1/2] Add castNode(type, ptr) for safe casting between NodeTag
 based types.

Author: Peter Eisentraut and Andres Freund
Discussion: https://postgr.es/m/c5d387d9-3440-f5e0-f9d4-71d53b9fbe52@2ndquadrant.com
---
 src/include/nodes/nodes.h | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h
index fa4932a902..b462a5ffde 100644
--- a/src/include/nodes/nodes.h
+++ b/src/include/nodes/nodes.h
@@ -558,6 +558,26 @@ extern PGDLLIMPORT Node *newNodeMacroHolder;
 
 #define IsA(nodeptr,_type_)		(nodeTag(nodeptr) == T_##_type_)
 
+/*
+ * castNode(type, ptr) casts ptr to type and, if cassert is enabled, verifies
+ * that the the c actually has the appropriate type (using it's nodeTag()).
+ *
+ * Use an inline function when assertions are enabled, to avoid multiple
+ * evaluations of the ptr argument (which could e.g. be a function call).
+ */
+#ifdef USE_ASSERT_CHECKING
+static inline Node*
+castNodeImpl(enum NodeTag type, void *ptr)
+{
+	Assert(ptr == NULL || nodeTag(ptr) == type);
+	return ptr;
+}
+#define castNode(_type_, nodeptr) ((_type_ *) castNodeImpl(T_##_type_, nodeptr))
+#else
+#define castNode(_type_,nodeptr)  ((_type_ *)(nodeptr))
+#endif
+
+
 /* ----------------------------------------------------------------
  *					  extern declarations follow
  * ----------------------------------------------------------------
-- 
2.11.0.22.g8d7a455.dirty

