libyang REFACTOR use freeing context

Fixes compiled extension memory leaks.
Refactoring included.
diff --git a/src/context.c b/src/context.c
index 593dff0..3a3c10b 100644
--- a/src/context.c
+++ b/src/context.c
@@ -45,6 +45,7 @@
 #include "tree_data.h"
 #include "tree_data_internal.h"
 #include "tree_schema.h"
+#include "tree_schema_free.h"
 #include "tree_schema_internal.h"
 
 #include "../models/ietf-datastores@2018-02-14.h"
@@ -1237,7 +1238,7 @@
 LIBYANG_API_DEF void
 ly_ctx_destroy(struct ly_ctx *ctx)
 {
-    struct lys_module *mod;
+    struct lysf_ctx fctx = {.ctx = ctx};
 
     if (!ctx) {
         return;
@@ -1245,18 +1246,21 @@
 
     /* models list */
     for ( ; ctx->list.count; ctx->list.count--) {
-        mod = ctx->list.objs[ctx->list.count - 1];
+        fctx.mod = ctx->list.objs[ctx->list.count - 1];
 
         /* remove the module */
-        if (mod->implemented) {
-            mod->implemented = 0;
-            lysc_module_free(mod->compiled);
-            mod->compiled = NULL;
+        if (fctx.mod->implemented) {
+            fctx.mod->implemented = 0;
+            lysc_module_free(&fctx, fctx.mod->compiled);
+            fctx.mod->compiled = NULL;
         }
-        lys_module_free(ctx->list.objs[ctx->list.count - 1], 0);
+        lys_module_free(&fctx, fctx.mod, 0);
     }
     free(ctx->list.objs);
 
+    /* free extensions */
+    lysf_ctx_erase(&fctx);
+
     /* search paths list */
     ly_set_erase(&ctx->search_paths, free);
 
diff --git a/src/parser_xml.c b/src/parser_xml.c
index 49b20fb..a1fd82c 100644
--- a/src/parser_xml.c
+++ b/src/parser_xml.c
@@ -1034,7 +1034,7 @@
 {
     LY_ERR rc = LY_SUCCESS;
     struct ly_ctx *ctx = (struct ly_ctx *)LYD_CTX(node);
-    struct lysc_ctx cctx = {.ctx = ctx};
+    struct lysc_ctx cctx;
     const struct lys_module *mod;
     LY_ARRAY_COUNT_TYPE u;
     struct ly_err_item *err = NULL;
@@ -1042,6 +1042,8 @@
     struct lysc_pattern **patterns = NULL;
     const char *value;
 
+    LYSC_CTX_INIT_CTX(cctx, ctx);
+
     /* get date-and-time parsed type */
     mod = ly_ctx_get_module_latest(ctx, "ietf-yang-types");
     assert(mod);
@@ -1062,7 +1064,7 @@
     rc = lyplg_type_validate_patterns(patterns, value, strlen(value), &err);
 
 cleanup:
-    FREE_ARRAY(ctx, patterns, lysc_pattern_free);
+    FREE_ARRAY(&cctx.free_ctx, patterns, lysc_pattern_free);
     if (rc && err) {
         LOGVAL_ERRITEM(ctx, err);
         ly_err_free(err);
diff --git a/src/parser_yang.c b/src/parser_yang.c
index cb0ff61..d0b2ea1 100644
--- a/src/parser_yang.c
+++ b/src/parser_yang.c
@@ -3,7 +3,7 @@
  * @author Michal Vasko <mvasko@cesnet.cz>
  * @brief YANG parser
  *
- * Copyright (c) 2018 CESNET, z.s.p.o.
+ * Copyright (c) 2018 - 2022 CESNET, z.s.p.o.
  *
  * This source code is licensed under BSD 3-Clause License (the "License").
  * You may not use this file except in compliance with the License.
@@ -32,6 +32,7 @@
 #include "tree.h"
 #include "tree_edit.h"
 #include "tree_schema.h"
+#include "tree_schema_free.h"
 #include "tree_schema_internal.h"
 
 struct lys_glob_unres;
@@ -1635,6 +1636,7 @@
     size_t word_len;
     enum ly_stmt kw;
     struct lysp_when *when;
+    struct lysf_ctx fctx = {.ctx = PARSER_CTX(ctx)};
 
     if (*when_p) {
         LOGVAL_PARSER(ctx, LY_VCODE_DUPSTMT, "when");
@@ -1669,7 +1671,7 @@
 
 cleanup:
     if (ret) {
-        lysp_when_free(PARSER_CTX(ctx), when);
+        lysp_when_free(&fctx, when);
         free(when);
     } else {
         *when_p = when;
@@ -3809,6 +3811,7 @@
     char *buf = NULL, *word;
     size_t word_len, dev_mod;
     enum ly_stmt kw;
+    struct lysf_ctx fctx = {.ctx = PARSER_CTX(ctx)};
     struct lysp_deviate *d = NULL;
     struct lysp_deviate_add *d_add = NULL;
     struct lysp_deviate_rpl *d_rpl = NULL;
@@ -4013,7 +4016,7 @@
 cleanup:
     free(buf);
     if (ret) {
-        lysp_deviate_free(PARSER_CTX(ctx), d);
+        lysp_deviate_free(&fctx, d);
         free(d);
     } else {
         /* insert into siblings */
@@ -4038,6 +4041,7 @@
     size_t word_len;
     enum ly_stmt kw;
     struct lysp_deviation *dev;
+    struct lysf_ctx fctx = {.ctx = PARSER_CTX(ctx)};
 
     LY_ARRAY_NEW_RET(PARSER_CTX(ctx), *deviations, dev, LY_EMEM);
 
@@ -4078,7 +4082,7 @@
 
 cleanup:
     if (ret) {
-        lysp_deviation_free(PARSER_CTX(ctx), dev);
+        lysp_deviation_free(&fctx, dev);
         LY_ARRAY_DECREMENT_FREE(*deviations);
     }
     return ret;
@@ -4653,6 +4657,7 @@
     size_t word_len;
     enum ly_stmt kw;
     struct lysp_submodule *mod_p = NULL;
+    struct lysf_ctx fctx = {.ctx = ly_ctx};
 
     assert(context && ly_ctx && main_ctx && in && submod);
 
@@ -4711,7 +4716,7 @@
 cleanup:
     LOG_LOCBACK(0, 0, 0, 1);
     if (ret) {
-        lysp_module_free((struct lysp_module *)mod_p);
+        lysp_module_free(&fctx, (struct lysp_module *)mod_p);
         yang_parser_ctx_free(*context);
         *context = NULL;
     }
@@ -4727,6 +4732,7 @@
     size_t word_len;
     enum ly_stmt kw;
     struct lysp_module *mod_p = NULL;
+    struct lysf_ctx fctx = {.ctx = mod->ctx};
 
     /* create context */
     *context = calloc(1, sizeof **context);
@@ -4779,7 +4785,7 @@
 cleanup:
     LOG_LOCBACK(0, 0, 0, 1);
     if (ret) {
-        lysp_module_free(mod_p);
+        lysp_module_free(&fctx, mod_p);
         yang_parser_ctx_free(*context);
         *context = NULL;
     }
diff --git a/src/parser_yin.c b/src/parser_yin.c
index 6dd7d6e..1e201b0 100644
--- a/src/parser_yin.c
+++ b/src/parser_yin.c
@@ -1,9 +1,10 @@
 /**
  * @file parser_yin.c
  * @author David Sedlák <xsedla1d@stud.fit.vutbr.cz>
+ * @author Michal Vasko <mvasko@cesnet.cz>
  * @brief YIN parser.
  *
- * Copyright (c) 2015 - 2019 CESNET, z.s.p.o.
+ * Copyright (c) 2015 - 2022 CESNET, z.s.p.o.
  *
  * This source code is licensed under BSD 3-Clause License (the "License").
  * You may not use this file except in compliance with the License.
@@ -2770,7 +2771,6 @@
  *
  * @param[in,out] ctx YIN parser context for logging and to store current state.
  * @param[in] deviations Deviations to add to.
- *
  * @return LY_ERR values.
  */
 static LY_ERR
@@ -2778,6 +2778,7 @@
 {
     LY_ERR ret = LY_SUCCESS;
     struct lysp_deviation *dev = NULL;
+    struct lysf_ctx fctx = {.ctx = PARSER_CTX(ctx)};
 
     /* create new deviation */
     LY_ARRAY_NEW_RET(ctx->xmlctx->ctx, *deviations, dev, LY_EMEM);
@@ -2797,7 +2798,7 @@
 
 cleanup:
     if (ret) {
-        lysp_deviation_free(PARSER_CTX(ctx), dev);
+        lysp_deviation_free(&fctx, dev);
         LY_ARRAY_DECREMENT_FREE(*deviations);
     }
     return ret;
@@ -2809,7 +2810,6 @@
  * @param[in] ctx YIN parser context used for logging.
  * @param[in] kw Keyword that is child of module or submodule.
  * @param[out] group Group of keyword.
- *
  * @return LY_SUCCESS on success LY_EINT if kw can't be mapped to kw_group, should not happen if called correctly.
  */
 static LY_ERR
@@ -2877,7 +2877,6 @@
  * @param[in] next_kw Next keyword.
  * @param[in] parrent Identification of parrent element, can be se to to LY_STMT_MODULE of LY_STMT_SUBMODULE,
  *            because relative order is required only in module and submodule sub-elements, used for logging.
- *
  * @return LY_SUCCESS on success and LY_EVALID if relative order is invalid.
  */
 static LY_ERR
@@ -2908,7 +2907,6 @@
  * @param[in,out] ctx Yin parser context for logging and to store current state.
  * @param[in] elem_type Type of element that is currently being parsed.
  * @param[out] arg Value to write to.
- *
  * @return LY_ERR values.
  */
 static LY_ERR
@@ -3062,7 +3060,6 @@
  * @param[in,out] ctx Yin parser context for XML context, logging, and to store current state.
  * @param[in] parent Identification of parent element.
  * @param[out] element Where the element structure should be stored.
- *
  * @return LY_ERR values.
  */
 LY_ERR
@@ -3183,7 +3180,6 @@
  * @param[in] subelem The statement this extension instance is a subelement of.
  * @param[in] subelem_index Index of the keyword instance this extension instance is a subelement of
  * @param[in,out] exts Extension instance to add to.
- *
  * @return LY_ERR values.
  */
 LY_ERR
@@ -3291,7 +3287,6 @@
  * @param[in] current_element Type of current element.
  * @param[out] text_content Where the text content of element should be stored if any. Text content is ignored if set to NULL.
  * @param[in,out] exts Extension instance to add to. Can be set to null if element cannot have extension as subelements.
- *
  * @return LY_ERR values.
  */
 LY_ERR
@@ -3595,7 +3590,6 @@
  *
  * @param[in,out] ctx Yin parser context for logging and to store current state.
  * @param[out] mod Parsed module structure.
- *
  * @return LY_ERR values.
  */
 LY_ERR
@@ -3661,7 +3655,6 @@
  * @param[in,out] ctx Yin parser context for logging and to store current state.
  * @param[in] mod_attrs Attributes of submodule element.
  * @param[out] submod Parsed submodule structure.
- *
  * @return LY_ERR values.
  */
 LY_ERR
@@ -3727,6 +3720,7 @@
     enum ly_stmt kw = LY_STMT_NONE;
     LY_ERR ret = LY_SUCCESS;
     struct lysp_submodule *mod_p = NULL;
+    struct lysf_ctx fctx = {.ctx = ctx};
 
     assert(yin_ctx && ctx && main_ctx && in && submod);
 
@@ -3781,7 +3775,7 @@
 
 cleanup:
     if (ret) {
-        lysp_module_free((struct lysp_module *)mod_p);
+        lysp_module_free(&fctx, (struct lysp_module *)mod_p);
         yin_parser_ctx_free(*yin_ctx);
         *yin_ctx = NULL;
     }
@@ -3794,6 +3788,7 @@
     LY_ERR ret = LY_SUCCESS;
     enum ly_stmt kw = LY_STMT_NONE;
     struct lysp_module *mod_p = NULL;
+    struct lysf_ctx fctx = {.ctx = mod->ctx};
 
     /* create context */
     *yin_ctx = calloc(1, sizeof **yin_ctx);
@@ -3843,7 +3838,7 @@
 
 cleanup:
     if (ret != LY_SUCCESS) {
-        lysp_module_free(mod_p);
+        lysp_module_free(&fctx, mod_p);
         yin_parser_ctx_free(*yin_ctx);
         *yin_ctx = NULL;
     }
diff --git a/src/path.c b/src/path.c
index 523a509..b6dc04a 100644
--- a/src/path.c
+++ b/src/path.c
@@ -1148,6 +1148,7 @@
 ly_path_predicates_free(const struct ly_ctx *ctx, enum ly_path_pred_type pred_type, struct ly_path_predicate *predicates)
 {
     LY_ARRAY_COUNT_TYPE u;
+    struct lysf_ctx fctx = {.ctx = (struct ly_ctx *)ctx};
 
     if (!predicates) {
         return;
@@ -1163,7 +1164,7 @@
         case LY_PATH_PREDTYPE_LEAFLIST:
             if (predicates[u].value.realtype) {
                 predicates[u].value.realtype->plugin->free(ctx, &predicates[u].value);
-                lysc_type_free((struct ly_ctx *)ctx, (struct lysc_type *)predicates[u].value.realtype);
+                lysc_type_free(&fctx, (struct lysc_type *)predicates[u].value.realtype);
             }
             break;
         }
diff --git a/src/schema_compile.c b/src/schema_compile.c
index f4aae9e..c02e628 100644
--- a/src/schema_compile.c
+++ b/src/schema_compile.c
@@ -44,6 +44,7 @@
 #include "tree.h"
 #include "tree_data.h"
 #include "tree_schema.h"
+#include "tree_schema_free.h"
 #include "tree_schema_internal.h"
 #include "xpath.h"
 
@@ -55,39 +56,30 @@
 {
     LY_ERR ret = LY_SUCCESS;
 
-    if (ext_p->compiled && (ext_p->compiled->refcount == 1)) {
-        /* context recompilation - all the extension instances were previously freed (the last link to the compiled extension
-         * remains from the parsed extension definition) and now we are recompiling them again, to have the up-to-date
-         * extension definition, we have to recompile it as well now */
-        lysc_extension_free(ctx->ctx, &ext_p->compiled);
-    }
-
     if (!ext_p->compiled) {
         lysc_update_path(ctx, NULL, "{extension}");
         lysc_update_path(ctx, NULL, ext_p->name);
 
         /* compile the extension definition */
-        ext_p->compiled = calloc(1, sizeof **ext);
-        ext_p->compiled->refcount = 2;
-        DUP_STRING_GOTO(ctx->ctx, ext_p->name, ext_p->compiled->name, ret, done);
-        DUP_STRING_GOTO(ctx->ctx, ext_p->argname, ext_p->compiled->argname, ret, done);
-        ext_p->compiled->module = (struct lys_module *)ext_mod;
-        COMPILE_EXTS_GOTO(ctx, ext_p->exts, ext_p->compiled->exts, *ext, ret, done);
+        *ext = ext_p->compiled = calloc(1, sizeof **ext);
+        (*ext)->refcount = 1;
+        DUP_STRING_GOTO(ctx->ctx, ext_p->name, (*ext)->name, ret, done);
+        DUP_STRING_GOTO(ctx->ctx, ext_p->argname, (*ext)->argname, ret, done);
+        (*ext)->module = (struct lys_module *)ext_mod;
+
+        /* compile nested extensions */
+        COMPILE_EXTS_GOTO(ctx, ext_p->exts, (*ext)->exts, *ext, ret, done);
 
         lysc_update_path(ctx, NULL, NULL);
         lysc_update_path(ctx, NULL, NULL);
 
         /* find extension definition plugin */
-        ext_p->compiled->plugin = lyplg_find(LYPLG_EXTENSION, ext_p->compiled->module->name,
-                ext_p->compiled->module->revision, ext_p->compiled->name);
-
-        /* refcount 2 already */
-        *ext = ext_p->compiled;
-    } else {
-        /* increase refcount */
-        *ext = lysc_ext_dup(ext_p->compiled);
+        (*ext)->plugin = lyplg_find(LYPLG_EXTENSION, (*ext)->module->name,
+                (*ext)->module->revision, (*ext)->name);
     }
 
+    *ext = ext_p->compiled;
+
 done:
     if (ret) {
         lysc_update_path(ctx, NULL, NULL);
@@ -126,7 +118,7 @@
         }
         ret = ext->def->plugin->compile(ctx, ext_p, ext);
         if (ret == LY_ENOT) {
-            lysc_ext_instance_free(ctx->ctx, ext);
+            lysc_ext_instance_free(&ctx->free_ctx, ext);
         }
         if (ext->argument) {
             lysc_update_path(ctx, NULL, NULL);
@@ -137,7 +129,6 @@
 cleanup:
     lysc_update_path(ctx, NULL, NULL);
     lysc_update_path(ctx, NULL, NULL);
-
     return ret;
 }
 
@@ -286,19 +277,19 @@
         const struct lysp_ident *identities_p, struct lysc_ident **identities)
 {
     LY_ARRAY_COUNT_TYPE u;
-    struct lysc_ctx context = {0};
+    struct lysc_ctx cctx;
     struct lysc_ident *ident;
     LY_ERR ret = LY_SUCCESS;
 
     assert(ctx_sc || ctx);
 
     if (!ctx_sc) {
-        context.ctx = ctx;
-        context.cur_mod = parsed_mod ? parsed_mod->mod : NULL;
-        context.pmod = parsed_mod;
-        context.path_len = 1;
-        context.path[0] = '/';
-        ctx_sc = &context;
+        if (parsed_mod) {
+            LYSC_CTX_INIT_PMOD(cctx, parsed_mod);
+        } else {
+            LYSC_CTX_INIT_CTX(cctx, ctx);
+        }
+        ctx_sc = &cctx;
     }
 
     if (!identities_p) {
@@ -657,7 +648,7 @@
                     LY_CHECK_GOTO(rc = lysp_stmt_parse(ctx, stmt, &parsed, NULL), cleanup);
                     r = lys_compile_type(ctx, NULL, flags ? *flags : 0, ext_p->name, parsed, (struct lysc_type **)compiled,
                             (units && !*units) ? units : NULL, NULL);
-                    lysp_type_free(ctx->ctx, parsed);
+                    lysp_type_free(&ctx->free_ctx, parsed);
                     free(parsed);
                     LY_CHECK_ERR_GOTO(r, rc = r, cleanup);
                     break;
@@ -1033,7 +1024,7 @@
  * @param[in] items Sized array of bits/enums.
  */
 static void
-lys_compile_unres_disabled_bitenum_remove(struct ly_ctx *ctx, struct lysc_type_bitenum_item *items)
+lys_compile_unres_disabled_bitenum_remove(struct lysf_ctx *ctx, struct lysc_type_bitenum_item *items)
 {
     LY_ARRAY_COUNT_TYPE u = 0, last_u;
 
@@ -1082,7 +1073,7 @@
         if ((t[u]->basetype == LY_TYPE_BITS) || (t[u]->basetype == LY_TYPE_ENUM)) {
             /* remove all disabled items */
             ent = (struct lysc_type_enum *)(t[u]);
-            lys_compile_unres_disabled_bitenum_remove(ctx->ctx, ent->enums);
+            lys_compile_unres_disabled_bitenum_remove(&ctx->free_ctx, ent->enums);
 
             if (!LY_ARRAY_COUNT(ent->enums)) {
                 LOGVAL(ctx->ctx, LYVE_SEMANTICS, "%s type of node \"%s\" without any (or all disabled) valid values.",
@@ -1384,22 +1375,16 @@
     struct lysc_node *node;
     struct lysc_type *typeiter;
     struct lysc_type_leafref *lref;
-    struct lysc_ctx cctx;
-    struct lys_depset_unres *ds_unres;
+    struct lysc_ctx cctx = {0};
+    struct lys_depset_unres *ds_unres = &unres->ds_unres;
     struct ly_path *path;
     LY_ARRAY_COUNT_TYPE v;
     struct lysc_unres_leafref *l;
+    struct lysc_unres_must *m;
+    struct lysc_unres_dflt *r;
     uint32_t i, processed_leafrefs = 0;
 
-    ds_unres = &unres->ds_unres;
-
-    /* fake compile context */
 resolve_all:
-    memset(&cctx, 0, sizeof cctx);
-    cctx.ctx = ctx;
-    cctx.path_len = 1;
-    cctx.path[0] = '/';
-
     /* for leafref, we need 2 rounds - first detects circular chain by storing the first referred type (which
      * can be also leafref, in case it is already resolved, go through the chain and check that it does not
      * point to the starting leafref type). The second round stores the first non-leafref type for later data validation.
@@ -1408,8 +1393,7 @@
         /* remember index, it can change before we get to free this item */
         i = ds_unres->disabled_leafrefs.count - 1;
         l = ds_unres->disabled_leafrefs.objs[i];
-        cctx.cur_mod = l->node->module;
-        cctx.pmod = l->node->module->parsed;
+        LYSC_CTX_INIT_PMOD(cctx, l->node->module->parsed);
 
         LOG_LOCSET(l->node, NULL, NULL, NULL);
         v = 0;
@@ -1417,24 +1401,22 @@
             ret = lys_compile_unres_leafref(&cctx, l->node, lref, l->local_mod, unres);
         }
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
 
         ly_set_rm_index(&ds_unres->disabled_leafrefs, i, free);
     }
 
     for (i = processed_leafrefs; i < ds_unres->leafrefs.count; ++i) {
         l = ds_unres->leafrefs.objs[i];
-        cctx.cur_mod = l->node->module;
-        cctx.pmod = l->node->module->parsed;
-        LOG_LOCSET(l->node, NULL, NULL, NULL);
+        LYSC_CTX_INIT_PMOD(cctx, l->node->module->parsed);
 
+        LOG_LOCSET(l->node, NULL, NULL, NULL);
         v = 0;
         while ((ret == LY_SUCCESS) && (lref = lys_type_leafref_next(l->node, &v))) {
             ret = lys_compile_unres_leafref(&cctx, l->node, lref, l->local_mod, unres);
         }
-
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
     }
     for (i = processed_leafrefs; i < ds_unres->leafrefs.count; ++i) {
         l = ds_unres->leafrefs.objs[i];
@@ -1446,7 +1428,7 @@
                     typeiter->basetype == LY_TYPE_LEAFREF;
                     typeiter = ((struct lysc_type_leafref *)typeiter)->realtype) {}
 
-            lysc_type_free(ctx, lref->realtype);
+            lysc_type_free(&cctx.free_ctx, lref->realtype);
             lref->realtype = typeiter;
             ++lref->realtype->refcount;
         }
@@ -1461,13 +1443,12 @@
     while (ds_unres->whens.count) {
         i = ds_unres->whens.count - 1;
         node = ds_unres->whens.objs[i];
-        cctx.cur_mod = node->module;
-        cctx.pmod = node->module->parsed;
+        LYSC_CTX_INIT_PMOD(cctx, node->module->parsed);
 
         LOG_LOCSET(node, NULL, NULL, NULL);
         ret = lys_compile_unres_when(&cctx, node, unres);
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
 
         ly_set_rm_index(&ds_unres->whens, i, NULL);
     }
@@ -1475,15 +1456,13 @@
     /* check must */
     while (ds_unres->musts.count) {
         i = ds_unres->musts.count - 1;
-        struct lysc_unres_must *m = ds_unres->musts.objs[i];
-
-        cctx.cur_mod = m->node->module;
-        cctx.pmod = m->node->module->parsed;
+        m = ds_unres->musts.objs[i];
+        LYSC_CTX_INIT_PMOD(cctx, m->node->module->parsed);
 
         LOG_LOCSET(m->node, NULL, NULL, NULL);
         ret = lys_compile_unres_must(&cctx, m->node, m->local_mods, unres);
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
 
         lysc_unres_must_free(m);
         ly_set_rm_index(&ds_unres->musts, i, NULL);
@@ -1493,13 +1472,12 @@
     while (ds_unres->disabled_bitenums.count) {
         i = ds_unres->disabled_bitenums.count - 1;
         node = ds_unres->disabled_bitenums.objs[i];
-        cctx.cur_mod = node->module;
-        cctx.pmod = node->module->parsed;
+        LYSC_CTX_INIT_PMOD(cctx, node->module->parsed);
 
         LOG_LOCSET(node, NULL, NULL, NULL);
         ret = lys_compile_unres_disabled_bitenum(&cctx, (struct lysc_node_leaf *)node);
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
 
         ly_set_rm_index(&ds_unres->disabled_bitenums, i, NULL);
     }
@@ -1507,10 +1485,8 @@
     /* finish incomplete default values compilation */
     while (ds_unres->dflts.count) {
         i = ds_unres->dflts.count - 1;
-        struct lysc_unres_dflt *r = ds_unres->dflts.objs[i];
-
-        cctx.cur_mod = r->leaf->module;
-        cctx.pmod = r->leaf->module->parsed;
+        r = ds_unres->dflts.objs[i];
+        LYSC_CTX_INIT_PMOD(cctx, r->leaf->module->parsed);
 
         LOG_LOCSET(&r->leaf->node, NULL, NULL, NULL);
         if (r->leaf->nodetype == LYS_LEAF) {
@@ -1519,7 +1495,7 @@
             ret = lys_compile_unres_llist_dflts(&cctx, r->llist, r->dflt, r->dflts, unres);
         }
         LOG_LOCBACK(1, 0, 0, 0);
-        LY_CHECK_RET(ret);
+        LY_CHECK_GOTO(ret, cleanup);
 
         lysc_unres_dflt_free(ctx, r);
         ly_set_rm_index(&ds_unres->dflts, i, NULL);
@@ -1538,17 +1514,18 @@
             LOG_LOCSET(node, NULL, NULL, NULL);
             LOGVAL(ctx, LYVE_REFERENCE, "Key \"%s\" is disabled.", node->name);
             LOG_LOCBACK(1, 0, 0, 0);
-            return LY_EVALID;
+            ret = LY_EVALID;
+            goto cleanup;
         }
+        LYSC_CTX_INIT_PMOD(cctx, node->module->parsed);
 
-        lysc_node_free(ctx, node, 1);
+        lysc_node_free(&cctx.free_ctx, node, 1);
     }
 
     /* also check if the leafref target has not been disabled */
     for (i = 0; i < ds_unres->leafrefs.count; ++i) {
         l = ds_unres->leafrefs.objs[i];
-        cctx.cur_mod = l->node->module;
-        cctx.pmod = l->node->module->parsed;
+        LYSC_CTX_INIT_PMOD(cctx, l->node->module->parsed);
 
         v = 0;
         while ((lref = lys_type_leafref_next(l->node, &v))) {
@@ -1563,12 +1540,15 @@
                 LOGVAL(ctx, LYVE_REFERENCE, "Target of leafref \"%s\" cannot be referenced because it is disabled.",
                         l->node->name);
                 LOG_LOCBACK(1, 0, 0, 0);
-                return LY_EVALID;
+                ret = LY_EVALID;
+                goto cleanup;
             }
         }
     }
 
-    return LY_SUCCESS;
+cleanup:
+    lysf_ctx_erase(&cctx.free_ctx);
+    return ret;
 }
 
 /**
@@ -1609,6 +1589,7 @@
 lys_compile_depset_r(struct ly_ctx *ctx, struct ly_set *dep_set, struct lys_glob_unres *unres)
 {
     LY_ERR ret = LY_SUCCESS;
+    struct lysf_ctx fctx = {.ctx = ctx};
     struct lys_module *mod;
     uint32_t i;
 
@@ -1621,7 +1602,7 @@
         assert(mod->implemented);
 
         /* free the compiled module, if any */
-        lysc_module_free(mod->compiled);
+        lysc_module_free(&fctx, mod->compiled);
         mod->compiled = NULL;
 
         /* (re)compile the module */
@@ -1647,6 +1628,7 @@
 
 cleanup:
     lys_compile_unres_depset_erase(ctx, unres);
+    lysf_ctx_erase(&fctx);
     return ret;
 }
 
@@ -1782,7 +1764,7 @@
 LY_ERR
 lys_compile(struct lys_module *mod, struct lys_depset_unres *unres)
 {
-    struct lysc_ctx ctx = {0};
+    struct lysc_ctx ctx;
     struct lysc_module *mod_c = NULL;
     struct lysp_module *sp;
     struct lysp_submodule *submod;
@@ -1796,12 +1778,7 @@
     assert(mod->implemented && mod->to_compile);
 
     sp = mod->parsed;
-
-    ctx.ctx = mod->ctx;
-    ctx.cur_mod = mod;
-    ctx.pmod = sp;
-    ctx.path_len = 1;
-    ctx.path[0] = '/';
+    LYSC_CTX_INIT_PMOD(ctx, sp);
     ctx.unres = unres;
 
     ++mod->ctx->change_count;
@@ -1898,7 +1875,7 @@
     LOG_LOCBACK(0, 0, 1, 0);
     lys_compile_unres_mod_erase(&ctx, ret);
     if (ret) {
-        lysc_module_free(mod_c);
+        lysc_module_free(&ctx.free_ctx, mod_c);
         mod->compiled = NULL;
     }
     return ret;
@@ -1908,7 +1885,7 @@
 lys_compile_identities(struct lys_module *mod)
 {
     LY_ERR rc = LY_SUCCESS;
-    struct lysc_ctx ctx = {0};
+    struct lysc_ctx ctx;
     struct lysp_submodule *submod;
     LY_ARRAY_COUNT_TYPE u;
 
@@ -1922,11 +1899,7 @@
     }
 
     /* prepare context */
-    ctx.ctx = mod->ctx;
-    ctx.cur_mod = mod;
-    ctx.pmod = mod->parsed;
-    ctx.path_len = 1;
-    ctx.path[0] = '/';
+    LYSC_CTX_INIT_PMOD(ctx, mod->parsed);
 
     if (mod->parsed->identities) {
         rc = lys_compile_identities_derived(&ctx, mod->parsed->identities, &mod->identities);
diff --git a/src/schema_compile.h b/src/schema_compile.h
index ef51185..c68fd43 100644
--- a/src/schema_compile.h
+++ b/src/schema_compile.h
@@ -4,7 +4,7 @@
  * @author Michal Vasko <mvasko@cesnet.cz>
  * @brief Header for schema compilation.
  *
- * Copyright (c) 2015 - 2021 CESNET, z.s.p.o.
+ * Copyright (c) 2015 - 2022 CESNET, z.s.p.o.
  *
  * This source code is licensed under BSD 3-Clause License (the "License").
  * You may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
 #include "set.h"
 #include "tree.h"
 #include "tree_schema.h"
+#include "tree_schema_free.h"
 
 struct lyxp_expr;
 
@@ -52,12 +53,41 @@
     struct lys_depset_unres *unres; /**< dependency set unres sets */
     uint32_t path_len;          /**< number of path bytes used */
     uint32_t compile_opts;      /**< various @ref scflags. */
+    struct lysf_ctx free_ctx;   /**< freeing context for errors/recompilation */
 
 #define LYSC_CTX_BUFSIZE 4078
     char path[LYSC_CTX_BUFSIZE];/**< Path identifying the schema node currently being processed */
 };
 
 /**
+ * @brief Initalize local compilation context using libyang context.
+ *
+ * @param[out] CCTX Compile context.
+ * @param[in] CTX libyang context.
+ */
+#define LYSC_CTX_INIT_CTX(CCTX, CTX) \
+    memset(&(CCTX), 0, sizeof (CCTX)); \
+    (CCTX).ctx = (CTX); \
+    (CCTX).path_len = 1; \
+    (CCTX).path[0] = '/'; \
+    (CCTX).free_ctx.ctx = (CTX)
+
+/**
+ * @brief Initalize local compilation context using a parsed module.
+ *
+ * @param[out] CCTX Compile context.
+ * @param[in] PMOD Parsed module.
+ */
+#define LYSC_CTX_INIT_PMOD(CCTX, PMOD) \
+    memset(&(CCTX), 0, sizeof (CCTX)); \
+    (CCTX).ctx = (PMOD)->mod->ctx; \
+    (CCTX).cur_mod = (PMOD)->mod; \
+    (CCTX).pmod = (PMOD); \
+    (CCTX).path_len = 1; \
+    (CCTX).path[0] = '/'; \
+    (CCTX).free_ctx.ctx = (PMOD)->mod->ctx
+
+/**
  * @brief Structure for unresolved items that may depend on any implemented module data in the dependency set
  * so their resolution can only be performed after the whole dep set compilation is done.
  */
diff --git a/src/schema_compile_amend.c b/src/schema_compile_amend.c
index 37fb351..bab8ba3 100644
--- a/src/schema_compile_amend.c
+++ b/src/schema_compile_amend.c
@@ -1099,7 +1099,7 @@
     LY_ARRAY_COUNT_TYPE u, v;
     struct lysp_qname **uniques, **dflts;
 
-#define DEV_DEL_ARRAY(DEV_ARRAY, ORIG_ARRAY, DEV_MEMBER, ORIG_MEMBER, FREE_FUNC, PROPERTY) \
+#define DEV_DEL_ARRAY(DEV_ARRAY, ORIG_ARRAY, DEV_MEMBER, ORIG_MEMBER, FREE_FUNC, FREE_CTX, PROPERTY) \
     LY_ARRAY_FOR(d->DEV_ARRAY, u) { \
         int found = 0; \
         LY_ARRAY_FOR(ORIG_ARRAY, v) { \
@@ -1116,7 +1116,7 @@
             goto cleanup; \
         } \
         LY_ARRAY_DECREMENT(ORIG_ARRAY); \
-        FREE_FUNC(ctx->ctx, &(ORIG_ARRAY)[v]); \
+        FREE_FUNC(FREE_CTX, &(ORIG_ARRAY)[v]); \
         if (v < LY_ARRAY_COUNT(ORIG_ARRAY)) { \
             memmove(&(ORIG_ARRAY)[v], &(ORIG_ARRAY)[v + 1], (LY_ARRAY_COUNT(ORIG_ARRAY) - v) * sizeof *(ORIG_ARRAY)); \
         } \
@@ -1161,7 +1161,7 @@
             AMEND_WRONG_NODETYPE("deviation", "delete", "must");
         }
 
-        DEV_DEL_ARRAY(musts, *musts, .arg.str, .arg.str, lysp_restr_free, "must");
+        DEV_DEL_ARRAY(musts, *musts, .arg.str, .arg.str, lysp_restr_free, &ctx->free_ctx, "must");
     }
 
     /* *unique-stmt */
@@ -1174,7 +1174,7 @@
         }
 
         uniques = &((struct lysp_node_list *)target)->uniques;
-        DEV_DEL_ARRAY(uniques, *uniques, .str, .str, lysp_qname_free, "unique");
+        DEV_DEL_ARRAY(uniques, *uniques, .str, .str, lysp_qname_free, ctx->ctx, "unique");
     }
 
     /* *default-stmt */
@@ -1189,7 +1189,7 @@
             break;
         case LYS_LEAFLIST:
             dflts = &((struct lysp_node_leaflist *)target)->dflts;
-            DEV_DEL_ARRAY(dflts, *dflts, .str, .str, lysp_qname_free, "default");
+            DEV_DEL_ARRAY(dflts, *dflts, .str, .str, lysp_qname_free, ctx->ctx, "default");
             break;
         case LYS_CHOICE:
             AMEND_CHECK_CARDINALITY(d->dflts, 1, "deviation", "default");
@@ -1238,7 +1238,7 @@
             AMEND_WRONG_NODETYPE("deviation", "replace", "type");
         }
 
-        lysp_type_free(ctx->ctx, &((struct lysp_node_leaf *)target)->type);
+        lysp_type_free(&ctx->free_ctx, &((struct lysp_node_leaf *)target)->type);
         lysp_type_dup(ctx->ctx, &((struct lysp_node_leaf *)target)->type, d->type);
     }
 
@@ -1551,7 +1551,7 @@
 }
 
 void
-lysp_dev_node_free(const struct ly_ctx *ctx, struct lysp_node *dev_pnode)
+lysp_dev_node_free(struct lysc_ctx *cctx, struct lysp_node *dev_pnode)
 {
     if (!dev_pnode) {
         return;
@@ -1591,15 +1591,15 @@
     case LYS_INPUT:
     case LYS_OUTPUT:
         ((struct lysp_node_action_inout *)dev_pnode)->child = NULL;
-        lysp_node_free((struct ly_ctx *)ctx, dev_pnode);
+        lysp_node_free(&cctx->free_ctx, dev_pnode);
         free(dev_pnode);
         return;
     default:
-        LOGINT(ctx);
+        LOGINT(cctx->ctx);
         return;
     }
 
-    lysp_node_free((struct ly_ctx *)ctx, dev_pnode);
+    lysp_node_free(&cctx->free_ctx, dev_pnode);
 }
 
 LY_ERR
@@ -1725,7 +1725,7 @@
     ctx->cur_mod = orig_mod;
     ctx->pmod = orig_pmod;
     if (ret) {
-        lysp_dev_node_free(ctx->ctx, *dev_pnode);
+        lysp_dev_node_free(ctx, *dev_pnode);
         *dev_pnode = NULL;
         *not_supported = 0;
     }
@@ -2212,7 +2212,7 @@
 {
     LY_ERR ret = LY_SUCCESS, r;
     LY_ARRAY_COUNT_TYPE u, v;
-    struct lysc_ctx ctx = {0};
+    struct lysc_ctx ctx;
     struct lysp_module *mod_p;
     struct lys_module *m;
     struct lysp_submodule *submod;
@@ -2222,13 +2222,7 @@
     struct ly_set mod_set = {0}, set = {0};
 
     mod_p = mod->parsed;
-
-    /* prepare context */
-    ctx.ctx = mod->ctx;
-    ctx.cur_mod = mod;
-    ctx.pmod = mod_p;
-    ctx.path_len = 1;
-    ctx.path[0] = '/';
+    LYSC_CTX_INIT_PMOD(ctx, mod_p);
 
     LY_LIST_FOR(mod_p->augments, aug) {
         /* get target module */
diff --git a/src/schema_compile_amend.h b/src/schema_compile_amend.h
index 9fe5c65..581dfae 100644
--- a/src/schema_compile_amend.h
+++ b/src/schema_compile_amend.h
@@ -115,7 +115,7 @@
  * @param[in] ctx libyang context.
  * @param[in] dev_pnode Parsed node to free.
  */
-void lysp_dev_node_free(const struct ly_ctx *ctx, struct lysp_node *dev_pnode);
+void lysp_dev_node_free(struct lysc_ctx *cctx, struct lysp_node *dev_pnode);
 
 /**
  * @brief Compile and apply any precompiled deviations and refines targeting a node.
diff --git a/src/schema_compile_node.c b/src/schema_compile_node.c
index 86621c9..881759e 100644
--- a/src/schema_compile_node.c
+++ b/src/schema_compile_node.c
@@ -1595,7 +1595,7 @@
             --additional;
 
             /* free the replaced union subtype */
-            lysc_type_free(ctx->ctx, (struct lysc_type *)un_aux);
+            lysc_type_free(&ctx->free_ctx, (struct lysc_type *)un_aux);
             un_aux = NULL;
         } else {
             LY_ARRAY_INCREMENT(utypes);
@@ -1607,7 +1607,7 @@
 
 error:
     if (un_aux) {
-        lysc_type_free(ctx->ctx, (struct lysc_type *)un_aux);
+        lysc_type_free(&ctx->free_ctx, (struct lysc_type *)un_aux);
     }
     *utypes_p = utypes;
     return ret;
@@ -2002,7 +2002,7 @@
         if (tctx->tpdf->type.compiled && (tctx->tpdf->type.compiled->refcount == 1)) {
             /* context recompilation - everything was freed previously (the only reference is from the parsed type itself)
              * and we need now recompile the type again in the updated context. */
-            lysc_type_free(ctx->ctx, tctx->tpdf->type.compiled);
+            lysc_type_free(&ctx->free_ctx, tctx->tpdf->type.compiled);
             ((struct lysp_tpdf *)tctx->tpdf)->type.compiled = NULL;
         }
 
@@ -2627,13 +2627,14 @@
     goto cleanup;
 
 error:
-    lysc_node_free(ctx->ctx, node, 0);
+    lysc_node_free(&ctx->free_ctx, node, 0);
+
 cleanup:
     if (ret && dev_pnode) {
         LOGVAL(ctx->ctx, LYVE_OTHER, "Compilation of a deviated and/or refined node failed.");
     }
     ctx->compile_opts = prev_opts;
-    lysp_dev_node_free(ctx->ctx, dev_pnode);
+    lysp_dev_node_free(ctx, dev_pnode);
     return ret;
 }
 
@@ -3340,13 +3341,12 @@
         }
 
         /* check status */
-        LY_CHECK_RET(lysc_check_status(ctx, list->flags, list->module, list->name,
-                key->flags, key->module, key->name));
+        LY_CHECK_RET(lysc_check_status(ctx, list->flags, list->module, list->name, key->flags, key->module, key->name));
 
         /* ignore default values of the key */
         if (key->dflt) {
             key->dflt->realtype->plugin->free(ctx->ctx, key->dflt);
-            lysc_type_free(ctx->ctx, (struct lysc_type *)key->dflt->realtype);
+            lysc_type_free(&ctx->free_ctx, (struct lysc_type *)key->dflt->realtype);
             free(key->dflt);
             key->dflt = NULL;
         }
@@ -3540,7 +3540,7 @@
 revert_sh_case:
         /* free the parsed shorthand case and correct pointers back */
         cs_p->child = NULL;
-        lysp_node_free(ctx->ctx, (struct lysp_node *)cs_p);
+        lysp_node_free(&ctx->free_ctx, (struct lysp_node *)cs_p);
         child_p->next = child_p_next;
     }
 
@@ -4080,7 +4080,7 @@
     ctx->path[1] = '\0';
 
     /* cleanup */
-    lysc_node_container_free(ctx->ctx, &fake_container);
+    lysc_node_container_free(&ctx->free_ctx, &fake_container);
 
     return ret;
 }
diff --git a/src/schema_features.c b/src/schema_features.c
index e770cd7..f70968f 100644
--- a/src/schema_features.c
+++ b/src/schema_features.c
@@ -506,6 +506,7 @@
     LY_ERR ret;
     LY_ARRAY_COUNT_TYPE u;
     struct lysc_iffeature iff;
+    struct lysf_ctx fctx = {.ctx = (struct ly_ctx *)ctx};
 
     /* enabled by default */
     *enabled = 1;
@@ -520,7 +521,7 @@
         LY_CHECK_RET(lys_compile_iffeature(ctx, &iffeatures[u], &iff));
 
         ret = lysc_iffeature_value(&iff);
-        lysc_iffeature_free((struct ly_ctx *)ctx, &iff);
+        lysc_iffeature_free(&fctx, &iff);
         if (ret == LY_ENOT) {
             *enabled = 0;
             break;
diff --git a/src/tree_schema.c b/src/tree_schema.c
index 4a247cb..000c115 100644
--- a/src/tree_schema.c
+++ b/src/tree_schema.c
@@ -43,6 +43,7 @@
 #include "set.h"
 #include "tree.h"
 #include "tree_edit.h"
+#include "tree_schema_free.h"
 #include "tree_schema_internal.h"
 #include "xpath.h"
 
@@ -1146,43 +1147,46 @@
 lys_unres_glob_revert(struct ly_ctx *ctx, struct lys_glob_unres *unres)
 {
     uint32_t i, j, idx, prev_lo;
+    struct lysf_ctx fctx = {.ctx = ctx};
     struct ly_set *dep_set;
-    struct lys_module *m;
     LY_ERR ret;
 
     for (i = 0; i < unres->implementing.count; ++i) {
-        m = unres->implementing.objs[i];
-        assert(m->implemented);
+        fctx.mod = unres->implementing.objs[i];
+        assert(fctx.mod->implemented);
 
         /* make the module correctly non-implemented again */
-        m->implemented = 0;
-        lys_precompile_augments_deviations_revert(ctx, m);
-        lysc_module_free(m->compiled);
-        m->compiled = NULL;
+        fctx.mod->implemented = 0;
+        lys_precompile_augments_deviations_revert(ctx, fctx.mod);
+        lysc_module_free(&fctx, fctx.mod->compiled);
+        fctx.mod->compiled = NULL;
 
         /* should not be made implemented */
-        m->to_compile = 0;
+        fctx.mod->to_compile = 0;
     }
 
     for (i = 0; i < unres->creating.count; ++i) {
-        m = unres->creating.objs[i];
+        fctx.mod = unres->creating.objs[i];
 
         /* remove the module from the context */
-        ly_set_rm(&ctx->list, m, NULL);
+        ly_set_rm(&ctx->list, fctx.mod, NULL);
 
         /* remove it also from dep sets */
         for (j = 0; j < unres->dep_sets.count; ++j) {
             dep_set = unres->dep_sets.objs[j];
-            if (ly_set_contains(dep_set, m, &idx)) {
+            if (ly_set_contains(dep_set, fctx.mod, &idx)) {
                 ly_set_rm_index(dep_set, idx, NULL);
                 break;
             }
         }
 
         /* free the module */
-        lys_module_free(m, 1);
+        lys_module_free(&fctx, fctx.mod, 1);
     }
 
+    /* remove the extensions as well */
+    lysf_ctx_erase(&fctx);
+
     if (unres->implementing.count) {
         /* recompile previous context because some implemented modules are no longer implemented,
          * we can reuse the current to_compile flags */
@@ -1290,6 +1294,7 @@
     struct lys_yang_parser_ctx *yangctx = NULL;
     struct lys_yin_parser_ctx *yinctx = NULL;
     struct lys_parser_ctx *pctx;
+    struct lysf_ctx fctx = {.ctx = ctx};
 
     LY_CHECK_ARG_RET(ctx, ctx, in, LY_EINVAL);
 
@@ -1361,7 +1366,7 @@
     } else {
         LOGERR(ctx, ret, "Parsing submodule \"%s\" failed.", submod->name);
     }
-    lysp_module_free((struct lysp_module *)submod);
+    lysp_module_free(&fctx, (struct lysp_module *)submod);
     if (format == LYS_IN_YANG) {
         yang_parser_ctx_free(yangctx);
     } else {
@@ -1593,6 +1598,7 @@
     struct lys_yang_parser_ctx *yangctx = NULL;
     struct lys_yin_parser_ctx *yinctx = NULL;
     struct lys_parser_ctx *pctx = NULL;
+    struct lysf_ctx fctx = {.ctx = ctx};
     char *filename, *rev, *dot;
     size_t len;
     ly_bool module_created = 0;
@@ -1762,7 +1768,10 @@
         }
     }
     if (!module_created) {
-        lys_module_free(mod, 0);
+        fctx.mod = mod;
+        lys_module_free(&fctx, mod, 0);
+        lysf_ctx_erase(&fctx);
+
         mod = mod_dup;
     }
 
diff --git a/src/tree_schema.h b/src/tree_schema.h
index 8dfd965..32044a8 100644
--- a/src/tree_schema.h
+++ b/src/tree_schema.h
@@ -1429,7 +1429,7 @@
     struct lysc_ext_instance *exts;  /**< list of the extension instances ([sized array](@ref sizedarrays)) */
     struct lyplg_ext *plugin;        /**< Plugin implementing the specific extension */
     struct lys_module *module;       /**< module structure */
-    uint32_t refcount;               /**< reference counter since extension definition is shared among all its instances */
+    uint32_t refcount;               /**< unused, always 1 */
     uint16_t flags;                  /**< LYS_STATUS_* value (@ref snodeflags) */
 };
 
diff --git a/src/tree_schema_free.c b/src/tree_schema_free.c
index 409a56a..71536d3 100644
--- a/src/tree_schema_free.c
+++ b/src/tree_schema_free.c
@@ -1,9 +1,10 @@
 /**
  * @file tree_schema_free.c
  * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @author Michal Vasko <mvasko@cesnet.cz>
  * @brief Freeing functions for schema tree structures.
  *
- * Copyright (c) 2019 CESNET, z.s.p.o.
+ * Copyright (c) 2019 - 2022 CESNET, z.s.p.o.
  *
  * This source code is licensed under BSD 3-Clause License (the "License").
  * You may not use this file except in compliance with the License.
@@ -12,6 +13,8 @@
  *     https://opensource.org/licenses/BSD-3-Clause
  */
 
+#include "tree_schema_free.h"
+
 #include <assert.h>
 #include <stdlib.h>
 
@@ -30,9 +33,23 @@
 #include "xml.h"
 #include "xpath.h"
 
-static void lysp_grp_free(struct ly_ctx *ctx, struct lysp_node_grp *grp);
-static void lysc_node_free_(struct ly_ctx *ctx, struct lysc_node *node);
+static void lysc_extension_free(struct lysf_ctx *ctx, struct lysc_ext **ext);
+static void lysc_node_free_(struct lysf_ctx *ctx, struct lysc_node *node);
 
+void
+lysp_qname_free(struct ly_ctx *ctx, struct lysp_qname *qname)
+{
+    if (qname) {
+        lydict_remove(ctx, qname->str);
+    }
+}
+
+/**
+ * @brief Free the parsed generic statement structure.
+ *
+ * @param[in] ctx libyang context.
+ * @param[in] grp Parsed schema statement structure to free. Note that the structure itself is not freed.
+ */
 static void
 lysp_stmt_free(struct ly_ctx *ctx, struct lysp_stmt *stmt)
 {
@@ -49,32 +66,38 @@
     free(stmt);
 }
 
-static void
-lysp_ext_instance_free(struct ly_ctx *ctx, struct lysp_ext_instance *ext)
+void
+lysp_ext_instance_free(struct lysf_ctx *ctx, struct lysp_ext_instance *ext)
 {
     struct lysp_stmt *stmt, *next;
     struct lysp_node *node, *next_node;
 
-    lydict_remove(ctx, ext->name);
-    lydict_remove(ctx, ext->argument);
+    lydict_remove(ctx->ctx, ext->name);
+    lydict_remove(ctx->ctx, ext->argument);
     ly_free_prefix_data(ext->format, ext->prefix_data);
     LY_LIST_FOR_SAFE(ext->parsed, next_node, node) {
         lysp_node_free(ctx, node);
     }
 
     LY_LIST_FOR_SAFE(ext->child, next, stmt) {
-        lysp_stmt_free(ctx, stmt);
+        lysp_stmt_free(ctx->ctx, stmt);
     }
 }
 
+/**
+ * @brief Free the parsed import structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] import Parsed schema import structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_import_free(struct ly_ctx *ctx, struct lysp_import *import)
+lysp_import_free(struct lysf_ctx *ctx, struct lysp_import *import)
 {
     /* imported module is freed directly from the context's list */
-    lydict_remove(ctx, import->name);
-    lydict_remove(ctx, import->prefix);
-    lydict_remove(ctx, import->dsc);
-    lydict_remove(ctx, import->ref);
+    lydict_remove(ctx->ctx, import->name);
+    lydict_remove(ctx->ctx, import->prefix);
+    lydict_remove(ctx->ctx, import->dsc);
+    lydict_remove(ctx->ctx, import->ref);
     FREE_ARRAY(ctx, import->exts, lysp_ext_instance_free);
 }
 
@@ -91,105 +114,147 @@
  * is supposed to be freed.
  */
 static void
-lysp_include_free_(struct ly_ctx *ctx, struct lysp_include *include, ly_bool main_module)
+lysp_include_free_(struct lysf_ctx *ctx, struct lysp_include *include, ly_bool main_module)
 {
     if (main_module && include->submodule) {
-        lysp_module_free((struct lysp_module *)include->submodule);
+        lysp_module_free(ctx, (struct lysp_module *)include->submodule);
     }
-    lydict_remove(ctx, include->name);
-    lydict_remove(ctx, include->dsc);
-    lydict_remove(ctx, include->ref);
+    lydict_remove(ctx->ctx, include->name);
+    lydict_remove(ctx->ctx, include->dsc);
+    lydict_remove(ctx->ctx, include->ref);
     FREE_ARRAY(ctx, include->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed include structure of a submodule.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] include Parsed schema include structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_include_free_submodule(struct ly_ctx *ctx, struct lysp_include *include)
+lysp_include_free_submodule(struct lysf_ctx *ctx, struct lysp_include *include)
 {
     lysp_include_free_(ctx, include, 0);
 }
 
+/**
+ * @brief Free the parsed include structure of a module.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] include Parsed schema include structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_include_free(struct ly_ctx *ctx, struct lysp_include *include)
+lysp_include_free(struct lysf_ctx *ctx, struct lysp_include *include)
 {
     lysp_include_free_(ctx, include, 1);
 }
 
+/**
+ * @brief Free the parsed revision structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] rev Parsed schema revision structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_revision_free(struct ly_ctx *ctx, struct lysp_revision *rev)
+lysp_revision_free(struct lysf_ctx *ctx, struct lysp_revision *rev)
 {
-    lydict_remove(ctx, rev->dsc);
-    lydict_remove(ctx, rev->ref);
+    lydict_remove(ctx->ctx, rev->dsc);
+    lydict_remove(ctx->ctx, rev->ref);
     FREE_ARRAY(ctx, rev->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed ext structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] ext Parsed schema ext structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_ext_free(struct ly_ctx *ctx, struct lysp_ext *ext)
+lysp_ext_free(struct lysf_ctx *ctx, struct lysp_ext *ext)
 {
-    lydict_remove(ctx, ext->name);
-    lydict_remove(ctx, ext->argname);
-    lydict_remove(ctx, ext->dsc);
-    lydict_remove(ctx, ext->ref);
+    lydict_remove(ctx->ctx, ext->name);
+    lydict_remove(ctx->ctx, ext->argname);
+    lydict_remove(ctx->ctx, ext->dsc);
+    lydict_remove(ctx->ctx, ext->ref);
     FREE_ARRAY(ctx, ext->exts, lysp_ext_instance_free);
     if (ext->compiled) {
         lysc_extension_free(ctx, &ext->compiled);
     }
 }
 
+/**
+ * @brief Free the parsed feature structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] feat Parsed schema feature structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_feature_free(struct ly_ctx *ctx, struct lysp_feature *feat)
+lysp_feature_free(struct lysf_ctx *ctx, struct lysp_feature *feat)
 {
-    lydict_remove(ctx, feat->name);
-    FREE_ARRAY(ctx, feat->iffeatures, lysp_qname_free);
+    lydict_remove(ctx->ctx, feat->name);
+    FREE_ARRAY(ctx->ctx, feat->iffeatures, lysp_qname_free);
     FREE_ARRAY(ctx, feat->iffeatures_c, lysc_iffeature_free);
     LY_ARRAY_FREE(feat->depfeatures);
-    lydict_remove(ctx, feat->dsc);
-    lydict_remove(ctx, feat->ref);
+    lydict_remove(ctx->ctx, feat->dsc);
+    lydict_remove(ctx->ctx, feat->ref);
     FREE_ARRAY(ctx, feat->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed identity structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] ident Parsed schema identity structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_ident_free(struct ly_ctx *ctx, struct lysp_ident *ident)
+lysp_ident_free(struct lysf_ctx *ctx, struct lysp_ident *ident)
 {
-    lydict_remove(ctx, ident->name);
-    FREE_ARRAY(ctx, ident->iffeatures, lysp_qname_free);
-    FREE_STRINGS(ctx, ident->bases);
-    lydict_remove(ctx, ident->dsc);
-    lydict_remove(ctx, ident->ref);
+    lydict_remove(ctx->ctx, ident->name);
+    FREE_ARRAY(ctx->ctx, ident->iffeatures, lysp_qname_free);
+    FREE_STRINGS(ctx->ctx, ident->bases);
+    lydict_remove(ctx->ctx, ident->dsc);
+    lydict_remove(ctx->ctx, ident->ref);
     FREE_ARRAY(ctx, ident->exts, lysp_ext_instance_free);
 }
 
 void
-lysp_restr_free(struct ly_ctx *ctx, struct lysp_restr *restr)
+lysp_restr_free(struct lysf_ctx *ctx, struct lysp_restr *restr)
 {
-    lydict_remove(ctx, restr->arg.str);
-    lydict_remove(ctx, restr->emsg);
-    lydict_remove(ctx, restr->eapptag);
-    lydict_remove(ctx, restr->dsc);
-    lydict_remove(ctx, restr->ref);
+    lydict_remove(ctx->ctx, restr->arg.str);
+    lydict_remove(ctx->ctx, restr->emsg);
+    lydict_remove(ctx->ctx, restr->eapptag);
+    lydict_remove(ctx->ctx, restr->dsc);
+    lydict_remove(ctx->ctx, restr->ref);
     FREE_ARRAY(ctx, restr->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed type enum item.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] item Parsed schema type enum item to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_type_enum_free(struct ly_ctx *ctx, struct lysp_type_enum *item)
+lysp_type_enum_free(struct lysf_ctx *ctx, struct lysp_type_enum *item)
 {
-    lydict_remove(ctx, item->name);
-    lydict_remove(ctx, item->dsc);
-    lydict_remove(ctx, item->ref);
-    FREE_ARRAY(ctx, item->iffeatures, lysp_qname_free);
+    lydict_remove(ctx->ctx, item->name);
+    lydict_remove(ctx->ctx, item->dsc);
+    lydict_remove(ctx->ctx, item->ref);
+    FREE_ARRAY(ctx->ctx, item->iffeatures, lysp_qname_free);
     FREE_ARRAY(ctx, item->exts, lysp_ext_instance_free);
 }
 
 void
-lysp_type_free(struct ly_ctx *ctx, struct lysp_type *type)
+lysp_type_free(struct lysf_ctx *ctx, struct lysp_type *type)
 {
-    lydict_remove(ctx, type->name);
+    lydict_remove(ctx->ctx, type->name);
     FREE_MEMBER(ctx, type->range, lysp_restr_free);
     FREE_MEMBER(ctx, type->length, lysp_restr_free);
     FREE_ARRAY(ctx, type->patterns, lysp_restr_free);
     FREE_ARRAY(ctx, type->enums, lysp_type_enum_free);
     FREE_ARRAY(ctx, type->bits, lysp_type_enum_free);
-    lyxp_expr_free(ctx, type->path);
-    FREE_STRINGS(ctx, type->bases);
+    lyxp_expr_free(ctx->ctx, type->path);
+    FREE_STRINGS(ctx->ctx, type->bases);
     FREE_ARRAY(ctx, type->types, lysp_type_free);
     FREE_ARRAY(ctx, type->exts, lysp_ext_instance_free);
     if (type->compiled) {
@@ -197,22 +262,34 @@
     }
 }
 
+/**
+ * @brief Free the parsed typedef structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] tpdf Parsed schema typedef structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_tpdf_free(struct ly_ctx *ctx, struct lysp_tpdf *tpdf)
+lysp_tpdf_free(struct lysf_ctx *ctx, struct lysp_tpdf *tpdf)
 {
-    lydict_remove(ctx, tpdf->name);
-    lydict_remove(ctx, tpdf->units);
-    lydict_remove(ctx, tpdf->dflt.str);
-    lydict_remove(ctx, tpdf->dsc);
-    lydict_remove(ctx, tpdf->ref);
+    lydict_remove(ctx->ctx, tpdf->name);
+    lydict_remove(ctx->ctx, tpdf->units);
+    lydict_remove(ctx->ctx, tpdf->dflt.str);
+    lydict_remove(ctx->ctx, tpdf->dsc);
+    lydict_remove(ctx->ctx, tpdf->ref);
     FREE_ARRAY(ctx, tpdf->exts, lysp_ext_instance_free);
 
     lysp_type_free(ctx, &tpdf->type);
 
 }
 
+/**
+ * @brief Free the parsed grouping structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] grp Parsed schema grouping structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_grp_free(struct ly_ctx *ctx, struct lysp_node_grp *grp)
+lysp_grp_free(struct lysf_ctx *ctx, struct lysp_node_grp *grp)
 {
     struct lysp_node *node, *next;
 
@@ -232,40 +309,38 @@
 }
 
 void
-lysp_when_free(struct ly_ctx *ctx, struct lysp_when *when)
+lysp_when_free(struct lysf_ctx *ctx, struct lysp_when *when)
 {
-    lydict_remove(ctx, when->cond);
-    lydict_remove(ctx, when->dsc);
-    lydict_remove(ctx, when->ref);
+    lydict_remove(ctx->ctx, when->cond);
+    lydict_remove(ctx->ctx, when->dsc);
+    lydict_remove(ctx->ctx, when->ref);
     FREE_ARRAY(ctx, when->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed augment structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] aug Parsed schema augment structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_augment_free(struct ly_ctx *ctx, struct lysp_node_augment *augment)
+lysp_augment_free(struct lysf_ctx *ctx, struct lysp_node_augment *aug)
 {
     struct lysp_node *node, *next;
 
-    LY_LIST_FOR_SAFE(augment->child, next, node) {
+    LY_LIST_FOR_SAFE(aug->child, next, node) {
         lysp_node_free(ctx, node);
     }
-    LY_LIST_FOR_SAFE((struct lysp_node *)augment->actions, next, node) {
+    LY_LIST_FOR_SAFE((struct lysp_node *)aug->actions, next, node) {
         lysp_node_free(ctx, node);
     }
-    LY_LIST_FOR_SAFE((struct lysp_node *)augment->notifs, next, node) {
+    LY_LIST_FOR_SAFE((struct lysp_node *)aug->notifs, next, node) {
         lysp_node_free(ctx, node);
     }
 }
 
 void
-lysp_qname_free(struct ly_ctx *ctx, struct lysp_qname *qname)
-{
-    if (qname) {
-        lydict_remove(ctx, qname->str);
-    }
-}
-
-void
-lysp_deviate_free(struct ly_ctx *ctx, struct lysp_deviate *d)
+lysp_deviate_free(struct lysf_ctx *ctx, struct lysp_deviate *d)
 {
     struct lysp_deviate_add *add = (struct lysp_deviate_add *)d;
     struct lysp_deviate_rpl *rpl = (struct lysp_deviate_rpl *)d;
@@ -281,30 +356,30 @@
         break;
     case LYS_DEV_ADD:
     case LYS_DEV_DELETE: /* compatible for dynamically allocated data */
-        lydict_remove(ctx, add->units);
+        lydict_remove(ctx->ctx, add->units);
         FREE_ARRAY(ctx, add->musts, lysp_restr_free);
-        FREE_ARRAY(ctx, add->uniques, lysp_qname_free);
-        FREE_ARRAY(ctx, add->dflts, lysp_qname_free);
+        FREE_ARRAY(ctx->ctx, add->uniques, lysp_qname_free);
+        FREE_ARRAY(ctx->ctx, add->dflts, lysp_qname_free);
         break;
     case LYS_DEV_REPLACE:
         FREE_MEMBER(ctx, rpl->type, lysp_type_free);
-        lydict_remove(ctx, rpl->units);
-        lysp_qname_free(ctx, &rpl->dflt);
+        lydict_remove(ctx->ctx, rpl->units);
+        lysp_qname_free(ctx->ctx, &rpl->dflt);
         break;
     default:
-        LOGINT(ctx);
+        LOGINT(ctx->ctx);
         break;
     }
 }
 
 void
-lysp_deviation_free(struct ly_ctx *ctx, struct lysp_deviation *dev)
+lysp_deviation_free(struct lysf_ctx *ctx, struct lysp_deviation *dev)
 {
     struct lysp_deviate *next, *iter;
 
-    lydict_remove(ctx, dev->nodeid);
-    lydict_remove(ctx, dev->dsc);
-    lydict_remove(ctx, dev->ref);
+    lydict_remove(ctx->ctx, dev->nodeid);
+    lydict_remove(ctx->ctx, dev->dsc);
+    lydict_remove(ctx->ctx, dev->ref);
     LY_LIST_FOR_SAFE(dev->deviates, next, iter) {
         lysp_deviate_free(ctx, iter);
         free(iter);
@@ -312,21 +387,27 @@
     FREE_ARRAY(ctx, dev->exts, lysp_ext_instance_free);
 }
 
+/**
+ * @brief Free the parsed refine structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] ref Parsed schema refine structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysp_refine_free(struct ly_ctx *ctx, struct lysp_refine *ref)
+lysp_refine_free(struct lysf_ctx *ctx, struct lysp_refine *ref)
 {
-    lydict_remove(ctx, ref->nodeid);
-    lydict_remove(ctx, ref->dsc);
-    lydict_remove(ctx, ref->ref);
-    FREE_ARRAY(ctx, ref->iffeatures, lysp_qname_free);
+    lydict_remove(ctx->ctx, ref->nodeid);
+    lydict_remove(ctx->ctx, ref->dsc);
+    lydict_remove(ctx->ctx, ref->ref);
+    FREE_ARRAY(ctx->ctx, ref->iffeatures, lysp_qname_free);
     FREE_ARRAY(ctx, ref->musts, lysp_restr_free);
-    lydict_remove(ctx, ref->presence);
-    FREE_ARRAY(ctx, ref->dflts, lysp_qname_free);
+    lydict_remove(ctx->ctx, ref->presence);
+    FREE_ARRAY(ctx->ctx, ref->dflts, lysp_qname_free);
     FREE_ARRAY(ctx, ref->exts, lysp_ext_instance_free);
 }
 
 void
-lysp_node_free(struct ly_ctx *ctx, struct lysp_node *node)
+lysp_node_free(struct lysf_ctx *ctx, struct lysp_node *node)
 {
     struct lysp_node *child, *next;
     struct lysp_node_container *cont;
@@ -342,10 +423,10 @@
     struct lysp_restr *musts = lysp_node_musts(node);
     struct lysp_when *when = lysp_node_when(node);
 
-    lydict_remove(ctx, node->name);
-    lydict_remove(ctx, node->dsc);
-    lydict_remove(ctx, node->ref);
-    FREE_ARRAY(ctx, node->iffeatures, lysp_qname_free);
+    lydict_remove(ctx->ctx, node->name);
+    lydict_remove(ctx->ctx, node->dsc);
+    lydict_remove(ctx->ctx, node->ref);
+    FREE_ARRAY(ctx->ctx, node->iffeatures, lysp_qname_free);
     FREE_ARRAY(ctx, node->exts, lysp_ext_instance_free);
 
     FREE_MEMBER(ctx, when, lysp_when_free);
@@ -355,7 +436,7 @@
     case LYS_CONTAINER:
         cont = (struct lysp_node_container *)node;
 
-        lydict_remove(ctx, cont->presence);
+        lydict_remove(ctx->ctx, cont->presence);
         FREE_ARRAY(ctx, cont->typedefs, lysp_tpdf_free);
         if (cont->groupings) {
             LY_LIST_FOR_SAFE(&cont->groupings->node, next, child) {
@@ -380,20 +461,20 @@
         leaf = (struct lysp_node_leaf *)node;
 
         lysp_type_free(ctx, &leaf->type);
-        lydict_remove(ctx, leaf->units);
-        lydict_remove(ctx, leaf->dflt.str);
+        lydict_remove(ctx->ctx, leaf->units);
+        lydict_remove(ctx->ctx, leaf->dflt.str);
         break;
     case LYS_LEAFLIST:
         llist = (struct lysp_node_leaflist *)node;
 
         lysp_type_free(ctx, &llist->type);
-        lydict_remove(ctx, llist->units);
-        FREE_ARRAY(ctx, llist->dflts, lysp_qname_free);
+        lydict_remove(ctx->ctx, llist->units);
+        FREE_ARRAY(ctx->ctx, llist->dflts, lysp_qname_free);
         break;
     case LYS_LIST:
         list = (struct lysp_node_list *)node;
 
-        lydict_remove(ctx, list->key);
+        lydict_remove(ctx->ctx, list->key);
         FREE_ARRAY(ctx, list->typedefs, lysp_tpdf_free);
         if (list->groupings) {
             LY_LIST_FOR_SAFE(&list->groupings->node, next, child) {
@@ -413,7 +494,7 @@
                 lysp_node_free(ctx, child);
             }
         }
-        FREE_ARRAY(ctx, list->uniques, lysp_qname_free);
+        FREE_ARRAY(ctx->ctx, list->uniques, lysp_qname_free);
         break;
     case LYS_CHOICE:
         choice = (struct lysp_node_choice *)node;
@@ -421,7 +502,7 @@
         LY_LIST_FOR_SAFE(choice->child, next, child) {
             lysp_node_free(ctx, child);
         }
-        lydict_remove(ctx, choice->dflt.str);
+        lydict_remove(ctx->ctx, choice->dflt.str);
         break;
     case LYS_CASE:
         cas = (struct lysp_node_case *)node;
@@ -496,22 +577,20 @@
         lysp_augment_free(ctx, ((struct lysp_node_augment *)node));
         break;
     default:
-        LOGINT(ctx);
+        LOGINT(ctx->ctx);
     }
 
     free(node);
 }
 
 void
-lysp_module_free(struct lysp_module *module)
+lysp_module_free(struct lysf_ctx *ctx, struct lysp_module *module)
 {
-    struct ly_ctx *ctx;
     struct lysp_node *node, *next;
 
     if (!module) {
         return;
     }
-    ctx = module->mod->ctx;
 
     FREE_ARRAY(ctx, module->imports, lysp_import_free);
     FREE_ARRAY(ctx, module->includes, module->is_submod ? lysp_include_free_submodule : lysp_include_free);
@@ -542,77 +621,102 @@
     if (module->is_submod) {
         struct lysp_submodule *submod = (struct lysp_submodule *)module;
 
-        lydict_remove(ctx, submod->name);
-        lydict_remove(ctx, submod->filepath);
-        lydict_remove(ctx, submod->prefix);
-        lydict_remove(ctx, submod->org);
-        lydict_remove(ctx, submod->contact);
-        lydict_remove(ctx, submod->dsc);
-        lydict_remove(ctx, submod->ref);
+        lydict_remove(ctx->ctx, submod->name);
+        lydict_remove(ctx->ctx, submod->filepath);
+        lydict_remove(ctx->ctx, submod->prefix);
+        lydict_remove(ctx->ctx, submod->org);
+        lydict_remove(ctx->ctx, submod->contact);
+        lydict_remove(ctx->ctx, submod->dsc);
+        lydict_remove(ctx->ctx, submod->ref);
     }
 
     free(module);
 }
 
-void
-lysc_extension_free(struct ly_ctx *ctx, struct lysc_ext **ext)
+/**
+ * @brief Free the compiled extension definition and NULL the provided pointer.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] ext Compiled extension definition to be freed.
+ */
+static void
+lysc_extension_free(struct lysf_ctx *ctx, struct lysc_ext **ext)
 {
-    if (--(*ext)->refcount) {
+    if (ly_set_contains(&ctx->ext_set, *ext, NULL)) {
+        /* already freed and only referenced again in this module */
         return;
     }
-    lydict_remove(ctx, (*ext)->name);
-    lydict_remove(ctx, (*ext)->argname);
+
+    /* remember this extension to be freed */
+    ly_set_add(&ctx->ext_set, *ext, 0, NULL);
+
+    /* recursive exts free */
     FREE_ARRAY(ctx, (*ext)->exts, lysc_ext_instance_free);
-    free(*ext);
+
     *ext = NULL;
 }
 
 void
-lysc_ext_instance_free(struct ly_ctx *ctx, struct lysc_ext_instance *ext)
+lysc_ext_instance_free(struct lysf_ctx *ctx, struct lysc_ext_instance *ext)
 {
     if (ext->def && ext->def->plugin && ext->def->plugin->free) {
-        ext->def->plugin->free(ctx, ext);
+        ext->def->plugin->free(ctx->ctx, ext);
     }
-    if (ext->def) {
-        lysc_extension_free(ctx, &ext->def);
-    }
-    lydict_remove(ctx, ext->argument);
+    lydict_remove(ctx->ctx, ext->argument);
     FREE_ARRAY(ctx, ext->exts, lysc_ext_instance_free);
 }
 
 void
-lysc_iffeature_free(struct ly_ctx *UNUSED(ctx), struct lysc_iffeature *iff)
+lysc_iffeature_free(struct lysf_ctx *UNUSED(ctx), struct lysc_iffeature *iff)
 {
     LY_ARRAY_FREE(iff->features);
     free(iff->expr);
 }
 
+/**
+ * @brief Free the compiled when structure (decrease refcount) and NULL the provided pointer.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] grp Parsed schema grouping structure to free. Note that the structure itself is not freed.
+ */
 static void
-lysc_when_free(struct ly_ctx *ctx, struct lysc_when **w)
+lysc_when_free(struct lysf_ctx *ctx, struct lysc_when **w)
 {
     if (--(*w)->refcount) {
         return;
     }
-    lyxp_expr_free(ctx, (*w)->cond);
+    lyxp_expr_free(ctx->ctx, (*w)->cond);
     ly_free_prefix_data(LY_VALUE_SCHEMA_RESOLVED, (*w)->prefixes);
-    lydict_remove(ctx, (*w)->dsc);
-    lydict_remove(ctx, (*w)->ref);
+    lydict_remove(ctx->ctx, (*w)->dsc);
+    lydict_remove(ctx->ctx, (*w)->ref);
     FREE_ARRAY(ctx, (*w)->exts, lysc_ext_instance_free);
     free(*w);
 }
 
+/**
+ * @brief Free the compiled must structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] must Compiled must structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_must_free(struct ly_ctx *ctx, struct lysc_must *must)
+lysc_must_free(struct lysf_ctx *ctx, struct lysc_must *must)
 {
-    lyxp_expr_free(ctx, must->cond);
+    lyxp_expr_free(ctx->ctx, must->cond);
     ly_free_prefix_data(LY_VALUE_SCHEMA_RESOLVED, must->prefixes);
-    lydict_remove(ctx, must->emsg);
-    lydict_remove(ctx, must->eapptag);
-    lydict_remove(ctx, must->dsc);
-    lydict_remove(ctx, must->ref);
+    lydict_remove(ctx->ctx, must->emsg);
+    lydict_remove(ctx->ctx, must->eapptag);
+    lydict_remove(ctx->ctx, must->dsc);
+    lydict_remove(ctx->ctx, must->ref);
     FREE_ARRAY(ctx, must->exts, lysc_ext_instance_free);
 }
 
+/**
+ * @brief Unlink the identity from all derived identity arrays.
+ *
+ * @param[in] ident Identity to unlink.
+ */
 static void
 lysc_ident_derived_unlink(const struct lysc_ident *ident)
 {
@@ -696,60 +800,81 @@
     }
 }
 
+/**
+ * @brief Free the compiled identity structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] ident Compiled identity structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_ident_free(struct ly_ctx *ctx, struct lysc_ident *ident)
+lysc_ident_free(struct lysf_ctx *ctx, struct lysc_ident *ident)
 {
-    lydict_remove(ctx, ident->name);
-    lydict_remove(ctx, ident->dsc);
-    lydict_remove(ctx, ident->ref);
+    lydict_remove(ctx->ctx, ident->name);
+    lydict_remove(ctx->ctx, ident->dsc);
+    lydict_remove(ctx->ctx, ident->ref);
     LY_ARRAY_FREE(ident->derived);
     FREE_ARRAY(ctx, ident->exts, lysc_ext_instance_free);
 }
 
+/**
+ * @brief Free the compiled range structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] range Compiled range structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_range_free(struct ly_ctx *ctx, struct lysc_range *range)
+lysc_range_free(struct lysf_ctx *ctx, struct lysc_range *range)
 {
     LY_ARRAY_FREE(range->parts);
-    lydict_remove(ctx, range->eapptag);
-    lydict_remove(ctx, range->emsg);
-    lydict_remove(ctx, range->dsc);
-    lydict_remove(ctx, range->ref);
+    lydict_remove(ctx->ctx, range->eapptag);
+    lydict_remove(ctx->ctx, range->emsg);
+    lydict_remove(ctx->ctx, range->dsc);
+    lydict_remove(ctx->ctx, range->ref);
     FREE_ARRAY(ctx, range->exts, lysc_ext_instance_free);
 }
 
 void
-lysc_pattern_free(struct ly_ctx *ctx, struct lysc_pattern **pattern)
+lysc_pattern_free(struct lysf_ctx *ctx, struct lysc_pattern **pattern)
 {
     if (--(*pattern)->refcount) {
         return;
     }
     pcre2_code_free((*pattern)->code);
-    lydict_remove(ctx, (*pattern)->expr);
-    lydict_remove(ctx, (*pattern)->eapptag);
-    lydict_remove(ctx, (*pattern)->emsg);
-    lydict_remove(ctx, (*pattern)->dsc);
-    lydict_remove(ctx, (*pattern)->ref);
+    lydict_remove(ctx->ctx, (*pattern)->expr);
+    lydict_remove(ctx->ctx, (*pattern)->eapptag);
+    lydict_remove(ctx->ctx, (*pattern)->emsg);
+    lydict_remove(ctx->ctx, (*pattern)->dsc);
+    lydict_remove(ctx->ctx, (*pattern)->ref);
     FREE_ARRAY(ctx, (*pattern)->exts, lysc_ext_instance_free);
     free(*pattern);
 }
 
 void
-lysc_enum_item_free(struct ly_ctx *ctx, struct lysc_type_bitenum_item *item)
+lysc_enum_item_free(struct lysf_ctx *ctx, struct lysc_type_bitenum_item *item)
 {
-    lydict_remove(ctx, item->name);
-    lydict_remove(ctx, item->dsc);
-    lydict_remove(ctx, item->ref);
+    lydict_remove(ctx->ctx, item->name);
+    lydict_remove(ctx->ctx, item->dsc);
+    lydict_remove(ctx->ctx, item->ref);
     FREE_ARRAY(ctx, item->exts, lysc_ext_instance_free);
 }
 
+/**
+ * @brief Free the compiled type structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] type Pointer to compiled type structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_type2_free(struct ly_ctx *ctx, struct lysc_type **type)
+lysc_type2_free(struct lysf_ctx *ctx, struct lysc_type **type)
 {
     lysc_type_free(ctx, *type);
 }
 
 void
-lysc_type_free(struct ly_ctx *ctx, struct lysc_type *type)
+lysc_type_free(struct lysf_ctx *ctx, struct lysc_type *type)
 {
     if (!type || (LY_ATOMIC_DEC_BARRIER(type->refcount) > 1)) {
         return;
@@ -789,7 +914,7 @@
         FREE_ARRAY(ctx, ((struct lysc_type_union *)type)->types, lysc_type2_free);
         break;
     case LY_TYPE_LEAFREF:
-        lyxp_expr_free(ctx, ((struct lysc_type_leafref *)type)->path);
+        lyxp_expr_free(ctx->ctx, ((struct lysc_type_leafref *)type)->path);
         ly_free_prefix_data(LY_VALUE_SCHEMA_RESOLVED, ((struct lysc_type_leafref *)type)->prefixes);
         lysc_type_free(ctx, ((struct lysc_type_leafref *)type)->realtype);
         break;
@@ -805,8 +930,15 @@
     free(type);
 }
 
+/**
+ * @brief Free the compiled input/output structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] inout Compiled inout structure to be freed.
+ * Since the structure is part of the RPC/action structure, it is not freed itself.
+ */
 static void
-lysc_node_action_inout_free(struct ly_ctx *ctx, struct lysc_node_action_inout *inout)
+lysc_node_action_inout_free(struct lysf_ctx *ctx, struct lysc_node_action_inout *inout)
 {
     struct lysc_node *child, *child_next;
 
@@ -816,8 +948,15 @@
     }
 }
 
+/**
+ * @brief Free the compiled RPC/action structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] action Compiled RPC/action structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_action_free(struct ly_ctx *ctx, struct lysc_node_action *action)
+lysc_node_action_free(struct lysf_ctx *ctx, struct lysc_node_action *action)
 {
     FREE_ARRAY(ctx, action->when, lysc_when_free);
     if (action->input.nodetype) {
@@ -828,8 +967,15 @@
     }
 }
 
+/**
+ * @brief Free the compiled notification structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] notif Compiled notification structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_notif_free(struct ly_ctx *ctx, struct lysc_node_notif *notif)
+lysc_node_notif_free(struct lysf_ctx *ctx, struct lysc_node_notif *notif)
 {
     struct lysc_node *child, *child_next;
 
@@ -841,7 +987,7 @@
 }
 
 void
-lysc_node_container_free(struct ly_ctx *ctx, struct lysc_node_container *node)
+lysc_node_container_free(struct lysf_ctx *ctx, struct lysc_node_container *node)
 {
     struct lysc_node *child, *child_next;
 
@@ -858,24 +1004,38 @@
     FREE_ARRAY(ctx, node->musts, lysc_must_free);
 }
 
+/**
+ * @brief Free the compiled leaf structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled leaf structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_leaf_free(struct ly_ctx *ctx, struct lysc_node_leaf *node)
+lysc_node_leaf_free(struct lysf_ctx *ctx, struct lysc_node_leaf *node)
 {
     FREE_ARRAY(ctx, node->when, lysc_when_free);
     FREE_ARRAY(ctx, node->musts, lysc_must_free);
     if (node->type) {
         lysc_type_free(ctx, node->type);
     }
-    lydict_remove(ctx, node->units);
+    lydict_remove(ctx->ctx, node->units);
     if (node->dflt) {
-        node->dflt->realtype->plugin->free(ctx, node->dflt);
+        node->dflt->realtype->plugin->free(ctx->ctx, node->dflt);
         lysc_type_free(ctx, (struct lysc_type *)node->dflt->realtype);
         free(node->dflt);
     }
 }
 
+/**
+ * @brief Free the compiled leaflist structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled leaflist structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_leaflist_free(struct ly_ctx *ctx, struct lysc_node_leaflist *node)
+lysc_node_leaflist_free(struct lysf_ctx *ctx, struct lysc_node_leaflist *node)
 {
     LY_ARRAY_COUNT_TYPE u;
 
@@ -884,17 +1044,24 @@
     if (node->type) {
         lysc_type_free(ctx, node->type);
     }
-    lydict_remove(ctx, node->units);
+    lydict_remove(ctx->ctx, node->units);
     LY_ARRAY_FOR(node->dflts, u) {
-        node->dflts[u]->realtype->plugin->free(ctx, node->dflts[u]);
+        node->dflts[u]->realtype->plugin->free(ctx->ctx, node->dflts[u]);
         lysc_type_free(ctx, (struct lysc_type *)node->dflts[u]->realtype);
         free(node->dflts[u]);
     }
     LY_ARRAY_FREE(node->dflts);
 }
 
+/**
+ * @brief Free the compiled list structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled list structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_list_free(struct ly_ctx *ctx, struct lysc_node_list *node)
+lysc_node_list_free(struct lysf_ctx *ctx, struct lysc_node_list *node)
 {
     LY_ARRAY_COUNT_TYPE u;
     struct lysc_node *child, *child_next;
@@ -918,8 +1085,15 @@
     }
 }
 
+/**
+ * @brief Free the compiled choice structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled choice structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_choice_free(struct ly_ctx *ctx, struct lysc_node_choice *node)
+lysc_node_choice_free(struct lysf_ctx *ctx, struct lysc_node_choice *node)
 {
     struct lysc_node *child, *child_next;
 
@@ -929,8 +1103,15 @@
     }
 }
 
+/**
+ * @brief Free the compiled case structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled case structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_case_free(struct ly_ctx *ctx, struct lysc_node_case *node)
+lysc_node_case_free(struct lysf_ctx *ctx, struct lysc_node_case *node)
 {
     struct lysc_node *child, *child_next;
 
@@ -940,22 +1121,36 @@
     }
 }
 
+/**
+ * @brief Free the compiled anyxml/anydata structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled anyxml/anydata structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_anydata_free(struct ly_ctx *ctx, struct lysc_node_anydata *node)
+lysc_node_anydata_free(struct lysf_ctx *ctx, struct lysc_node_anydata *node)
 {
     FREE_ARRAY(ctx, node->when, lysc_when_free);
     FREE_ARRAY(ctx, node->musts, lysc_must_free);
 }
 
+/**
+ * @brief Free the compiled node structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled node structure to be freed.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
 static void
-lysc_node_free_(struct ly_ctx *ctx, struct lysc_node *node)
+lysc_node_free_(struct lysf_ctx *ctx, struct lysc_node *node)
 {
     ly_bool inout = 0;
 
     /* common part */
-    lydict_remove(ctx, node->name);
-    lydict_remove(ctx, node->dsc);
-    lydict_remove(ctx, node->ref);
+    lydict_remove(ctx->ctx, node->name);
+    lydict_remove(ctx->ctx, node->dsc);
+    lydict_remove(ctx->ctx, node->ref);
 
     /* nodetype-specific part */
     switch (node->nodetype) {
@@ -994,7 +1189,7 @@
         lysc_node_notif_free(ctx, (struct lysc_node_notif *)node);
         break;
     default:
-        LOGINT(ctx);
+        LOGINT(ctx->ctx);
     }
 
     FREE_ARRAY(ctx, node->exts, lysc_ext_instance_free);
@@ -1005,7 +1200,7 @@
 }
 
 void
-lysc_node_free(struct ly_ctx *ctx, struct lysc_node *node, ly_bool unlink)
+lysc_node_free(struct lysf_ctx *ctx, struct lysc_node *node, ly_bool unlink)
 {
     struct lysc_node *next, *iter, **child_p;
 
@@ -1037,7 +1232,7 @@
                 } else {
                     iter = (struct lysc_node *)lysc_node_child(node->parent);
                 }
-                LY_CHECK_ERR_RET(!iter, LOGINT(ctx), );
+                LY_CHECK_ERR_RET(!iter, LOGINT(ctx->ctx), );
             } else if (node->nodetype == LYS_RPC) {
                 iter = (struct lysc_node *)node->module->compiled->rpcs;
             } else if (node->nodetype == LYS_NOTIF) {
@@ -1075,17 +1270,14 @@
 }
 
 void
