// Copyright (c) 2023, Marvin Borner // SPDX-License-Identifier: MIT #include #include #include #include static struct term *substitute(struct term *term, struct term *substitution, size_t level) { if (term->type == VAR && term->u.var.index == level) { return substitution; } else if (term->type == ABS) { struct term *new = substitute(term->u.abs.term, substitution, level + 1); return term_rehash_abs(term, new); } else if (term->type == APP) { struct term *lhs = substitute(term->u.app.lhs, substitution, level); struct term *rhs = substitute(term->u.app.rhs, substitution, level); return term_rehash_app(term, lhs, rhs); } fatal("invalid type %d\n", term->type); } static struct term *reduce_app(struct term *term) { if (term->u.app.lhs->type == ABS) { return substitute(term->u.app.lhs->u.abs.term, term->u.app.rhs, 0); } else { struct term *lhs = reduce(term->u.app.lhs); struct term *rhs = reduce(term->u.app.rhs); return term_rehash_app(term, lhs, rhs); } } static struct term *reduce_abs(struct term *term) { return reduce(term->u.abs.term); } struct term *reduce(struct term *term) { if (term->type == APP) { return reduce_app(term); } else if (term->type == ABS) { return reduce_abs(term); } else if (term->type == VAR) { return term; } fatal("invalid type %d\n", term->type); }