17bool is_shape(
const Def* s) {
18 if (
s->isa<
Nat>())
return true;
19 if (
auto arr =
s->isa<
Arr>())
return arr->body()->zonk()->isa<
Nat>();
20 if (
auto sig =
s->isa_imm<
Sigma>())
21 return std::ranges::all_of(sig->ops(), [](
const Def* op) { return op->isa<Nat>(); });
32#if (!defined(_MSC_VER) && defined(NDEBUG))
33bool World::Lock::guard_ =
false;
55 data_.lit_bool[0] =
lit_idx(2, 0_u64);
56 data_.lit_bool[1] =
lit_idx(2, 1_u64);
64 for (
auto def : move_.defs) def->~Def();
79 DLOG(
"register: 0x{x} -> {}", f, def);
81 if (
driver().is_loaded(plugin)) {
91 def->external_ =
true;
97 def->external_ =
false;
98 auto num = move_.sym2external.erase(def->
sym());
99 assert_unused(num == 1);
107 level = level->
zonk();
110 error(level->
loc(),
"argument `{}` to `Type` must be of type `Univ` but is of type `{}`", level, level->
type());
112 return unify<Type>(1, level)->as<
Type>();
119 error(op->
loc(),
"operand '{}' of a universe increment must be of type `Univ` but is of type `{}`", op,
123 return unify<UInc>(1, op, offset);
129 for (
auto op : ops_) {
131 if (
auto um = op->isa<
UMax>())
132 for (
auto umo : um->ops()) ops.emplace_back(umo->zonk());
134 ops.emplace_back(op);
138 for (
auto& op : ops) {
146 error(r->loc(),
"operand '{}' must be a Type of some level", r);
149 if (!r->type()->isa<
Univ>())
150 error(r->loc(),
"operand '{}' of a universe max must be of type 'Univ' but is of type '{}'", r, r->type());
155 lvl = std::max(lvl, *l);
164 std::ranges::sort(ops, [](
auto op1,
auto op2) {
return op1->gid() < op2->gid(); });
165 ops.erase(std::unique(ops.begin(), ops.end()), ops.end());
166 ldef = unify<UMax>(ops.size(), *
this, ops);
181 if (
auto var = mut->var_)
return var;
182 return mut->var_ = unify<Var>(1,
type, mut);
191 callee = callee->
zonk();
194 if (
auto pi = callee->
type()->isa<
Pi>()) {
196 arg = new_arg->
zonk();
197 if (
auto imm = callee->
isa_imm<
Lam>())
return imm->body();
200 if (
auto var =
lam->has_var()) {
201 if (
auto i = move_.substs.find({var, arg}); i != move_.substs.end()) {
203 auto [
filter, body] = i->second->defs<2>();
210 DLOG(
"partial evaluate: {} ({})",
lam, arg);
211 auto body = rw.rewrite(
lam->body());
212 auto num_bytes =
sizeof(Reduct) + 2 *
sizeof(
const Def*);
213 auto buf = move_.arena.substs.allocate(num_bytes,
alignof(
const Def*));
214 auto reduct =
new (buf) Reduct(2);
215 reduct->defs_[0] =
filter;
216 reduct->defs_[1] = body;
226 auto type =
pi->reduce(arg)->zonk();
227 callee = callee->
zonk();
230 curry = curry == 0 ? trip : curry;
233 if (
auto normalizer =
axm->normalizer(); Normalize && normalizer && curry == 0) {
234 if (
auto norm = normalizer(
type, callee, arg))
return norm;
242 .
error(arg->
loc(),
"cannot apply argument to callee")
243 .
note(callee->
loc(),
"callee: '{}'", callee)
244 .
note(arg->
loc(),
"argument: '{}'", arg)
245 .
note(callee->
loc(),
"vvv domain type vvv\n'{}'\n'{}'",
pi->dom(), arg->
type())
246 .
note(arg->
loc(),
"^^^ argument type ^^^");
250 .
error(callee->
loc(),
"called expression not of function type")
251 .
error(callee->
loc(),
"'{}' <--- callee type", callee->
type());
256 callee = callee->
zonk();
261 curry = curry == 0 ? trip : curry;
269 return unify<App>(2,
axm, curry, trip,
type, callee, arg);
274 if (n == 0)
return sigma();
275 if (n == 1)
return ops[0]->zonk();
279 return unify<Sigma>(zops.size(),
Sigma::infer(*
this, zops), ops);
284 if (n == 0)
return tuple();
285 if (n == 1)
return ops[0]->zonk();
292 error(t->loc(),
"cannot assign tuple '{}' of type '{}' to incompatible tuple type '{}'", t, t->type(),
sigma);
304 if (n == 0)
return tuple();
305 if (n == 1)
return ops[0];
312 if (
auto extract = ops[0]->isa<Extract>()) {
314 bool eta = tup->type() ==
type;
315 for (
size_t i = 0; i != n && eta; ++i) {
316 if (
auto extract = ops[i]->isa<Extract>()) {
318 if (eta &=
u64(i) == *index) {
319 eta &=
extract->tuple() == tup;
331 return unify<Tuple>(ops.size(),
type, ops);
336 std::ranges::transform(
sym, std::back_inserter(defs), [
this](
auto c) {
return lit_i8(c); });
342 index = index->
zonk();
344 if (index->isa<
Tuple>()) {
346 auto idx =
DefVec(n, [&](
size_t i) {
return index->
op(i); });
347 auto ops =
DefVec(n, [&](
size_t i) {
return d->proj(n,
Lit::as(idx[i])); });
349 }
else if (index->isa<
Pack>()) {
350 auto ops =
DefVec(index->
as_lit_arity(), [&](
size_t) { return extract(d, index->ops().back()); });
355 auto type = d->unfold_type()->zonk();
358 if (
auto l =
Lit::isa(size); l && *l == 1) {
359 if (
auto l =
Lit::isa(index); !l || *l != 0)
WLOG(
"unknown Idx of size 1: {}", index);
368 if (
auto pack = d->isa_imm<
Pack>())
return pack->body();
371 error(index->
loc(),
"index '{}' does not fit within arity '{}'", index,
type->arity());
390 return unify<Extract>(2, t, d, index);
393 return unify<Extract>(2,
sigma->op(*i), d, index);
399 elem_t =
arr->reduce(index);
403 if (index->isa<
Top>()) {
404 if (
auto hole = d->isa_mut<
Hole>(); hole && !hole->
is_set()) {
406 hole->set(
pack(size, elem_hole));
412 return unify<Extract>(2, elem_t, d, index);
417 index = index->
zonk();
420 auto type = d->unfold_type();
425 error(index->
loc(),
"index '{}' does not fit within arity '{}'", index,
type->arity());
428 auto elem_type =
type->proj(*lidx);
432 .
error(val->
loc(),
"value to be inserted not assignable to element")
433 .
note(val->
loc(),
"vvv value type vvv \n'{}'\n'{}'", val->
type(), elem_type)
434 .
note(val->
loc(),
"^^^ element type ^^^", elem_type);
439 if (
auto l =
Lit::isa(size); l && *l == 1)
440 return tuple(d, {val});
443 if (
auto t = d->isa<
Tuple>(); t && lidx)
return t->refine(*lidx, val);
447 if (
auto a =
pack->isa_lit_arity(); a && *a <
flags().scalarize_threshold) {
449 new_ops[*lidx] = val;
459 return unify<Insert>(3, d, index, val);
464 shape = shape->zonk();
467 if (!is_shape(shape->type()))
error(shape->loc(),
"expected shape but got '{}' of type '{}'", shape, shape->type());
470 if (*a == 0)
return sigma();
471 if (*a == 1)
return body;
478 if (
auto p = shape->isa<
Pack>()) {
479 if (
auto s =
Lit::isa(p->shape()))
return arr(*s,
arr(
pack(*s - 1, p->body()), body));
482 return unify<Arr>(2, body->
unfold_type(), shape, body);
486 shape = shape->zonk();
489 if (!is_shape(shape->unfold_type()))
490 error(shape->loc(),
"expected shape but got '{}' of type '{}'", shape, shape->unfold_type());
493 if (*a == 0)
return tuple();
494 if (*a == 1)
return body;
501 if (
auto p = shape->isa<
Pack>()) {
506 return unify<Pack>(1,
type, body);
510 if (shape.empty())
return body;
511 return arr(shape.rsubspan(1),
arr(shape.back(), body));
515 if (shape.empty())
return body;
516 return pack(shape.rsubspan(1),
pack(shape.back(), body));
523 if (size->isa<
Top>()) {
525 }
else if (
auto s =
Lit::isa(size)) {
526 if (*s != 0 && val >= *s)
error(
type->loc(),
"index '{}' does not fit within arity '{}'", size, val);
527 }
else if (val != 0) {
528 error(
type->loc(),
"cannot create literal '{}' of 'Idx {}' as size is unknown", val, size);
532 return unify<Lit>(0,
type, val);
545 return unify<TExt<Up>>(0,
type);
550 for (
size_t i = 0, e = ops_.size(); i != e; ++i) {
551 auto op = ops_[i]->zonk();
552 if (!op->isa<
TExt<!Up>>()) ops.emplace_back(op);
558 if (std::ranges::any_of(ops, [&](
const Def* op) ->
bool {
return op->isa<
TExt<Up>>(); }))
return ext<Up>(kind);
562 ops.resize(std::distance(ops.begin(), std::unique(ops.begin(), ops.end())));
564 if (ops.size() == 0)
return ext<!Up>(kind);
565 if (ops.size() == 1)
return ops[0];
568 return unify<TBound<Up>>(ops.size(), kind, ops);
576 auto types =
DefVec(ops.size(), [&](
size_t i) { return ops[i]->type(); });
577 return unify<Merge>(ops.size(),
meet(types), ops);
580 assert(ops.size() == 1);
591 value = value->
zonk();
593 if (
type->isa<
Join>())
return unify<Inj>(1,
type, value);
599 value = value->
zonk();
601 return unify<Split>(1,
type, value);
606 if (ops.size() == 1)
return ops.front();
608 auto scrutinee = ops.front();
609 auto arms = ops.span().subspan(1);
610 auto join = scrutinee->type()->isa<
Join>();
612 if (!
join)
error(scrutinee->loc(),
"scrutinee of a test expression must be of union type");
614 if (arms.size() !=
join->num_ops())
615 error(scrutinee->loc(),
"test expression has {} arms but union type has {} cases", arms.size(),
618 for (
auto arm : arms)
619 if (!arm->type()->isa<
Pi>())
620 error(arm->loc(),
"arm of test expression does not have a function type but is of type '{}'", arm->type());
622 std::ranges::sort(arms, [](
const Def* arm1,
const Def* arm2) {
627 for (
size_t i = 0, e = arms.size(); i != e; ++i) {
629 auto pi = arm->type()->as<
Pi>();
632 "domain type '{}' of arm in a test expression does not match case type '{}' in union type",
pi->dom(),
637 return unify<Match>(ops.size(),
type, ops);
641 inhabitant = inhabitant->
zonk();
646 auto name = symbol.str();
648 auto pos =
name.find(suffix);
649 if (pos != std::string::npos) {
650 auto num =
name.substr(pos + suffix.size());
655 num = std::to_string(std::stoi(num) + 1);
656 name =
name.substr(0, pos + suffix.size()) +
"_" + num;
666 auto mut =
var->mut();
667 auto offset = mut->reduction_offset();
668 auto size = mut->num_ops() - offset;
670 if (
auto i = move_.substs.find({var, arg}); i != move_.substs.end())
return i->second->defs();
672 auto buf = move_.arena.substs.allocate(
sizeof(Reduct) + size *
sizeof(
const Def*),
alignof(
const Def*));
673 auto reduct =
new (buf) Reduct(size);
675 for (
size_t i = 0; i != size; ++i) reduct->defs_[i] = rw.rewrite(mut->op(i + offset));
677 return reduct->defs();
684#ifdef MIM_ENABLE_CHECKS
689 auto i = std::ranges::find_if(move_.defs, [=](
auto def) { return def->gid() == gid; });
690 if (i == move_.defs.end())
return nullptr;
695 for (
auto mut :
externals()) assert(mut->is_closed() && mut->is_set());
696 for (
auto anx :
annexes()) 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?
bool is_set() const
Yields true if empty or the last op is set.
const Def * zonk() const
If Holes have been filled, reconstruct the program without them.
nat_t as_lit_arity() const
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 * op(size_t i) const noexcept
const Def * unfold_type() const
Yields the type of this Def and builds a new Type (UInc n) if necessary.
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
const T * isa_imm() const
bool is_closed() const
Has no free_vars()?
constexpr size_t num_ops() const noexcept
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 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)
static T as(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?
virtual const Def * rewrite(const Def *)
static const Def * infer(World &, Defs)
Extremum. Either Top (Up) or Bottom.
Data constructor for a Sigma.
static const Def * infer(World &, Defs)
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)
const Type * type(const Def *level)
void make_external(Def *)
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 * app(const Def *callee, const Def *arg)
const Def * arr(const Def *shape, const Def *body)
const Pi * pi(const Def *dom, const Def *codom, bool implicit=false)
World & verify()
Verifies that all externals() and annexes() are Def::is_closed(), if MIM_ENABLE_CHECKS.
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 * var(const Def *type, Def *mut)
const Def * extract(const Def *d, const Def *i)
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.
void make_internal(Def *)
const Lit * lit_univ(u64 level)
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 Def with Def::gid 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)
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.