aboutsummaryrefslogtreecommitdiff
path: root/src/term.c
blob: 3074bfc71ac2df0b4151bf0122354816e60975da (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
// Copyright (c) 2024, Marvin Borner <dev@marvinborner.de>
// SPDX-License-Identifier: MIT

#include <stdlib.h>
#include <stdio.h>

#include <term.h>
#include <log.h>
#include <print.h>

Term *term_new(TermType type)
{
	struct term *term = malloc(sizeof(*term));
	if (!term)
		fatal("out of memory!\n");
	term->type = type;
	return term;
}

void term_free(Term *term)
{
	switch (term->type) {
	case ABS:
		term_free(term->u.abs.body);
		free(term);
		break;
	case APP:
		term_free(term->u.app.lhs);
		term_free(term->u.app.rhs);
		free(term);
		break;
	case IDX:
		free(term);
		break;
	default:
		fatal("invalid type %d\n", term->type);
	}
}

void term_diff(Term *a, Term *b)
{
	if (a->type != b->type) {
		fprintf(stderr, "Term a: ");
		print_bruijn(a);
		fprintf(stderr, "\nTerm b: ");
		print_bruijn(b);
		fprintf(stderr, "\n");
		fatal("type mismatch %d %d\n", a->type, b->type);
	}

	switch (a->type) {
	case ABS:
		term_diff(a->u.abs.body, b->u.abs.body);
		break;
	case APP:
		term_diff(a->u.app.lhs, b->u.app.lhs);
		term_diff(a->u.app.rhs, b->u.app.rhs);
		break;
	case IDX:
		if (a->u.index != b->u.index)
			fatal("var mismatch %d=%d\n", a->u.index, b->u.index);
		break;
	default:
		fatal("invalid type %d\n", a->type);
	}
}