-lysc_module_free(struct lysc_module *module)
+lysc_module_free(struct lysf_ctx *ctx, struct lysc_module *module)
 {
-    struct ly_ctx *ctx;
     struct lysc_node *node, *node_next;
 
     if (!module) {
         return;
     }
 
-    ctx = module->mod->ctx;
-
     LY_LIST_FOR_SAFE(module->data, node_next, node) {
         lysc_node_free_(ctx, node);
     }
@@ -1101,7 +1293,7 @@
 }
 
 void
-lys_module_free(struct lys_module *module, ly_bool remove_links)
+lys_module_free(struct lysf_ctx *ctx, struct lys_module *module, ly_bool remove_links)
 {
     LY_ARRAY_COUNT_TYPE u;
 
@@ -1118,29 +1310,46 @@
             lysc_ident_derived_unlink(&module->identities[u]);
         }
     }
-    FREE_ARRAY(module->ctx, module->identities, lysc_ident_free);
-    lysp_module_free(module->parsed);
+    FREE_ARRAY(ctx, module->identities, lysc_ident_free);
+    lysp_module_free(ctx, module->parsed);
 
     LY_ARRAY_FREE(module->augmented_by);
     LY_ARRAY_FREE(module->deviated_by);
 
-    lydict_remove(module->ctx, module->name);
-    lydict_remove(module->ctx, module->revision);
-    lydict_remove(module->ctx, module->ns);
-    lydict_remove(module->ctx, module->prefix);
-    lydict_remove(module->ctx, module->filepath);
-    lydict_remove(module->ctx, module->org);
-    lydict_remove(module->ctx, module->contact);
-    lydict_remove(module->ctx, module->dsc);
-    lydict_remove(module->ctx, module->ref);
+    lydict_remove(ctx->ctx, module->name);
+    lydict_remove(ctx->ctx, module->revision);
+    lydict_remove(ctx->ctx, module->ns);
+    lydict_remove(ctx->ctx, module->prefix);
+    lydict_remove(ctx->ctx, module->filepath);
+    lydict_remove(ctx->ctx, module->org);
+    lydict_remove(ctx->ctx, module->contact);
+    lydict_remove(ctx->ctx, module->dsc);
+    lydict_remove(ctx->ctx, module->ref);
 
     free(module);
 }
 
