16bool is_shape(
const Def* s) {
17 if (
s->isa<
Nat>())
return true;
18 if (
auto arr =
s->isa<
Arr>())
return arr->body()->zonk()->isa<
Nat>();
19 if (
auto sig =
s->isa_imm<
Sigma>())
20 return std::ranges::all_of(sig->ops(), [](
const Def* op) { return op->isa<Nat>(); });
30 def->external_ =
true;
36 def->external_ =
false;
37 auto num = sym2mut_.erase(def->
sym());
38 assert_unused(num == 1);
45#if (!defined(_MSC_VER) && defined(NDEBUG))
46bool World::Lock::guard_ =
false;
60 data_.sigma = unify<Sigma>(
type(),
Defs{})->as<Sigma>();
61 data_.tuple = unify<Tuple>(
sigma(),
Defs{})->as<Tuple>();
67 data_.lit_idx_1_0 =
lit_idx(1, 0);
69 data_.lit_bool[0] =
lit_idx(2, 0_u64);
70 data_.lit_bool[1] =
lit_idx(2, 1_u64);
78 for (
auto def : move_.defs)
94 TLOG(
"register: 0x{x} -> {}", f, def);
96 if (
driver().is_loaded(plugin)) {
109 if (!level)
return nullptr;
110 level = level->
zonk();
113 error(level->
loc(),
"argument `{}` to `Type` must be of type `Univ` but is of type `{}`", level, level->
type());
115 return unify<Type>(level)->as<
Type>();
122 error(op->
loc(),
"operand '{}' of a universe increment must be of type `Univ` but is of type `{}`", op,
126 return unify<UInc>(op, offset);
130 if (
auto umax = def->isa<
UMax>())
131 for (
auto op : umax->ops())
134 ops.emplace_back(def);
140 for (
auto op : ops_) {
149 error(op->
loc(),
"operand '{}' must be a Type of some level", op);
157 for (
auto op : ops) {
159 error(op->
loc(),
"operand '{}' of a universe max must be of type 'Univ' but is of type '{}'", op,
163 lvl = std::max(lvl, *l);
165 res.emplace_back(op);
170 if (lvl > 0) res.emplace_back(l);
172 std::ranges::sort(res, [](
auto op1,
auto op2) {
return op1->gid() < op2->gid(); });
173 res.erase(std::unique(res.begin(), res.end()), res.end());
174 const Def*
umax = unify<UMax>(*
this, res);
181 if (
auto var = mut->var_)
return var;
183 if (
auto var_type = mut->
var_type()) {
189 return mut->var_ = unify<Var>(mut);
192template<
bool Normalize>
199template<
bool Normalize>
201 callee = callee->
zonk();
204 if (
auto pi = callee->
type()->isa<
Pi>()) {
206 arg = new_arg->
zonk();
207 if (
auto imm = callee->
isa_imm<
Lam>())
return imm->body();
210 if (
auto var =
lam->has_var()) {
211 if (
auto i = move_.substs.find({var, arg}); i != move_.substs.end()) {
213 auto [
filter, body] = i->second->defs<2>();
220 DLOG(
"partial evaluate: {} ({})",
lam, arg);
221 auto body = rw.rewrite(
lam->body());
222 auto num_bytes =
sizeof(Reduct) + 2 *
sizeof(
const Def*);
223 auto buf = move_.arena.substs.allocate(num_bytes,
alignof(
const Def*));
224 auto reduct =
new (buf) Reduct(2);
225 reduct->defs_[0] =
filter;
226 reduct->defs_[1] = body;
236 auto type =
pi->reduce(arg)->zonk();
237 callee = callee->
zonk();
240 curry = curry == 0 ? trip : curry;
243 if (
auto normalizer =
axm->normalizer(); Normalize && normalizer && curry == 0) {
244 if (
auto norm = normalizer(
type, callee, arg))
return norm;
252 .
error(arg->
loc(),
"cannot apply argument to callee")
253 .
note(callee->
loc(),
"callee: '{}'", callee)
254 .
note(arg->
loc(),
"argument: '{}'", arg)
255 .
note(callee->
loc(),
"vvv domain type vvv\n'{}'\n'{}'",
pi->dom(), arg->
type())
256 .
note(arg->
loc(),
"^^^ argument type ^^^");
260 .
error(callee->
loc(),
"called expression not of function type")
261 .
error(callee->
loc(),
"'{}' <--- callee type", callee->
type());
266 callee = callee->
zonk();
271 curry = curry == 0 ? trip : curry;
279 return unify<App>(
axm, curry, trip,
type, callee, arg);
284 if (n == 0)
return sigma();
285 if (n == 1)
return ops[0]->zonk();
294 if (n == 0)
return tuple();
295 if (n == 1)
return ops[0]->zonk();
302 error(t->loc(),
"cannot assign tuple '{}' of type '{}' to incompatible tuple type '{}'", t, t->type(),
sigma);
314 if (n == 0)
return tuple();
315 if (n == 1)
return ops[0];
322 if (
auto extract = ops[0]->isa<Extract>()) {
324 bool eta = tup->type() ==
type;
325 for (
size_t i = 0; i != n && eta; ++i) {
326 if (
auto extract = ops[i]->isa<Extract>()) {
328 if (eta &=
u64(i) == *index) {
329 eta &=
extract->tuple() == tup;
341 return unify<Tuple>(
type, ops);
346 std::ranges::transform(
sym, std::back_inserter(defs), [
this](
auto c) {
return lit_i8(c); });
351 if (!d || !index)
return nullptr;
353 index = index->
zonk();
356 for (
auto op :
tuple->ops())
359 }
else if (
auto pack = index->isa<
Pack>()) {
361 for (
nat_t i = 0, e = *a; i != e; ++i) {
370 auto type = d->unfold_type();
373 if (
auto l =
Lit::isa(size); l && *l == 1) {
374 if (
auto l =
Lit::isa(index); !l || *l != 0)
WLOG(
"unknown Idx of size 1: {}", index);
383 if (
auto pack = d->isa_imm<
Pack>())
return pack->body();
386 error(index->
loc(),
"index '{}' does not fit within arity '{}'", index,
type->arity());
406 return unify<Extract>(t, d, index);
409 return unify<Extract>(
sigma->op(*i), d, index);
415 elem_t =
arr->reduce(index);
419 if (index->isa<
Top>()) {
422 hole->set(
pack(size, elem_hole));
428 return unify<Extract>(elem_t, d, index);
433 index = index->
zonk();
436 auto type = d->unfold_type();
440 if (!size)
error(d->loc(),
"index '{}' must be of type 'Idx' but is of type '{}'", index, index->
type());
443 error(index->
loc(),
"index '{}' does not fit within arity '{}'", index,
type->arity());
446 auto elem_type =
type->proj(*lidx);
450 .
error(val->
loc(),
"value to be inserted not assignable to element")
451 .
note(val->
loc(),
"vvv value type vvv \n'{}'\n'{}'", val->
type(), elem_type)
452 .
note(val->
loc(),
"^^^ element type ^^^", elem_type);
457 if (
auto l =
Lit::isa(size); l && *l == 1)
458 return tuple(d, {val});
461 if (
auto t = d->isa<
Tuple>(); t && lidx)
return t->refine(*lidx, val);
467 new_ops[*lidx] = val;
477 return unify<Insert>(d, index, val);
481 arity = arity->
zonk();
485 if (!is_shape(arity_ty))
error(arity->
loc(),
"expected arity but got `{}` of type `{}`", arity, arity_ty);
488 if (*a == 0)
return unit(term);
489 if (*a == 1)
return body;
494 return seq(term,
tuple->ops().front(),
seq(term,
tuple->ops().subspan(1), body));
497 if (
auto p = arity->isa<
Pack>()) {
498 if (
auto s =
Lit::isa(p->arity()))
return seq(term, p->body(),
seq(term,
pack(*s - 1, p->body()), body));
503 return unify<Pack>(
type, body);
505 return unify<Arr>(body->
unfold_type(), arity, body);
510 if (shape.empty())
return body;
511 return seq(term, shape.rsubspan(1),
seq(term, shape.back(), body));
518 if (size->isa<
Top>()) {
520 }
else if (
auto s =
Lit::isa(size)) {
521 if (*s != 0 && val >= *s)
error(
type->loc(),
"index '{}' does not fit within arity '{}'", size, val);
522 }
else if (val != 0) {
523 error(
type->loc(),
"cannot create literal '{}' of 'Idx {}' as size is unknown", val, size);
527 return unify<Lit>(
type, val);
541 return unify<TExt<Up>>(
type);
547 for (
size_t i = 0, e = ops_.size(); i != e; ++i) {
548 auto op = ops_[i]->zonk();
549 if (!op->isa<
TExt<!Up>>()) ops.emplace_back(op);
555 if (std::ranges::any_of(ops, [&](
const Def* op) ->
bool {
return op->isa<
TExt<Up>>(); }))
return ext<Up>(kind);
559 ops.resize(std::distance(ops.begin(), std::unique(ops.begin(), ops.end())));
561 if (ops.size() == 0)
return ext<!Up>(kind);
562 if (ops.size() == 1)
return ops[0];
565 return unify<TBound<Up>>(kind, ops);
573 auto types =
DefVec(ops.size(), [&](
size_t i) { return ops[i]->type(); });
574 return unify<Merge>(
meet(types), ops);
577 assert(ops.size() == 1);
588 value = value->
zonk();
596 value = value->
zonk();
598 return unify<Split>(
type, value);
603 if (ops.size() == 1)
return ops.front();
605 auto scrutinee = ops.front();
606 auto arms = ops.span().subspan(1);
607 auto join = scrutinee->type()->isa<
Join>();
609 if (!
join)
error(scrutinee->loc(),
"scrutinee of a test expression must be of union type");
611 if (arms.size() !=
join->num_ops())
612 error(scrutinee->loc(),
"test expression has {} arms but union type has {} cases", arms.size(),
615 for (
auto arm : arms)
616 if (!arm->type()->isa<
Pi>())
617 error(arm->loc(),
"arm of test expression does not have a function type but is of type '{}'", arm->type());
619 std::ranges::sort(arms, [](
const Def* arm1,
const Def* arm2) {
624 for (
size_t i = 0, e = arms.size(); i != e; ++i) {
626 auto pi = arm->type()->as<
Pi>();
629 "domain type '{}' of arm in a test expression does not match case type '{}' in union type",
pi->dom(),
634 return unify<Match>(
type, ops);
638 inhabitant = inhabitant->
zonk();
643 auto name = symbol.str();
645 auto pos =
name.find(suffix);
646 if (pos != std::string::npos) {
647 auto num =
name.substr(pos + suffix.size());
652 num = std::to_string(std::stoi(num) + 1);
653 name =
name.substr(0, pos + suffix.size()) +
"_" + num;
663 auto mut =
var->mut();
664 auto offset = mut->reduction_offset();
665 auto size = mut->num_ops() - offset;
667 if (
auto i = move_.substs.find({var, arg}); i != move_.substs.end())
return i->second->defs();
669 auto buf = move_.arena.substs.allocate(
sizeof(Reduct) + size *
sizeof(
const Def*),
alignof(
const Def*));
670 auto reduct =
new (buf) Reduct(size);
672 for (
size_t i = 0; i != size; ++i)
673 reduct->defs_[i] = rw.rewrite(mut->op(i + offset));
675 return reduct->defs();
683 while (!queue.
empty()) {
684 auto mut = queue.
pop();
685 if (mut && mut->is_closed() && (!elide_empty || mut->is_set())) f(mut);
687 for (
auto op : mut->
deps())
697#ifdef MIM_ENABLE_CHECKS
703 auto i = std::ranges::find_if(move_.defs, [=](
auto def) { return def->gid() == gid; });
704 if (i == move_.defs.end())
return nullptr;
710 assert(mut->is_closed() && mut->is_set());
712 assert(anx->is_closed());
A (possibly paramterized) Array.
static constexpr u8 Trip_End
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
static const Def * is_uniform(Defs defs)
Yields defs.front(), if all defs are Check::alpha-equivalent (Mode::Test) and nullptr otherwise.
static bool alpha(const Def *d1, const Def *d2)
static const Def * assignable(const Def *type, const Def *value)
Can value be assigned to sth of type?
Defs deps() const noexcept
const Def * zonk() const
If Holes have been filled, reconstruct the program without them.
constexpr auto ops() const noexcept
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
const Def * unfold_type() const
Yields the type of this Def and builds a new Type (UInc n) if necessary.
Muts local_muts() const
Mutables reachable by following immutable deps(); mut->local_muts() is by definition the set { mut }...
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
bool is_external() const noexcept
const Def * var_type()
If this is a binder, compute the type of its Variable.
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
virtual const Def * arity() const
const T * isa_imm() const
bool is_closed() const
Has no free_vars()?
Some "global" variables needed all over the place.
Error & error(Loc loc, const char *s, Args &&... args)
Error & note(Loc loc, const char *s, Args &&... args)
This node is a hole in the IR that is inferred by its context later on.
static Hole * isa_unset(const Def *def)
static nat_t as_lit(const Def *def)
static const Def * isa(const Def *def)
Checks if def is a Idx s and returns s or nullptr otherwise.
Creates a new Tuple / Pack by inserting Insert::value at position Insert::index into Insert::tuple.
static std::optional< T > isa(const Def *def)
Facility to log what you are doing.
A (possibly paramterized) Tuple.
A dependent function type.
static Pi * isa_implicit(const Def *d)
Is d an Pi::is_implicit (mutable) Pi?
static const Def * infer(World &, Defs)
Extremum. Either Top (Up) or Bottom.
Data constructor for a Sigma.
static const Def * infer(World &, Defs)
const Def * rewrite(const Def *) final
A variable introduced by a binder (mutable).
const Lit * lit_idx(nat_t size, u64 val)
Constructs a Lit of type Idx of size size.
const Def * insert(const Def *d, const Def *i, const Def *val)
const Def * meet(Defs ops)
const Def * uinc(const Def *op, level_t offset=1)
const Lit * lit(const Def *type, u64 val)
void watchpoint(u32 gid)
Trigger breakpoint in your debugger when Def::setting a Def with this gid.
const Type * type(const Def *level)
const Driver & driver() const
const Def * filter(Lam::Filter filter)
const Def * sigma(Defs ops)
const Def * pack(const Def *arity, const Def *body)
const Def * unit(bool term)
const Def * app(const Def *callee, const Def *arg)
const Pi * pi(const Def *dom, const Def *codom, bool implicit=false)
const Def * seq(bool term, const Def *arity, const Def *body)
World & verify()
Verifies that all externals() and annexes() are Def::is_closed(), if MIM_ENABLE_CHECKS.
void for_each(bool elide_empty, std::function< void(Def *)>)
Hole * mut_hole(const Def *type)
const Lam * lam(const Pi *pi, Lam::Filter f, const Def *body)
const Def * tuple(Defs ops)
const Def * gid2def(u32 gid)
Lookup Def by gid.
Flags & flags()
Retrieve compile Flags.
const Def * implicit_app(const Def *callee, const Def *arg)
Places Holes as demanded by Pi::is_implicit() and then apps arg.
const Def * inj(const Def *type, const Def *value)
const Axm * axm(NormalizeFn n, u8 curry, u8 trip, const Def *type, plugin_t p, tag_t t, sub_t s)
const Def * extract(const Def *d, const Def *i)
const Def * arr(const Def *arity, const Def *body)
Sym sym(std::string_view)
const Def * bound(Defs ops)
const Def * join(Defs ops)
const Def * ext(const Def *type)
Sym append_suffix(Sym name, std::string suffix)
Appends a suffix or an increasing number if the suffix already exists.
const Lit * lit_idx_1_0()
const Lit * lit_univ(u64 level)
const Def * var(Def *mut)
const Tuple * tuple()
the unit value of type []
const Def * uniq(const Def *inhabitant)
const Def * raw_app(const Axm *axm, u8 curry, u8 trip, const Def *type, const Def *callee, const Def *arg)
const Def * merge(const Def *type, Defs ops)
const Sigma * sigma()
The unit type within Type 0.
const Lit * lit_nat(nat_t a)
const State & state() const
const Def * register_annex(flags_t f, const Def *)
Defs reduce(const Var *var, const Def *arg)
Yields the new body of [mut->var() -> arg]mut.
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
const Def * split(const Def *type, const Def *value)
#define DLOG(...)
Vaporizes to nothingness in Debug build.
Vector< const Def * > DefVec
auto assert_emplace(C &container, Args &&... args)
Invokes emplace on container, asserts that insertion actually happened, and returns the iterator.
TBound< true > Join
AKA union.
void error(Loc loc, const char *f, Args &&... args)
static void flatten_umax(DefVec &ops, const Def *def)
TBound< false > Meet
AKA intersection.
Compiler switches that must be saved and looked up in later phases of compilation.
static Sym demangle(Driver &, plugin_t plugin)
Reverts an Axm::mangled string to a Sym.