aboutsummaryrefslogtreecommitdiffstats
path: root/libnormalform_free.c
blob: 3bce4dfa00e9966777f4edbb3894dc3d59239614 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


/**
 * Recursively deallocate a `LIBNORMALFORM_SENTENCE *`
 * according to `libnormalform_free`
 *
 * @param  this  The object to deallocate
 */
NONNULL_INPUT static void
free_sentence(LIBNORMALFORM_SENTENCE *this)
{
	LIBNORMALFORM_SENTENCE *head = NULL, *a, *b;

	if (--this->refcount)
		return;

	do {
		if (this->atom && !--this->atom->refcount)
			free(this->atom);

		if (IS_BRANCH(this)) {
			a = LEFT(this);
			b = RIGHT(this);
			if (b && !--b->refcount)
				PUSH(&head, b);
		push_a:
			if (a && !--a->refcount)
				PUSH(&head, a);
		} else if (this->type == TYPE_TRANS) {
			a = this->data.trans.input;
			goto push_a;
		}

		free(this);
	} while (POP(&head, &this));
}


/**
 * Recursively deallocate a `LIBNORMALFORM_SENTENCE *`
 * according to `libnormalform_free`, but do not
 * deallocate the pointer itself
 *
 * @param  this  The object to deallocate
 */
NONNULL_INPUT static void
destroy_term(struct libnormalform_term *this)
{
	switch (this->type) {
	case LIBNORMALFORM_DISJUNCTION:
	case LIBNORMALFORM_CONJUNCTION:
	case LIBNORMALFORM_EXCLUSIVE_DISJUNCTION:
		while (this->term.clause.nterms)
			destroy_term(&this->term.clause.terms[--this->term.clause.nterms]);
		free(this->term.clause.terms);
		free(this);
		break;

	case LIBNORMALFORM_TRANSFORMATION:
		free(this->term.transformation.sentence);
		free(this);
		return;

	case LIBNORMALFORM_FOR_ALL:
	case LIBNORMALFORM_NEGATED_FOR_ALL:
	case LIBNORMALFORM_FOR_ANY:
	case LIBNORMALFORM_NEGATED_FOR_ANY:
	case LIBNORMALFORM_FOR_ONE:
	case LIBNORMALFORM_NEGATED_FOR_ONE:
		destroy_term(this->term.qualification.antecedent);
		destroy_term(this->term.qualification.predicate);
		free(this->term.qualification.antecedent);
		free(this->term.qualification.predicate);
		/* fall through */

	case LIBNORMALFORM_VARIABLE:
	case LIBNORMALFORM_NEGATED_VARIABLE:
	case LIBNORMALFORM_FUNCTION:
	case LIBNORMALFORM_NEGATED_FUNCTION:
		free(this);
		break;

	default:
		abort();
	}
}


void
(libnormalform_free)(void *this)
{
	if (!this)
		return;

	if (*(enum libnormalform_term_type *)this >= SENTENCE_TYPE_OFFSET) {
		free_sentence(this);
	} else {
		destroy_term(this);
		free(this);
	}
}


#else


int
main(void)
{
	TEST_BEGIN;

	libnormalform_free(NULL);

	/* Tested in other tests */

	TEST_END;
}


#endif