+void
+lysf_ctx_erase(struct lysf_ctx *ctx)
+{
+    struct lysc_ext *ext;
+    uint32_t i;
+
+    for (i = 0; i < ctx->ext_set.count; ++i) {
+        ext = ctx->ext_set.objs[i];
+
+        lydict_remove(ctx->ctx, ext->name);
+        lydict_remove(ctx->ctx, ext->argname);
+        free(ext);
+    }
+    ly_set_erase(&ctx->ext_set, NULL);
+}
+
 LIBYANG_API_DEF void
 lyplg_ext_instance_substatements_free(struct ly_ctx *ctx, struct lysc_ext_substmt *substmts)
 {
     LY_ARRAY_COUNT_TYPE u;
+    struct lysf_ctx fctx = {.ctx = ctx};
 
     LY_ARRAY_FOR(substmts, u) {
         if (!substmts[u].storage) {
@@ -1162,7 +1371,7 @@
             struct lysc_node *child, *child_next;
 
             LY_LIST_FOR_SAFE(*((struct lysc_node **)substmts[u].storage), child_next, child) {
-                lysc_node_free_(ctx, child);
+                lysc_node_free_(&fctx, child);
             }
             break;
         }
@@ -1206,11 +1415,11 @@
             }
             if (substmts[u].cardinality < LY_STMT_CARD_SOME) {
                 /* single item */
-                lysc_iffeature_free(ctx, iff);
+                lysc_iffeature_free(&fctx, iff);
                 free(iff);
             } else {
                 /* multiple items */
-                FREE_ARRAY(ctx, iff, lysc_iffeature_free);
+                FREE_ARRAY(&fctx, iff, lysc_iffeature_free);
             }
             break;
         }
