MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
world.cpp
Go to the documentation of this file.
1#include "mim/world.h"
2
3#include "mim/check.h"
4#include "mim/def.h"
5#include "mim/driver.h"
6#include "mim/rewrite.h"
7#include "mim/rule.h"
8#include "mim/tuple.h"
9
10#include "mim/util/util.h"
11
12namespace mim {
13
14namespace {
15
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>(); });
21
22 return false;
23}
24
25} // namespace
26
27/*
28 * constructor & destructor
29 */
30
31#if (!defined(_MSC_VER) && defined(NDEBUG))
32bool World::Lock::guard_ = false;
33#endif
34
36 : driver_(driver)
37 , zonker_(*this)
38 , state_(state) {
39 data_.univ = insert<Univ>(*this);
40 data_.lit_univ_0 = lit_univ(0);
41 data_.lit_univ_1 = lit_univ(1);
42 data_.type_0 = type(lit_univ_0());
43 data_.type_1 = type(lit_univ_1());
44 data_.type_bot = insert<Bot>(type());
45 data_.type_top = insert<Top>(type());
46 data_.sigma = unify<Sigma>(type(), Defs{})->as<Sigma>();
47 data_.tuple = unify<Tuple>(sigma(), Defs{})->as<Tuple>();
48 data_.type_nat = insert<mim::Nat>(*this);
49 data_.type_idx = insert<mim::Idx>(pi(type_nat(), type()));
50 data_.top_nat = insert<Top>(type_nat());
51 data_.lit_nat_0 = lit_nat(0);
52 data_.lit_nat_1 = lit_nat(1);
53 data_.lit_idx_1_0 = lit_idx(1, 0);
54 data_.type_bool = type_idx(2);
55 data_.lit_bool[0] = lit_idx(2, 0_u64);
56 data_.lit_bool[1] = lit_idx(2, 1_u64);
57 data_.lit_nat_max = lit_nat(nat_t(-1));
58}
59
62
64 for (auto def : move_.defs)
65 def->~Def();
66}
67
68/*
69 * Driver
70 */
71
72Log& World::log() const { return driver().log(); }
73Flags& World::flags() { return driver().flags(); }
74
75Sym World::sym(const char* s) { return driver().sym(s); }
76Sym World::sym(std::string_view s) { return driver().sym(s); }
77Sym World::sym(const std::string& s) { return driver().sym(s); }
78
79const Def* World::register_annex(flags_t f, const Def* def) {
80 TLOG("register: 0x{x} -> {}", f, def);
81 auto plugin = Annex::demangle(driver(), f);
82 if (driver().is_loaded(plugin)) {
83 assert_emplace(move_.flags2annex, f, def);
84 return def;
85 }
86 return nullptr;
87}
88
90 assert(!def->is_external());
91 assert(def->is_closed());
92 def->external_ = true;
93 assert_emplace(move_.sym2external, def->sym(), def);
94}
95
97 assert(def->is_external());
98 def->external_ = false;
99 auto num = move_.sym2external.erase(def->sym());
100 assert_unused(num == 1);
101}
102
103/*
104 * factory methods
105 */
106
107const Type* World::type(const Def* level) {
108 if (!level) return nullptr;
109 level = level->zonk();
110
111 if (!level->type()->isa<Univ>())
112 error(level->loc(), "argument `{}` to `Type` must be of type `Univ` but is of type `{}`", level, level->type());
113
114 return unify<Type>(level)->as<Type>();
115}
116
117const Def* World::uinc(const Def* op, level_t offset) {
118 op = op->zonk();
119
120 if (!op->type()->isa<Univ>())
121 error(op->loc(), "operand '{}' of a universe increment must be of type `Univ` but is of type `{}`", op,
122 op->type());
123
124 if (auto l = Lit::isa(op)) return lit_univ(*l + 1);
125 return unify<UInc>(op, offset);
126}
127
128static void flatten_umax(DefVec& ops, const Def* def) {
129 if (auto umax = def->isa<UMax>())
130 for (auto op : umax->ops())
131 flatten_umax(ops, op);
132 else
133 ops.emplace_back(def);
134}
135
136template<int sort>
137const Def* World::umax(Defs ops_) {
138 DefVec ops;
139 for (auto op : ops_) {
140 op = op->zonk();
141
142 if constexpr (sort == UMax::Term) op = op->unfold_type();
143 if constexpr (sort >= UMax::Type) op = op->unfold_type();
144 if constexpr (sort >= UMax::Kind) {
145 if (auto type = op->isa<Type>())
146 op = type->level();
147 else
148 error(op->loc(), "operand '{}' must be a Type of some level", op); // TODO better error message
149 }
150
151 flatten_umax(ops, op);
152 }
153
154 level_t lvl = 0;
155 DefVec res;
156 for (auto op : ops) {
157 if (!op->type()->isa<Univ>())
158 error(op->loc(), "operand '{}' of a universe max must be of type 'Univ' but is of type '{}'", op,
159 op->type());
160
161 if (auto l = Lit::isa(op))
162 lvl = std::max(lvl, *l);
163 else
164 res.emplace_back(op);
165 }
166
167 const Def* l = lit_univ(lvl);
168 if (res.empty()) return sort == UMax::Univ ? l : type(l);
169 if (lvl > 0) res.emplace_back(l);
170
171 std::ranges::sort(res, [](auto op1, auto op2) { return op1->gid() < op2->gid(); });
172 res.erase(std::unique(res.begin(), res.end()), res.end());
173 const Def* umax = unify<UMax>(*this, res);
174 return sort == UMax::Univ ? umax : type(umax);
175}
176
177// TODO more thorough & consistent checks for singleton types
178
179const Def* World::var(Def* mut) {
180 if (auto var = mut->var_) return var;
181
182 if (auto var_type = mut->var_type()) { // could be nullptr, if frozen
183 if (auto s = Idx::isa(var_type)) {
184 if (auto l = Lit::isa(s); l && l == 1) return lit_idx_1_0();
185 }
186 }
187
188 return mut->var_ = unify<Var>(mut);
189}
190
191template<bool Normalize>
192const Def* World::implicit_app(const Def* callee, const Def* arg) {
193 while (auto pi = Pi::isa_implicit(callee->type()))
194 callee = app(callee, mut_hole(pi->dom()));
195 return app<Normalize>(callee, arg);
196}
197
198template<bool Normalize>
199const Def* World::app(const Def* callee, const Def* arg) {
200 callee = callee->zonk();
201 arg = arg->zonk();
202
203 if (auto pi = callee->type()->isa<Pi>()) {
204 if (auto new_arg = Checker::assignable(pi->dom(), arg)) {
205 arg = new_arg->zonk();
206 if (auto imm = callee->isa_imm<Lam>()) return imm->body();
207
208 if (auto lam = callee->isa_mut<Lam>(); lam && lam->is_set() && lam->filter() != lit_ff()) {
209 if (auto var = lam->has_var()) {
210 if (auto i = move_.substs.find({var, arg}); i != move_.substs.end()) {
211 // Is there a cached version?
212 auto [filter, body] = i->second->defs<2>();
213 if (filter == lit_tt()) return body;
214 } else {
215 // First check filter, If true, reduce body and cache reduct.
216 auto rw = VarRewriter(var, arg);
217 auto filter = rw.rewrite(lam->filter());
218 if (filter == lit_tt()) {
219 DLOG("partial evaluate: {} ({})", lam, arg);
220 auto body = rw.rewrite(lam->body());
221 auto num_bytes = sizeof(Reduct) + 2 * sizeof(const Def*);
222 auto buf = move_.arena.substs.allocate(num_bytes, alignof(const Def*));
223 auto reduct = new (buf) Reduct(2);
224 reduct->defs_[0] = filter;
225 reduct->defs_[1] = body;
226 assert_emplace(move_.substs, std::pair{var, arg}, reduct);
227 return body;
228 }
229 }
230 } else if (lam->filter() == lit_tt()) {
231 return lam->body();
232 }
233 }
234
235 auto type = pi->reduce(arg)->zonk();
236 callee = callee->zonk();
237 auto [axm, curry, trip] = Axm::get(callee);
238 if (axm) {
239 curry = curry == 0 ? trip : curry;
240 curry = curry == Axm::Trip_End ? curry : curry - 1;
241
242 if (auto normalizer = axm->normalizer(); Normalize && normalizer && curry == 0) {
243 if (auto norm = normalizer(type, callee, arg)) return norm;
244 }
245 }
246
247 return raw_app(axm, curry, trip, type, callee, arg);
248 }
249
250 throw Error()
251 .error(arg->loc(), "cannot apply argument to callee")
252 .note(callee->loc(), "callee: '{}'", callee)
253 .note(arg->loc(), "argument: '{}'", arg)
254 .note(callee->loc(), "vvv domain type vvv\n'{}'\n'{}'", pi->dom(), arg->type())
255 .note(arg->loc(), "^^^ argument type ^^^");
256 }
257
258 throw Error()
259 .error(callee->loc(), "called expression not of function type")
260 .error(callee->loc(), "'{}' <--- callee type", callee->type());
261}
262
263const Def* World::raw_app(const Def* type, const Def* callee, const Def* arg) {
264 type = type->zonk();
265 callee = callee->zonk();
266 arg = arg->zonk();
267
268 auto [axm, curry, trip] = Axm::get(callee);
269 if (axm) {
270 curry = curry == 0 ? trip : curry;
271 curry = curry == Axm::Trip_End ? curry : curry - 1;
272 }
273
274 return raw_app(axm, curry, trip, type, callee, arg);
275}
276
277const Def* World::raw_app(const Axm* axm, u8 curry, u8 trip, const Def* type, const Def* callee, const Def* arg) {
278 return unify<App>(axm, curry, trip, type, callee, arg);
279}
280
281const Def* World::sigma(Defs ops) {
282 auto n = ops.size();
283 if (n == 0) return sigma();
284 if (n == 1) return ops[0]->zonk();
285
286 auto zops = Def::zonk(ops);
287 if (auto uni = Checker::is_uniform(zops)) return arr(n, uni);
288 return unify<Sigma>(Sigma::infer(*this, zops), zops);
289}
290
291const Def* World::tuple(Defs ops) {
292 auto n = ops.size();
293 if (n == 0) return tuple();
294 if (n == 1) return ops[0]->zonk();
295
296 auto zops = Def::zonk(ops);
297 auto sigma = Tuple::infer(*this, zops);
298 auto t = tuple(sigma, zops);
299 auto new_t = Checker::assignable(sigma, t);
300 if (!new_t)
301 error(t->loc(), "cannot assign tuple '{}' of type '{}' to incompatible tuple type '{}'", t, t->type(), sigma);
302
303 return new_t;
304}
305
306const Def* World::tuple(const Def* type, Defs ops_) {
307 // TODO type-check type vs inferred type
308 type = type->zonk();
309 auto ops = Def::zonk(ops_);
310
311 auto n = ops.size();
312 if (!type->isa_mut<Sigma>()) {
313 if (n == 0) return tuple();
314 if (n == 1) return ops[0];
315 if (auto uni = Checker::is_uniform(ops)) return pack(n, uni);
316 }
317
318 if (n != 0) {
319 // eta rule for tuples:
320 // (extract(tup, 0), extract(tup, 1), extract(tup, 2)) -> tup
321 if (auto extract = ops[0]->isa<Extract>()) {
322 auto tup = extract->tuple();
323 bool eta = tup->type() == type;
324 for (size_t i = 0; i != n && eta; ++i) {
325 if (auto extract = ops[i]->isa<Extract>()) {
326 if (auto index = Lit::isa(extract->index())) {
327 if (eta &= u64(i) == *index) {
328 eta &= extract->tuple() == tup;
329 continue;
330 }
331 }
332 }
333 eta = false;
334 }
335
336 if (eta) return tup;
337 }
338 }
339
340 return unify<Tuple>(type, ops);
341}
342
343const Def* World::tuple(Sym sym) {
344 DefVec defs;
345 std::ranges::transform(sym, std::back_inserter(defs), [this](auto c) { return lit_i8(c); });
346 return tuple(defs);
347}
348
349const Def* World::extract(const Def* d, const Def* index) {
350 if (!d || !index) return nullptr; // can happen if frozen
351 d = d->zonk();
352 index = index->zonk();
353
354 if (auto tuple = index->isa<Tuple>()) {
355 for (auto op : tuple->ops())
356 d = extract(d, op);
357 return d;
358 } else if (auto pack = index->isa<Pack>()) {
359 if (auto a = Lit::isa(index->arity())) {
360 for (nat_t i = 0, e = *a; i != e; ++i) {
361 auto idx = pack->has_var() ? pack->reduce(lit_idx(*a, i)) : pack->body();
362 d = extract(d, idx);
363 }
364 return d;
365 }
366 }
367
368 auto size = Idx::isa(index->type());
369 auto type = d->unfold_type();
370
371 if (size) {
372 if (auto l = Lit::isa(size); l && *l == 1) {
373 if (auto l = Lit::isa(index); !l || *l != 0) WLOG("unknown Idx of size 1: {}", index);
374 if (auto sigma = type->isa_mut<Sigma>(); sigma && sigma->num_ops() == 1) {
375 // mut sigmas can be 1-tuples; TODO mutables Arr?
376 } else {
377 return d;
378 }
379 }
380 }
381
382 if (auto pack = d->isa_imm<Pack>()) return pack->body();
383
384 if (size && !Checker::alpha<Checker::Check>(type->arity(), size))
385 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
386
387 // extract(insert(x, index, val), index) -> val
388 if (auto insert = d->isa<Insert>()) {
389 if (index == insert->index()) return insert->value();
390 }
391
392 if (auto i = Lit::isa(index)) {
393 if (auto hole = d->isa_mut<Hole>()) d = hole->tuplefy(Idx::as_lit(index->type()));
394 if (auto tuple = d->isa<Tuple>()) return tuple->op(*i);
395
396 // extract(insert(x, j, val), i) -> extract(x, i) where i != j (guaranteed by rule above)
397 if (auto insert = d->isa<Insert>()) {
398 if (insert->index()->isa<Lit>()) return extract(insert->tuple(), index);
399 }
400
401 if (auto sigma = type->isa<Sigma>()) {
402 if (auto var = sigma->has_var()) {
403 if (is_frozen()) return nullptr; // if frozen, we don't risk rewriting
404 auto t = VarRewriter(var, d).rewrite(sigma->op(*i));
405 return unify<Extract>(t, d, index);
406 }
407
408 return unify<Extract>(sigma->op(*i), d, index);
409 }
410 }
411
412 const Def* elem_t;
413 if (auto arr = type->isa<Arr>())
414 elem_t = arr->reduce(index);
415 else
416 elem_t = join(type->as<Sigma>()->ops());
417
418 if (index->isa<Top>()) {
419 if (auto hole = Hole::isa_unset(d)) {
420 auto elem_hole = mut_hole(elem_t);
421 hole->set(pack(size, elem_hole));
422 return elem_hole;
423 }
424 }
425
426 assert(d);
427 return unify<Extract>(elem_t, d, index);
428}
429
430const Def* World::insert(const Def* d, const Def* index, const Def* val) {
431 d = d->zonk();
432 index = index->zonk();
433 val = val->zonk();
434
435 auto type = d->unfold_type();
436 auto size = Idx::isa(index->type());
437 auto lidx = Lit::isa(index);
438
439 if (!size) error(d->loc(), "index '{}' must be of type 'Idx' but is of type '{}'", index, index->type());
440
441 if (!Checker::alpha<Checker::Check>(type->arity(), size))
442 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
443
444 if (lidx) {
445 auto elem_type = type->proj(*lidx);
446 auto new_val = Checker::assignable(elem_type, val);
447 if (!new_val) {
448 throw Error()
449 .error(val->loc(), "value to be inserted not assignable to element")
450 .note(val->loc(), "vvv value type vvv \n'{}'\n'{}'", val->type(), elem_type)
451 .note(val->loc(), "^^^ element type ^^^", elem_type);
452 }
453 val = new_val;
454 }
455
456 if (auto l = Lit::isa(size); l && *l == 1)
457 return tuple(d, {val}); // d could be mut - that's why the tuple ctor is needed
458
459 // insert((a, b, c, d), 2, x) -> (a, b, x, d)
460 if (auto t = d->isa<Tuple>(); t && lidx) return t->refine(*lidx, val);
461
462 // insert(‹4; x›, 2, y) -> (x, x, y, x)
463 if (auto pack = d->isa<Pack>(); pack && lidx) {
464 if (auto a = Lit::isa(pack->arity()); a && *a < flags().scalarize_threshold) {
465 auto new_ops = DefVec(*a, pack->body());
466 new_ops[*lidx] = val;
467 return tuple(type, new_ops);
468 }
469 }
470
471 // insert(insert(x, index, y), index, val) -> insert(x, index, val)
472 if (auto insert = d->isa<Insert>()) {
473 if (insert->index() == index) d = insert->tuple();
474 }
475
476 return unify<Insert>(d, index, val);
477}
478
479const Def* World::seq(bool term, const Def* arity, const Def* body) {
480 arity = arity->zonk(); // TODO use zonk_mut all over the place and rmeove zonk from is_shape?
481 body = body->zonk();
482
483 auto arity_ty = arity->unfold_type();
484 if (!is_shape(arity_ty)) error(arity->loc(), "expected arity but got `{}` of type `{}`", arity, arity_ty);
485
486 if (auto a = Lit::isa(arity)) {
487 if (*a == 0) return unit(term);
488 if (*a == 1) return body;
489 }
490
491 // «(a, b, c); body» -> «a; «(b, c); body»»
492 if (auto tuple = arity->isa<Tuple>())
493 return seq(term, tuple->ops().front(), seq(term, tuple->ops().subspan(1), body));
494
495 // «‹n; x›; body» -> «x; «<n-1, x>; body»»
496 if (auto p = arity->isa<Pack>()) {
497 if (auto s = Lit::isa(p->arity())) return seq(term, p->body(), seq(term, pack(*s - 1, p->body()), body));
498 }
499
500 if (term) {
501 auto type = arr(arity, body->type());
502 return unify<Pack>(type, body);
503 } else {
504 return unify<Arr>(body->unfold_type(), arity, body);
505 }
506}
507
508const Def* World::seq(bool term, Defs shape, const Def* body) {
509 if (shape.empty()) return body;
510 return seq(term, shape.rsubspan(1), seq(term, shape.back(), body));
511}
512
513const Lit* World::lit(const Def* type, u64 val) {
514 type = type->zonk();
515
516 if (auto size = Idx::isa(type)) {
517 if (size->isa<Top>()) {
518 // unsafe but fine
519 } else if (auto s = Lit::isa(size)) {
520 if (*s != 0 && val >= *s) error(type->loc(), "index '{}' does not fit within arity '{}'", size, val);
521 } else if (val != 0) { // 0 of any size is allowed
522 error(type->loc(), "cannot create literal '{}' of 'Idx {}' as size is unknown", val, size);
523 }
524 }
525
526 return unify<Lit>(type, val);
527}
528
529/*
530 * set
531 */
532
533template<bool Up>
534const Def* World::ext(const Def* type) {
535 type = type->zonk();
536
537 if (auto arr = type->isa<Arr>()) return pack(arr->arity(), ext<Up>(arr->body()));
538 if (auto sigma = type->isa<Sigma>())
539 return tuple(sigma, DefVec(sigma->num_ops(), [&](size_t i) { return ext<Up>(sigma->op(i)); }));
540 return unify<TExt<Up>>(type);
541}
542
543template<bool Up>
544const Def* World::bound(Defs ops_) {
545 auto ops = DefVec();
546 for (size_t i = 0, e = ops_.size(); i != e; ++i) {
547 auto op = ops_[i]->zonk();
548 if (!op->isa<TExt<!Up>>()) ops.emplace_back(op); // ignore: ext<!Up>
549 }
550
551 auto kind = umax<UMax::Type>(ops);
552
553 // has ext<Up> value?
554 if (std::ranges::any_of(ops, [&](const Def* op) -> bool { return op->isa<TExt<Up>>(); })) return ext<Up>(kind);
555
556 // sort and remove duplicates
557 std::ranges::sort(ops, GIDLt<const Def*>());
558 ops.resize(std::distance(ops.begin(), std::unique(ops.begin(), ops.end())));
559
560 if (ops.size() == 0) return ext<!Up>(kind);
561 if (ops.size() == 1) return ops[0];
562
563 // TODO simplify mixed terms with joins and meets?
564 return unify<TBound<Up>>(kind, ops);
565}
566
567const Def* World::merge(const Def* type, Defs ops_) {
568 type = type->zonk();
569 auto ops = Def::zonk(ops_);
570
571 if (type->isa<Meet>()) {
572 auto types = DefVec(ops.size(), [&](size_t i) { return ops[i]->type(); });
573 return unify<Merge>(meet(types), ops);
574 }
575
576 assert(ops.size() == 1);
577 return ops[0];
578}
579
580const Def* World::merge(Defs ops_) {
581 auto ops = Def::zonk(ops_);
582 return merge(umax<UMax::Term>(ops), ops);
583}
584
585const Def* World::inj(const Def* type, const Def* value) {
586 type = type->zonk();
587 value = value->zonk();
588
589 if (type->isa<Join>()) return unify<Inj>(type, value);
590 return value;
591}
592
593const Def* World::split(const Def* type, const Def* value) {
594 type = type->zonk();
595 value = value->zonk();
596
597 return unify<Split>(type, value);
598}
599
600const Def* World::match(Defs ops_) {
601 auto ops = Def::zonk(ops_);
602 if (ops.size() == 1) return ops.front();
603
604 auto scrutinee = ops.front();
605 auto arms = ops.span().subspan(1);
606 auto join = scrutinee->type()->isa<Join>();
607
608 if (!join) error(scrutinee->loc(), "scrutinee of a test expression must be of union type");
609
610 if (arms.size() != join->num_ops())
611 error(scrutinee->loc(), "test expression has {} arms but union type has {} cases", arms.size(),
612 join->num_ops());
613
614 for (auto arm : arms)
615 if (!arm->type()->isa<Pi>())
616 error(arm->loc(), "arm of test expression does not have a function type but is of type '{}'", arm->type());
617
618 std::ranges::sort(arms, [](const Def* arm1, const Def* arm2) {
619 return arm1->type()->as<Pi>()->dom()->gid() < arm2->type()->as<Pi>()->dom()->gid();
620 });
621
622 const Def* type = nullptr;
623 for (size_t i = 0, e = arms.size(); i != e; ++i) {
624 auto arm = arms[i];
625 auto pi = arm->type()->as<Pi>();
626 if (!Checker::alpha<Checker::Check>(pi->dom(), join->op(i)))
627 error(arm->loc(),
628 "domain type '{}' of arm in a test expression does not match case type '{}' in union type", pi->dom(),
629 join->op(i));
630 type = type ? this->join({type, pi->codom()}) : pi->codom();
631 }
632
633 return unify<Match>(type, ops);
634}
635
636const Def* World::uniq(const Def* inhabitant) {
637 inhabitant = inhabitant->zonk();
638 return unify<Uniq>(inhabitant->type()->unfold_type(), inhabitant);
639}
640
641Sym World::append_suffix(Sym symbol, std::string suffix) {
642 auto name = symbol.str();
643
644 auto pos = name.find(suffix);
645 if (pos != std::string::npos) {
646 auto num = name.substr(pos + suffix.size());
647 if (num.empty()) {
648 name += "_1";
649 } else {
650 num = num.substr(1);
651 num = std::to_string(std::stoi(num) + 1);
652 name = name.substr(0, pos + suffix.size()) + "_" + num;
653 }
654 } else {
655 name += suffix;
656 }
657
658 return sym(std::move(name));
659}
660
661Defs World::reduce(const Var* var, const Def* arg) {
662 auto mut = var->mut();
663 auto offset = mut->reduction_offset();
664 auto size = mut->num_ops() - offset;
665
666 if (auto i = move_.substs.find({var, arg}); i != move_.substs.end()) return i->second->defs();
667
668 auto buf = move_.arena.substs.allocate(sizeof(Reduct) + size * sizeof(const Def*), alignof(const Def*));
669 auto reduct = new (buf) Reduct(size);
670 auto rw = VarRewriter(var, arg);
671 for (size_t i = 0; i != size; ++i)
672 reduct->defs_[i] = rw.rewrite(mut->op(i + offset));
673 assert_emplace(move_.substs, std::pair{var, arg}, reduct);
674 return reduct->defs();
675}
676
677void World::for_each(bool elide_empty, std::function<void(Def*)> f) {
679 for (auto mut : externals())
680 queue.push(mut);
681
682 while (!queue.empty()) {
683 auto mut = queue.pop();
684 if (mut && mut->is_closed() && (!elide_empty || mut->is_set())) f(mut);
685
686 for (auto op : mut->deps())
687 for (auto mut : op->local_muts())
688 queue.push(mut);
689 }
690}
691
692/*
693 * debugging
694 */
695
696#ifdef MIM_ENABLE_CHECKS
697
698void World::breakpoint(u32 gid) { state_.breakpoints.emplace(gid); }
699void World::watchpoint(u32 gid) { state_.watchpoints.emplace(gid); }
700
701const Def* World::gid2def(u32 gid) {
702 auto i = std::ranges::find_if(move_.defs, [=](auto def) { return def->gid() == gid; });
703 if (i == move_.defs.end()) return nullptr;
704 return *i;
705}
706
708 for (auto mut : externals())
709 assert(mut->is_closed() && mut->is_set());
710 for (auto anx : annexes())
711 assert(anx->is_closed());
712 return *this;
713}
714
715#endif
716
717#ifndef DOXYGEN
718template const Def* World::umax<UMax::Term>(Defs);
719template const Def* World::umax<UMax::Type>(Defs);
720template const Def* World::umax<UMax::Kind>(Defs);
721template const Def* World::umax<UMax::Univ>(Defs);
722template const Def* World::ext<true>(const Def*);
723template const Def* World::ext<false>(const Def*);
724template const Def* World::bound<true>(Defs);
725template const Def* World::bound<false>(Defs);
726template const Def* World::app<true>(const Def*, const Def*);
727template const Def* World::app<false>(const Def*, const Def*);
728template const Def* World::implicit_app<true>(const Def*, const Def*);
729template const Def* World::implicit_app<false>(const Def*, const Def*);
730#endif
731
732} // namespace mim
A (possibly paramterized) Array.
Definition tuple.h:117
Definition axm.h:9
static constexpr u8 Trip_End
Definition axm.h:134
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
Definition axm.cpp:38
static const Def * is_uniform(Defs defs)
Yields defs.front(), if all defs are Check::alpha-equivalent (Mode::Test) and nullptr otherwise.
Definition check.cpp:115
static bool alpha(const Def *d1, const Def *d2)
Definition check.h:96
static const Def * assignable(const Def *type, const Def *value)
Can value be assigned to sth of type?
Definition check.h:103
Base class for all Defs.
Definition def.h:251
Defs deps() const noexcept
Definition def.cpp:467
const Def * zonk() const
If Holes have been filled, reconstruct the program without them.
Definition check.cpp:21
constexpr auto ops() const noexcept
Definition def.h:305
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
Definition def.h:485
const Def * unfold_type() const
Yields the type of this Def and builds a new Type (UInc n) if necessary.
Definition def.cpp:449
Muts local_muts() const
Mutables reachable by following immutable deps(); mut->local_muts() is by definition the set { mut }...
Definition def.cpp:329
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
Definition def.cpp:444
bool is_external() const noexcept
Definition def.h:467
Loc loc() const
Definition def.h:506
Sym sym() const
Definition def.h:507
const Def * var_type()
If this is a binder, compute the type of its Variable.
Definition def.cpp:312
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
Definition def.h:270
virtual const Def * arity() const
Definition def.cpp:550
const T * isa_imm() const
Definition def.h:479
bool is_closed() const
Has no free_vars()?
Definition def.cpp:415
Some "global" variables needed all over the place.
Definition driver.h:17
Log & log() const
Definition driver.h:25
Flags & flags()
Definition driver.h:23
Error & error(Loc loc, const char *s, Args &&... args)
Definition dbg.h:72
Error & note(Loc loc, const char *s, Args &&... args)
Definition dbg.h:74
This node is a hole in the IR that is inferred by its context later on.
Definition check.h:14
static Hole * isa_unset(const Def *def)
Definition check.h:53
static nat_t as_lit(const Def *def)
Definition def.h:880
static const Def * isa(const Def *def)
Checks if def is a Idx s and returns s or nullptr otherwise.
Definition def.cpp:608
Creates a new Tuple / Pack by inserting Insert::value at position Insert::index into Insert::tuple.
Definition tuple.h:233
A function.
Definition lam.h:111
static std::optional< T > isa(const Def *def)
Definition def.h:824
Facility to log what you are doing.
Definition log.h:17
A (possibly paramterized) Tuple.
Definition tuple.h:166
A dependent function type.
Definition lam.h:15
static Pi * isa_implicit(const Def *d)
Is d an Pi::is_implicit (mutable) Pi?
Definition lam.h:55
A dependent tuple type.
Definition tuple.h:20
static const Def * infer(World &, Defs)
Definition check.cpp:292
Extremum. Either Top (Up) or Bottom.
Definition lattice.h:152
Data constructor for a Sigma.
Definition tuple.h:68
static const Def * infer(World &, Defs)
Definition check.cpp:285
@ Type
Definition def.h:745
@ Univ
Definition def.h:745
@ Term
Definition def.h:745
@ Kind
Definition def.h:745
const Def * rewrite(const Def *) final
Definition rewrite.cpp:181
A variable introduced by a binder (mutable).
Definition def.h:700
const Lit * lit_idx(nat_t size, u64 val)
Constructs a Lit of type Idx of size size.
Definition world.h:439
const Def * insert(const Def *d, const Def *i, const Def *val)
Definition world.cpp:430
const Def * meet(Defs ops)
Definition world.h:481
const Def * uinc(const Def *op, level_t offset=1)
Definition world.cpp:117
const Lit * lit(const Def *type, u64 val)
Definition world.cpp:513
const Lit * lit_i8()
Definition world.h:433
void watchpoint(u32 gid)
Trigger breakpoint in your debugger when Def::setting a Def with this gid.
Definition world.cpp:699
const Type * type(const Def *level)
Definition world.cpp:107
void make_external(Def *)
Definition world.cpp:89
const Driver & driver() const
Definition world.h:87
const Lit * lit_tt()
Definition world.h:466
const Def * filter(Lam::Filter filter)
Definition world.h:289
World(Driver *)
Definition world.cpp:60
const Def * sigma(Defs ops)
Definition world.cpp:281
const Def * pack(const Def *arity, const Def *body)
Definition world.h:376
const Def * unit(bool term)
Definition world.h:359
const Def * app(const Def *callee, const Def *arg)
Definition world.cpp:199
const Def * match(Defs)
Definition world.cpp:600
const Pi * pi(const Def *dom, const Def *codom, bool implicit=false)
Definition world.h:265
const Def * seq(bool term, const Def *arity, const Def *body)
Definition world.cpp:479
World & verify()
Verifies that all externals() and annexes() are Def::is_closed(), if MIM_ENABLE_CHECKS.
Definition world.cpp:707
const Idx * type_idx()
Definition world.h:499
const Lit * lit_univ_0()
Definition world.h:424
Sym name() const
Definition world.h:91
void for_each(bool elide_empty, std::function< void(Def *)>)
Definition world.cpp:677
const Lit * lit_univ_1()
Definition world.h:425
const Nat * type_nat()
Definition world.h:498
Hole * mut_hole(const Def *type)
Definition world.h:232
const Lam * lam(const Pi *pi, Lam::Filter f, const Def *body)
Definition world.h:293
const Def * tuple(Defs ops)
Definition world.cpp:291
const Def * gid2def(u32 gid)
Lookup Def by gid.
Definition world.cpp:701
Flags & flags()
Retrieve compile Flags.
Definition world.cpp:73
const Def * implicit_app(const Def *callee, const Def *arg)
Places Holes as demanded by Pi::is_implicit() and then apps arg.
Definition world.cpp:192
const Def * inj(const Def *type, const Def *value)
Definition world.cpp:585
const Type * type()
Definition world.h:221
const Axm * axm(NormalizeFn n, u8 curry, u8 trip, const Def *type, plugin_t p, tag_t t, sub_t s)
Definition world.h:247
const Def * extract(const Def *d, const Def *i)
Definition world.cpp:349
bool is_frozen() const
Definition world.h:138
auto externals() const
Definition world.h:206
const Def * arr(const Def *arity, const Def *body)
Definition world.h:375
Sym sym(std::string_view)
Definition world.cpp:76
const Lit * lit_ff()
Definition world.h:465
const Def * bound(Defs ops)
Definition world.cpp:544
const Def * join(Defs ops)
Definition world.h:480
const Def * ext(const Def *type)
Definition world.cpp:534
Sym append_suffix(Sym name, std::string suffix)
Appends a suffix or an increasing number if the suffix already exists.
Definition world.cpp:641
void make_internal(Def *)
Definition world.cpp:96
const Lit * lit_idx_1_0()
Definition world.h:430
const Lit * lit_univ(u64 level)
Definition world.h:423
const Def * var(Def *mut)
Definition world.cpp:179
const Tuple * tuple()
the unit value of type []
Definition world.h:396
const Def * uniq(const Def *inhabitant)
Definition world.cpp:636
const Def * raw_app(const Axm *axm, u8 curry, u8 trip, const Def *type, const Def *callee, const Def *arg)
Definition world.cpp:277
const Def * umax(Defs)
Definition world.cpp:137
const Def * merge(const Def *type, Defs ops)
Definition world.cpp:567
const Sigma * sigma()
The unit type within Type 0.
Definition world.h:353
const Lit * lit_nat(nat_t a)
Definition world.h:426
const State & state() const
Definition world.h:86
const Def * register_annex(flags_t f, const Def *)
Definition world.cpp:79
Defs reduce(const Var *var, const Def *arg)
Yields the new body of [mut->var() -> arg]mut.
Definition world.cpp:661
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
Definition world.cpp:698
const Def * split(const Def *type, const Def *value)
Definition world.cpp:593
auto annexes() const
Definition world.h:178
Log & log() const
Definition world.cpp:72
bool empty() const
Definition util.h:168
bool push(T val)
Definition util.h:160
#define WLOG(...)
Definition log.h:90
#define TLOG(...)
Definition log.h:96
#define DLOG(...)
Vaporizes to nothingness in Debug build.
Definition log.h:95
Definition ast.h:14
View< const Def * > Defs
Definition def.h:76
u64 nat_t
Definition types.h:43
Vector< const Def * > DefVec
Definition def.h:77
auto assert_emplace(C &container, Args &&... args)
Invokes emplace on container, asserts that insertion actually happened, and returns the iterator.
Definition util.h:118
u64 flags_t
Definition types.h:45
TBound< true > Join
AKA union.
Definition lattice.h:174
void error(Loc loc, const char *f, Args &&... args)
Definition dbg.h:125
u64 level_t
Definition types.h:42
TExt< true > Top
Definition lattice.h:172
uint32_t u32
Definition types.h:34
static void flatten_umax(DefVec &ops, const Def *def)
Definition world.cpp:128
uint64_t u64
Definition types.h:34
uint8_t u8
Definition types.h:34
TBound< false > Meet
AKA intersection.
Definition lattice.h:173
Compiler switches that must be saved and looked up in later phases of compilation.
Definition flags.h:11
static Sym demangle(Driver &, plugin_t plugin)
Reverts an Axm::mangled string to a Sym.
Definition plugin.cpp:37