aboutsummaryrefslogtreecommitdiff
path: root/src/reduce.c
blob: 60fa57a540fef380f590a44813e0f4ec3a7fab42 (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
// Copyright (c) 2023, Marvin Borner <dev@marvinborner.de>
// SPDX-License-Identifier: MIT

#include <stdio.h>

#include <term.h>
#include <map.h>
#include <reduce.h>
#include <log.h>
#include <assert.h>

static struct term *substitute(struct term *term, struct term *substitution,
			       size_t level)
{
	if (term->type == VAR) {
		if (term->u.var.index == level) {
			return substitution;
		} else {
			term_refer_head(term, substitution->depth);
			return term;
		}
	} else if (term->type == ABS) {
		hash_t previous = term->u.abs.term->hash;
		struct term *new =
			substitute(term->u.abs.term, substitution, level + 1);
		if (previous == new->hash)
			return term; // nothing changed
		struct term *rehashed = term_rehash_abs(term, new);
		/* term_deref_head(term->u.abs.term); */ // TODO: only for vars?
		return rehashed;
	} else if (term->type == APP) {
		hash_t previous_lhs = term->u.app.lhs->hash;
		hash_t previous_rhs = term->u.app.rhs->hash;
		struct term *lhs =
			substitute(term->u.app.lhs, substitution, level);
		struct term *rhs =
			substitute(term->u.app.rhs, substitution, level);
		if (previous_lhs == lhs->hash && previous_rhs == rhs->hash)
			return term; // nothing changed
		struct term *rehashed = term_rehash_app(term, lhs, rhs);
		return rehashed;
	}
	fatal("invalid type %d\n", term->type);
}

// reduction of application
// ([X] Y) -> X/Y
struct term *reduce(struct term *term)
{
	if (!term_is_beta_redex(term))
		fatal("can't reduce non-beta-redex %d\n", term->type);

	fprintf(stderr, "reducing ");
	term_print(term);
	fprintf(stderr, "\n");

	struct term *reduced = substitute(term->u.app.lhs, term->u.app.rhs, -1);
	fprintf(stderr, "reduced ");
	term_print(reduced);
	fprintf(stderr, "\n");
	return reduced;
}