@@ -1222,7 +1431,7 @@
                 if (!type) {
                     break;
                 }
-                lysc_type_free(ctx, type);
+                lysc_type_free(&fctx, type);
             } else {
                 /* multiple items */
                 struct lysc_type **types = *((struct lysc_type ***)substmts[u].storage);
@@ -1230,7 +1439,7 @@
                 if (!types) {
                     break;
                 }
-                FREE_ARRAY(ctx, types, lysc_type2_free);
+                FREE_ARRAY(&fctx, types, lysc_type2_free);
             }
             break;
 
diff --git a/src/tree_schema_free.h b/src/tree_schema_free.h
new file mode 100644
index 0000000..ba5167f
--- /dev/null
+++ b/src/tree_schema_free.h
@@ -0,0 +1,221 @@
+/**
+ * @file tree_schema_free.h
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @brief internal freeing functions for YANG schema trees.
+ *
+ * Copyright (c) 2015 - 2022 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#ifndef LY_TREE_SCHEMA_FREE_H_
+#define LY_TREE_SCHEMA_FREE_H_
+
+#include "set.h"
+#include "tree_schema.h"
+
+struct lys_yang_parser_ctx;
+struct lys_yin_parser_ctx;
+
+struct lysf_ctx {
+    struct ly_ctx *ctx;
+    struct lys_module *mod;
+    struct ly_set ext_set;
+};
+
+/**
+ * @brief Macro to free [sized array](@ref sizedarrays) of items using the provided free function. The ARRAY itself is also freed,
+ * but the memory is not sanitized.
+ */
+#define FREE_ARRAY(CTX, ARRAY, FUNC) {LY_ARRAY_COUNT_TYPE c__; LY_ARRAY_FOR(ARRAY, c__){(FUNC)(CTX, &(ARRAY)[c__]);}LY_ARRAY_FREE(ARRAY);}
+
+/**
+ * @brief Macro to free the specified MEMBER of a structure using the provided free function. The memory is not sanitized.
+ */
+#define FREE_MEMBER(CTX, MEMBER, FUNC) if (MEMBER) {(FUNC)(CTX, MEMBER);free(MEMBER);}
+
+/**
+ * @brief Macro to free [sized array](@ref sizedarrays) of strings stored in the context's dictionary. The ARRAY itself is also freed,
+ * but the memory is not sanitized.
+ */
+#define FREE_STRINGS(CTX, ARRAY) {LY_ARRAY_COUNT_TYPE c__; LY_ARRAY_FOR(ARRAY, c__){lydict_remove(CTX, ARRAY[c__]);}LY_ARRAY_FREE(ARRAY);}
+
+/**
+ * @brief Free a parsed qualified name.
+ *
+ * @param[in] ctx libyang context.
+ * @param[in] qname Qualified name to free.
+ */
+void lysp_qname_free(struct ly_ctx *ctx, struct lysp_qname *qname);
+
+/**
+ * @brief Free the parsed extension instance structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] ext Parsed extension instance structure to free. Note that the instance itself is not freed.
+ */
+void lysp_ext_instance_free(struct lysf_ctx *ctx, struct lysp_ext_instance *ext);
+
+/**
+ * @brief Free a parsed restriction.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] restr Restriction to free.
+ */
+void lysp_restr_free(struct lysf_ctx *ctx, struct lysp_restr *restr);
+
+/**
+ * @brief Free the parsed type structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] type Parsed schema type structure to free. Note that the type itself is not freed.
+ */
+void lysp_type_free(struct lysf_ctx *ctx, struct lysp_type *type);
+
+/**
+ * @brief Free the parsed when structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] when Parsed schema when structure to free. Note that the structure itself is not freed.
+ */
+void lysp_when_free(struct lysf_ctx *ctx, struct lysp_when *when);
+
+/**
+ * @brief Free the parsed deviate structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] d Parsed schema deviate structure to free. Note that the structure itself is not freed.
+ */
+void lysp_deviate_free(struct lysf_ctx *ctx, struct lysp_deviate *d);
+
+/**
+ * @brief Free the parsed deviation structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] dev Parsed schema deviation structure to free. Note that the structure itself is not freed.
+ */
+void lysp_deviation_free(struct lysf_ctx *ctx, struct lysp_deviation *dev);
+
+/**
+ * @brief Free a parsed node.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] node Node to free.
+ */
+void lysp_node_free(struct lysf_ctx *ctx, struct lysp_node *node);
+
+/**
+ * @brief Free the parsed YANG schema tree structure. Works for both modules and submodules.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] module Parsed YANG schema tree structure to free.
+ */
+void lysp_module_free(struct lysf_ctx *ctx, struct lysp_module *module);
+
+/**
+ * @brief Free the compiled extension instance structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] ext Compiled extension instance structure to be cleaned.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
+void lysc_ext_instance_free(struct lysf_ctx *ctx, struct lysc_ext_instance *ext);
+
+/**
+ * @brief Free the compiled if-feature structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] iff Compiled if-feature structure to be cleaned.
+ * Since the structure is typically part of the sized array, the structure itself is not freed.
+ */
+void lysc_iffeature_free(struct lysf_ctx *ctx, struct lysc_iffeature *iff);
+
+/**
+ * @brief Free a compiled pattern.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] pattern Pointer to the pattern to free.
+ */
+void lysc_pattern_free(struct lysf_ctx *ctx, struct lysc_pattern **pattern);
+
+/**
+ * @brief Free a bit/enum item.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] item Bit/enum item to free.
+ */
+void lysc_enum_item_free(struct lysf_ctx *ctx, struct lysc_type_bitenum_item *item);
+
+/**
+ * @brief Free the compiled type structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] type Compiled type structure to be freed. The structure has refcount, so it is freed only in case
+ * the value is decreased to 0.
+ */
+void lysc_type_free(struct lysf_ctx *ctx, struct lysc_type *type);
+
+/**
+ * @brief Free the compiled container node structure.
+ *
+ * Only the container-specific members are freed, for generic node free function,
+ * use ::lysc_node_free().
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] node Compiled container node structure to be freed.
+ */
+void lysc_node_container_free(struct lysf_ctx *ctx, struct lysc_node_container *node);
+
+/**
+ * @brief Free the compiled node structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in] node Compiled node structure to be freed.
+ * @param[in] unlink Whether to first unlink the node before freeing.
+ */
+void lysc_node_free(struct lysf_ctx *ctx, struct lysc_node *node, ly_bool unlink);
+
+/**
+ * @brief Free the compiled schema structure.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] module Compiled schema module structure to free.
+ */
+void lysc_module_free(struct lysf_ctx *ctx, struct lysc_module *module);
+
+/**
+ * @brief Free the schema structure. It just frees, it does not remove the schema from its context.
+ *
+ * @param[in] ctx Free context.
+ * @param[in,out] module Schema module structure to free.
+ * @param[in] remove_links Whether to remove links in other modules to structures in this module. Not needed if
+ * the whole context is being freed.
+ */
+void lys_module_free(struct lysf_ctx *ctx, struct lys_module *module, ly_bool remove_links);
+
+/**
+ * @brief Erase free context.
+ *
+ * @param[in] ctx Free context to erase.
+ */
+void lysf_ctx_erase(struct lysf_ctx *ctx);
+
+/**
+ * @brief Free lys parser context.
+ *
+ * @param[in] ctx Context to free.
+ */
+void yang_parser_ctx_free(struct lys_yang_parser_ctx *ctx);
+
+/**
+ * @brief Free yin parser context
+ *
+ * @param[in] ctx Context to free.
+ */
+void yin_parser_ctx_free(struct lys_yin_parser_ctx *ctx);
+
+#endif /* LY_TREE_SCHEMA_FREE_H_ */
diff --git a/src/tree_schema_internal.h b/src/tree_schema_internal.h
index 18a0b90..fcbdbe9 100644
--- a/src/tree_schema_internal.h
+++ b/src/tree_schema_internal.h
@@ -174,11 +174,6 @@
 };
 
 /**
- * @brief free lys parser context.
- */
-void yang_parser_ctx_free(struct lys_yang_parser_ctx *ctx);
-
-/**
  * @brief Internal context for yin schema parser.
  */
 struct lys_yin_parser_ctx {
@@ -195,13 +190,6 @@
 };
 
 /**
- * @brief free yin parser context
- *
- * @param[in] ctx Context to free.
- */
-void yin_parser_ctx_free(struct lys_yin_parser_ctx *ctx);
-
-/**
  * @brief Check that \p c is valid UTF8 code point for YANG string.
  *
  * @param[in] ctx parser context for logging.
@@ -342,24 +330,6 @@
 LY_ERR lysp_load_submodules(struct lys_parser_ctx *pctx, struct lysp_module *pmod, struct ly_set *new_mods);
 
 /**
- * @brief Free a parsed restriction.
- *
- * @param[in] ctx libyang context.
- * @param[in] restr Restriction to free.
- */
-void lysp_restr_free(struct ly_ctx *ctx, struct lysp_restr *restr);
-
-void lysp_when_free(struct ly_ctx *ctx, struct lysp_when *when);
-
-/**
- * @brief Free a parsed qualified name.
- *
- * @param[in] ctx libyang context.
- * @param[in] qname Qualified name to free.
- */
-void lysp_qname_free(struct ly_ctx *ctx, struct lysp_qname *qname);
-
-/**
  * @brief Get address of a node's actions list if any.
  * Decides the node's type and in case it has an actions list, returns its address.
  *
@@ -632,37 +602,6 @@
 uint8_t lysc_iff_getop(uint8_t *list, size_t pos);
 
 /**
- * @brief Macro to free [sized array](@ref sizedarrays) of items using the provided free function. The ARRAY itself is also freed,
- * but the memory is not sanitized.
- */
-#define FREE_ARRAY(CTX, ARRAY, FUNC) {LY_ARRAY_COUNT_TYPE c__; LY_ARRAY_FOR(ARRAY, c__){(FUNC)(CTX, &(ARRAY)[c__]);}LY_ARRAY_FREE(ARRAY);}
-
-/**
- * @brief Macro to free the specified MEMBER of a structure using the provided free function. The memory is not sanitized.
- */
-#define FREE_MEMBER(CTX, MEMBER, FUNC) if (MEMBER) {(FUNC)(CTX, MEMBER);free(MEMBER);}
-
-/**
- * @brief Macro to free [sized array](@ref sizedarrays) of strings stored in the context's dictionary. The ARRAY itself is also freed,
- * but the memory is not sanitized.
- */
-#define FREE_STRINGS(CTX, ARRAY) {LY_ARRAY_COUNT_TYPE c__; LY_ARRAY_FOR(ARRAY, c__){lydict_remove(CTX, ARRAY[c__]);}LY_ARRAY_FREE(ARRAY);}
-
-/**
- * @brief Free the printable YANG schema tree structure. Works for both modules and submodules.
- *
- * @param[in] module Printable YANG schema tree structure to free.
- */
-void lysp_module_free(struct lysp_module *module);
-
-/**
- * @brief Free the parsed type structure.
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in] type Parsed schema type structure to free. Note that the type itself is not freed.
- */
-void lysp_type_free(struct ly_ctx *ctx, struct lysp_type *type);
-
-/**
  * @brief Parse generic statement structure into a specific parsed-schema structure.
  *
  * @param[in] ctx The compilation context of the @p stmt being processed
@@ -673,104 +612,6 @@
  */
 LY_ERR lysp_stmt_parse(struct lysc_ctx *ctx, const struct lysp_stmt *stmt, void **result, struct lysp_ext_instance **exts);
 
