tree data CHANGE lyd_leaf_type resolves leafrefs

Fixes #238
diff --git a/src/parser.c b/src/parser.c
index 045c4ca..e357d60 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -1659,6 +1659,7 @@
     case LY_TYPE_UNION:
         if (store) {
             /* unresolved union type */
+            memset(&leaf->value, 0, sizeof leaf->value);
             leaf->value_type = LY_TYPE_UNION;
         }
 
diff --git a/src/resolve.c b/src/resolve.c
index 7d2540b..820e4cc 100644
--- a/src/resolve.c
+++ b/src/resolve.c
@@ -6896,7 +6896,6 @@
     assert(type->base == LY_TYPE_UNION);
 
     if ((leaf->value_type == LY_TYPE_UNION) || (leaf->value_type == (LY_TYPE_INST | LY_TYPE_INST_UNRES))) {
-        assert(store);
         /* either NULL or instid previously converted to JSON */
         json_val = leaf->value.string;
     }
diff --git a/src/tree_data.c b/src/tree_data.c
index 522e4b5..fdd4d62 100644
--- a/src/tree_data.c
+++ b/src/tree_data.c
@@ -5893,17 +5893,22 @@
     }
 
     type = &((struct lys_node_leaf *)leaf->schema)->type;
-    if (type->base == LY_TYPE_UNION) {
-        if (type->info.uni.has_ptr_type && leaf->validity) {
-            /* we don't know what it will be after resolution */
-            return NULL;
-        }
 
-        if (resolve_union((struct lyd_node_leaf_list *)leaf, type, 0, 0, &type)) {
-            /* resolve union failed */
-            type = NULL;
+    do {
+        if (type->base == LY_TYPE_LEAFREF) {
+            type = &type->info.lref.target->type;
+        } else if (type->base == LY_TYPE_UNION) {
+            if (type->info.uni.has_ptr_type && leaf->validity) {
+                /* we don't know what it will be after resolution (validation) */
+                return NULL;
+            }
+
+            if (resolve_union((struct lyd_node_leaf_list *)leaf, type, 0, 0, &type)) {
+                /* resolve union failed */
+                return NULL;
+            }
         }
-    }
+    } while (type->base == LY_TYPE_LEAFREF);
 
     return type;
 }
diff --git a/src/tree_data.h b/src/tree_data.h
index 909c051..733c2df 100644
--- a/src/tree_data.h
+++ b/src/tree_data.h
@@ -1090,11 +1090,13 @@
 struct lys_module *lyd_node_module(const struct lyd_node *node);
 
 /**
- * @brief Get the type structure of a leaf. In case of union, the correct
- * specific type is found.
+ * @brief Get the type structure of a leaf.
+ *
+ * In case of a union, the correct specific type is found.
+ * In case of a leafref, the final (if there is a chain of leafrefs) target's type is found.
  *
  * @param[in] leaf Leaf to examine.
- * @return Type structure of \p leaf, NULL on error.
+ * @return Found type, NULL on error.
  */
 const struct lys_type *lyd_leaf_type(const struct lyd_node_leaf_list *leaf);