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