-void lysp_deviate_free(struct ly_ctx *ctx, struct lysp_deviate *d);
-
-void lysp_deviation_free(struct ly_ctx *ctx, struct lysp_deviation *dev);
-
-/**
- * @brief Free a parsed node.
- *
- * @param[in] ctx libyang context.
- * @param[in] node Node to free.
- */
-void lysp_node_free(struct ly_ctx *ctx, struct lysp_node *node);
-
-/**
- * @brief Free a compiled pattern.
- *
- * @param[in] ctx libyang context.
- * @param[in] pattern Pointer to the pattern to free.
- */
-void lysc_pattern_free(struct ly_ctx *ctx, struct lysc_pattern **pattern);
-
-/**
- * @brief Free a bit/enum item.
- *
- * @param[in] ctx libyang context.
- * @param[in] item Bit/enum item to free.
- */
-void lysc_enum_item_free(struct ly_ctx *ctx, struct lysc_type_bitenum_item *item);
-
-/**
- * @brief Free the compiled type structure.
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in,out] type Compiled type structure to be freed. The structure has refcount, so it is freed only in case the value is decreased to 0.
- */
-void lysc_type_free(struct ly_ctx *ctx, struct lysc_type *type);
-
-/**
- * @brief Free the compiled if-feature structure.
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in,out] iff Compiled if-feature structure to be cleaned.
- * Since the structure is typically part of the sized array, the structure itself is not freed.
- */
-void lysc_iffeature_free(struct ly_ctx *ctx, struct lysc_iffeature *iff);
-
-/**
- * @brief Free the compiled extension definition and NULL the provided pointer.
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in,out] ext Compiled extension definition to be freed.
- */
-void lysc_extension_free(struct ly_ctx *ctx, struct lysc_ext **ext);
-
-/**
- * @brief Free the compiled extension instance structure.
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in,out] ext Compiled extension instance structure to be cleaned.
- * Since the structure is typically part of the sized array, the structure itself is not freed.
- */
-void lysc_ext_instance_free(struct ly_ctx *ctx, struct lysc_ext_instance *ext);
-
-/**
- * @brief Free the compiled node structure.
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in] node Compiled node structure to be freed.
- * @param[in] unlink Whether to first unlink the node before freeing.
- */
-void lysc_node_free(struct ly_ctx *ctx, struct lysc_node *node, ly_bool unlink);
-
-/**
- * @brief Free the compiled container node structure.
- *
- * Only the container-specific members are freed, for generic node free function,
- * use ::lysc_node_free().
- *
- * @param[in] ctx libyang context where the string data resides in a dictionary.
- * @param[in,out] node Compiled container node structure to be freed.
- */
-void lysc_node_container_free(struct ly_ctx *ctx, struct lysc_node_container *node);
-
-/**
- * @brief Free the compiled schema structure.
- *
- * @param[in,out] module Compiled schema module structure to free.
- */
-void lysc_module_free(struct lysc_module *module);
-
-/**
- * @brief Free the schema structure. It just frees, it does not remove the schema from its context.
- *
- * @param[in,out] module Schema module structure to free.
- * @param[in] remove_links Whether to remove links in other modules to structures in this module. Not needed if
- * the whole context is being freed.
- */
-void lys_module_free(struct lys_module *module, ly_bool remove_links);
-
 /**
  * @brief match yang keyword
  *