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 }
187 }
188
189 return mut->var_ = unify<Var>(mut);
190}
191
192template<bool Normalize>
193const Def* World::implicit_app(const Def* callee, const Def* arg) {
194 while (auto pi = Pi::isa_implicit(callee->type()))
195 callee = app(callee, mut_hole(pi->dom()));
196 return app<Normalize>(callee, arg);
197}
198
199template<bool Normalize>
200const Def* World::app(const Def* callee, const Def* arg) {
201 callee = callee->zonk();
202 arg = arg->zonk();
203
204 if (auto pi = callee->type()->isa<Pi>()) {
205 if (auto new_arg = Checker::assignable(pi->dom(), arg)) {
206 arg = new_arg->zonk();
207 if (auto imm = callee->isa_imm<Lam>()) return imm->body();
208
209 if (auto lam = callee->isa_mut<Lam>(); lam && lam->is_set() && lam->filter() != lit_ff()) {
210 if (auto var = lam->has_var()) {
211 if (auto i = move_.substs.find({var, arg}); i != move_.substs.end()) {
212 // Is there a cached version?
213 auto [filter, body] = i->second->defs<2>();
214 if (filter == lit_tt()) return body;
215 } else {
216 // First check filter, If true, reduce body and cache reduct.
217 auto rw = VarRewriter(var, arg);
218 auto filter = rw.rewrite(lam->filter());
219 if (filter == lit_tt()) {
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;
227 assert_emplace(move_.substs, std::pair{var, arg}, reduct);
228 return body;
229 }
230 }
231 } else if (lam->filter() == lit_tt()) {
232 return lam->body();
233 }
234 }
235
236 auto type = pi->reduce(arg)->zonk();
237 callee = callee->zonk();
238 auto [axm, curry, trip] = Axm::get(callee);
239 if (axm) {
240 curry = curry == 0 ? trip : curry;
241 curry = curry == Axm::Trip_End ? curry : curry - 1;
242
243 if (auto normalizer = axm->normalizer(); Normalize && normalizer && curry == 0) {
244 if (auto norm = normalizer(type, callee, arg)) return norm;
245 }
246 }
247
248 return raw_app(axm, curry, trip, type, callee, arg);
249 }
250
251 throw Error()
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 ^^^");
257 }
258
259 throw Error()
260 .error(callee->loc(), "called expression not of function type")
261 .error(callee->loc(), "'{}' <--- callee type", callee->type());
262}
263
264const Def* World::raw_app(const Def* type, const Def* callee, const Def* arg) {
265 type = type->zonk();
266 callee = callee->zonk();
267 arg = arg->zonk();
268
269 auto [axm, curry, trip] = Axm::get(callee);
270 if (axm) {
271 curry = curry == 0 ? trip : curry;
272 curry = curry == Axm::Trip_End ? curry : curry - 1;
273 }
274
275 return raw_app(axm, curry, trip, type, callee, arg);
276}
277
278const Def* World::raw_app(const Axm* axm, u8 curry, u8 trip, const Def* type, const Def* callee, const Def* arg) {
279 return unify<App>(axm, curry, trip, type, callee, arg);
280}
281
282const Def* World::sigma(Defs ops) {
283 auto n = ops.size();
284 if (n == 0) return sigma();
285 if (n == 1) return ops[0]->zonk();
286
287 auto zops = Def::zonk(ops);
288 if (auto uni = Checker::is_uniform(zops)) return arr(n, uni);
289 return unify<Sigma>(Sigma::infer(*this, zops), zops);
290}
291
292const Def* World::tuple(Defs ops) {
293 auto n = ops.size();
294 if (n == 0) return tuple();
295 if (n == 1) return ops[0]->zonk();
296
297 auto zops = Def::zonk(ops);
298 auto sigma = Tuple::infer(*this, zops);
299 auto t = tuple(sigma, zops);
300 auto new_t = Checker::assignable(sigma, t);
301 if (!new_t)
302 error(t->loc(), "cannot assign tuple '{}' of type '{}' to incompatible tuple type '{}'", t, t->type(), sigma);
303
304 return new_t;
305}
306
307const Def* World::tuple(const Def* type, Defs ops_) {
308 // TODO type-check type vs inferred type
309 type = type->zonk();
310 auto ops = Def::zonk(ops_);
311
312 auto n = ops.size();
313 if (!type->isa_mut<Sigma>()) {
314 if (n == 0) return tuple();
315 if (n == 1) return ops[0];
316 if (auto uni = Checker::is_uniform(ops)) return pack(n, uni);
317 }
318
319 if (n != 0) {
320 // eta rule for tuples:
321 // (extract(tup, 0), extract(tup, 1), extract(tup, 2)) -> tup
322 if (auto extract = ops[0]->isa<Extract>()) {
323 auto tup = extract->tuple();
324 bool eta = tup->type() == type;
325 for (size_t i = 0; i != n && eta; ++i) {
326 if (auto extract = ops[i]->isa<Extract>()) {
327 if (auto index = Lit::isa(extract->index())) {
328 if (eta &= u64(i) == *index) {
329 eta &= extract->tuple() == tup;
330 continue;
331 }
332 }
333 }
334 eta = false;
335 }
336
337 if (eta) return tup;
338 }
339 }
340
341 return unify<Tuple>(type, ops);
342}
343
344const Def* World::tuple(Sym sym) {
345 DefVec defs;
346 std::ranges::transform(sym, std::back_inserter(defs), [this](auto c) { return lit_i8(c); });
347 return tuple(defs);
348}
349
350const Def* World::extract(const Def* d, const Def* index) {
351 if (!d || !index) return nullptr; // can happen if frozen
352 d = d->zonk();
353 index = index->zonk();
354
355 if (auto tuple = index->isa<Tuple>()) {
356 for (auto op : tuple->ops())
357 d = extract(d, op);
358 return d;
359 } else if (auto pack = index->isa<Pack>()) {
360 if (auto a = Lit::isa(index->arity())) {
361 for (nat_t i = 0, e = *a; i != e; ++i) {
362 auto idx = pack->has_var() ? pack->reduce(lit_idx(*a, i)) : pack->body();
363 d = extract(d, idx);
364 }
365 return d;
366 }
367 }
368
369 auto size = Idx::isa(index->type());
370 auto type = d->unfold_type();
371
372 if (size) {
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);
375 if (auto sigma = type->isa_mut<Sigma>(); sigma && sigma->num_ops() == 1) {
376 // mut sigmas can be 1-tuples; TODO mutables Arr?
377 } else {
378 return d;
379 }
380 }
381 }
382
383 if (auto pack = d->isa_imm<Pack>()) return pack->body();
384
385 if (size && !Checker::alpha<Checker::Check>(type->arity(), size))
386 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
387
388 // extract(insert(x, index, val), index) -> val
389 if (auto insert = d->isa<Insert>()) {
390 if (index == insert->index()) return insert->value();
391 }
392
393 if (auto i = Lit::isa(index)) {
394 if (auto hole = d->isa_mut<Hole>()) d = hole->tuplefy(Idx::as_lit(index->type()));
395 if (auto tuple = d->isa<Tuple>()) return tuple->op(*i);
396
397 // extract(insert(x, j, val), i) -> extract(x, i) where i != j (guaranteed by rule above)
398 if (auto insert = d->isa<Insert>()) {
399 if (insert->index()->isa<Lit>()) return extract(insert->tuple(), index);
400 }
401
402 if (auto sigma = type->isa<Sigma>()) {
403 if (auto var = sigma->has_var()) {
404 if (is_frozen()) return nullptr; // if frozen, we don't risk rewriting
405 auto t = VarRewriter(var, d).rewrite(sigma->op(*i));
406 return unify<Extract>(t, d, index);
407 }
408
409 return unify<Extract>(sigma->op(*i), d, index);
410 }
411 }
412
413 const Def* elem_t;
414 if (auto arr = type->isa<Arr>())
415 elem_t = arr->reduce(index);
416 else
417 elem_t = join(type->as<Sigma>()->ops());
418
419 if (index->isa<Top>()) {
420 if (auto hole = Hole::isa_unset(d)) {
421 auto elem_hole = mut_hole(elem_t);
422 hole->set(pack(size, elem_hole));
423 return elem_hole;
424 }
425 }
426
427 assert(d);
428 return unify<Extract>(elem_t, d, index);
429}
430
431const Def* World::insert(const Def* d, const Def* index, const Def* val) {
432 d = d->zonk();
433 index = index->zonk();
434 val = val->zonk();
435
436 auto type = d->unfold_type();
437 auto size = Idx::isa(index->type());
438 auto lidx = Lit::isa(index);
439
440 if (!size) error(d->loc(), "index '{}' must be of type 'Idx' but is of type '{}'", index, index->type());
441
442 if (!Checker::alpha<Checker::Check>(type->arity(), size))
443 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
444
445 if (lidx) {
446 auto elem_type = type->proj(*lidx);
447 auto new_val = Checker::assignable(elem_type, val);
448 if (!new_val) {
449 throw Error()
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);
453 }
454 val = new_val;
455 }
456
457 if (auto l = Lit::isa(size); l && *l == 1)
458 return tuple(d, {val}); // d could be mut - that's why the tuple ctor is needed
459
460 // insert((a, b, c, d), 2, x) -> (a, b, x, d)
461 if (auto t = d->isa<Tuple>(); t && lidx) return t->refine(*lidx, val);
462
463 // insert(‹4; x›, 2, y) -> (x, x, y, x)
464 if (auto pack = d->isa<Pack>(); pack && lidx) {
465 if (auto a = Lit::isa(pack->arity()); a && *a < flags().scalarize_threshold) {
466 auto new_ops = DefVec(*a, pack->body());
467 new_ops[*lidx] = val;
468 return tuple(type, new_ops);
469 }
470 }
471
472 // insert(insert(x, index, y), index, val) -> insert(x, index, val)
473 if (auto insert = d->isa<Insert>()) {
474 if (insert->index() == index) d = insert->tuple();
475 }
476
477 return unify<Insert>(d, index, val);
478}
479
480const Def* World::seq(bool term, const Def* arity, const Def* body) {
481 arity = arity->zonk(); // TODO use zonk_mut all over the place and rmeove zonk from is_shape?
482 body = body->zonk();
483
484 auto arity_ty = arity->unfold_type();
485 if (!is_shape(arity_ty)) error(arity->loc(), "expected arity but got `{}` of type `{}`", arity, arity_ty);
486
487 if (auto a = Lit::isa(arity)) {
488 if (*a == 0) return unit(term);
489 if (*a == 1) return body;
490 }
491
492 // «(a, b, c); body» -> «a; «(b, c); body»»
493 if (auto tuple = arity->isa<Tuple>())
494 return seq(term, tuple->ops().front(), seq(term, tuple->ops().subspan(1), body));
495
496 // «‹n; x›; body» -> «x; «<n-1, x>; 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));
499 }
500
501 if (term) {
502 auto type = arr(arity, body->type());
503 return unify<Pack>(type, body);
504 } else {
505 return unify<Arr>(body->unfold_type(), arity, body);
506 }
507}
508
509const Def* World::seq(bool term, Defs shape, const Def* body) {
510 if (shape.empty()) return body;
511 return seq(term, shape.rsubspan(1), seq(term, shape.back(), body));
512}
513
514const Lit* World::lit(const Def* type, u64 val) {
515 type = type->zonk();
516
517 if (auto size = Idx::isa(type)) {
518 if (size->isa<Top>()) {
519 // unsafe but fine
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) { // 0 of any size is allowed
523 error(type->loc(), "cannot create literal '{}' of 'Idx {}' as size is unknown", val, size);
524 }
525 }
526
527 return unify<Lit>(type, val);
528}
529
530/*
531 * set
532 */
533
534template<bool Up>
535const Def* World::ext(const Def* type) {
536 type = type->zonk();
537
538 if (auto arr = type->isa<Arr>()) return pack(arr->arity(), ext<Up>(arr->body()));
539 if (auto sigma = type->isa<Sigma>())
540 return tuple(sigma, DefVec(sigma->num_ops(), [&](size_t i) { return ext<Up>(sigma->op(i)); }));
541 return unify<TExt<Up>>(type);
542}
543
544template<bool Up>
545const Def* World::bound(Defs ops_) {
546 auto ops = DefVec();
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); // ignore: ext<!Up>
550 }
551
552 auto kind = umax<UMax::Type>(ops);
553
554 // has ext<Up> value?
555 if (std::ranges::any_of(ops, [&](const Def* op) -> bool { return op->isa<TExt<Up>>(); })) return ext<Up>(kind);
556
557 // sort and remove duplicates
558 std::ranges::sort(ops, GIDLt<const Def*>());
559 ops.resize(std::distance(ops.begin(), std::unique(ops.begin(), ops.end())));
560
561 if (ops.size() == 0) return ext<!Up>(kind);
562 if (ops.size() == 1) return ops[0];
563
564 // TODO simplify mixed terms with joins and meets?
565 return unify<TBound<Up>>(kind, ops);
566}
567
568const Def* World::merge(const Def* type, Defs ops_) {
569 type = type->zonk();
570 auto ops = Def::zonk(ops_);
571
572 if (type->isa<Meet>()) {
573 auto types = DefVec(ops.size(), [&](size_t i) { return ops[i]->type(); });
574 return unify<Merge>(meet(types), ops);
575 }
576
577 assert(ops.size() == 1);
578 return ops[0];
579}
580
581const Def* World::merge(Defs ops_) {
582 auto ops = Def::zonk(ops_);
583 return merge(umax<UMax::Term>(ops), ops);
584}
585
586const Def* World::inj(const Def* type, const Def* value) {
587 type = type->zonk();
588 value = value->zonk();
589
590 if (type->isa<Join>()) return unify<Inj>(type, value);
591 return value;
592}
593
594const Def* World::split(const Def* type, const Def* value) {
595 type = type->zonk();
596 value = value->zonk();
597
598 return unify<Split>(type, value);
599}
600
601const Def* World::match(Defs ops_) {
602 auto ops = Def::zonk(ops_);
603 if (ops.size() == 1) return ops.front();
604
605 auto scrutinee = ops.front();
606 auto arms = ops.span().subspan(1);
607 auto join = scrutinee->type()->isa<Join>();
608
609 if (!join) error(scrutinee->loc(), "scrutinee of a test expression must be of union type");
610
611 if (arms.size() != join->num_ops())
612 error(scrutinee->loc(), "test expression has {} arms but union type has {} cases", arms.size(),
613 join->num_ops());
614
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());
618
619 std::ranges::sort(arms, [](const Def* arm1, const Def* arm2) {
620 return arm1->type()->as<Pi>()->dom()->gid() < arm2->type()->as<Pi>()->dom()->gid();
621 });
622
623 const Def* type = nullptr;
624 for (size_t i = 0, e = arms.size(); i != e; ++i) {
625 auto arm = arms[i];
626 auto pi = arm->type()->as<Pi>();
627 if (!Checker::alpha<Checker::Check>(pi->dom(), join->op(i)))
628 error(arm->loc(),
629 "domain type '{}' of arm in a test expression does not match case type '{}' in union type", pi->dom(),
630 join->op(i));
631 type = type ? this->join({type, pi->codom()}) : pi->codom();
632 }
633
634 return unify<Match>(type, ops);
635}
636
637const Def* World::uniq(const Def* inhabitant) {
638 inhabitant = inhabitant->zonk();
639 return unify<Uniq>(inhabitant->type()->unfold_type(), inhabitant);
640}
641
642Sym World::append_suffix(Sym symbol, std::string suffix) {
643 auto name = symbol.str();
644
645 auto pos = name.find(suffix);
646 if (pos != std::string::npos) {
647 auto num = name.substr(pos + suffix.size());
648 if (num.empty()) {
649 name += "_1";
650 } else {
651 num = num.substr(1);
652 num = std::to_string(std::stoi(num) + 1);
653 name = name.substr(0, pos + suffix.size()) + "_" + num;
654 }
655 } else {
656 name += suffix;
657 }
658
659 return sym(std::move(name));
660}
661
662Defs World::reduce(const Var* var, const Def* arg) {
663 auto mut = var->mut();
664 auto offset = mut->reduction_offset();
665 auto size = mut->num_ops() - offset;
666
667 if (auto i = move_.substs.find({var, arg}); i != move_.substs.end()) return i->second->defs();
668
669 auto buf = move_.arena.substs.allocate(sizeof(Reduct) + size * sizeof(const Def*), alignof(const Def*));
670 auto reduct = new (buf) Reduct(size);
671 auto rw = VarRewriter(var, arg);
672 for (size_t i = 0; i != size; ++i)
673 reduct->defs_[i] = rw.rewrite(mut->op(i + offset));
674 assert_emplace(move_.substs, std::pair{var, arg}, reduct);
675 return reduct->defs();
676}
677
678void World::for_each(bool elide_empty, std::function<void(Def*)> f) {
680 for (auto mut : externals().muts())
681 queue.push(mut);
682
683 while (!queue.empty()) {
684 auto mut = queue.pop();
685 if (mut && mut->is_closed() && (!elide_empty || mut->is_set())) f(mut);
686
687 for (auto op : mut->deps())
688 for (auto mut : op->local_muts())
689 queue.push(mut);
690 }
691}
692
693/*
694 * debugging
695 */
696
697#ifdef MIM_ENABLE_CHECKS
698
699void World::breakpoint(u32 gid) { state_.breakpoints.emplace(gid); }
700void World::watchpoint(u32 gid) { state_.watchpoints.emplace(gid); }
701
702const Def* World::gid2def(u32 gid) {
703 auto i = std::ranges::find_if(move_.defs, [=](auto def) { return def->gid() == gid; });
704 if (i == move_.defs.end()) return nullptr;
705 return *i;
706}
707
709 for (auto mut : externals().muts())
710 assert(mut->is_closed() && mut->is_set());
711 for (auto anx : annexes())
712 assert(anx->is_closed());
713 return *this;
714}
715
716#endif
717
718#ifndef DOXYGEN
719template const Def* World::umax<UMax::Term>(Defs);
720template const Def* World::umax<UMax::Type>(Defs);
721template const Def* World::umax<UMax::Kind>(Defs);
722template const Def* World::umax<UMax::Univ>(Defs);
723template const Def* World::ext<true>(const Def*);
724template const Def* World::ext<false>(const Def*);
725template const Def* World::bound<true>(Defs);
726template const Def* World::bound<false>(Defs);
727template const Def* World::app<true>(const Def*, const Def*);
728template const Def* World::app<false>(const Def*, const Def*);
729template const Def* World::implicit_app<true>(const Def*, const Def*);
730template const Def* World::implicit_app<false>(const Def*, const Def*);
731#endif
732
733} // 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:431
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:514
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:700
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:282
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:200
const Def * match(Defs)
Definition world.cpp:601
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:480
World & verify()
Verifies that all externals() and annexes() are Def::is_closed(), if MIM_ENABLE_CHECKS.
Definition world.cpp:708
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:678
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:292
const Def * gid2def(u32 gid)
Lookup Def by gid.
Definition world.cpp:702
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:193
const Def * inj(const Def *type, const Def *value)
Definition world.cpp:586
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:350
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:545
const Def * join(Defs ops)
Definition world.h:508
const Def * ext(const Def *type)
Definition world.cpp:535
Sym append_suffix(Sym name, std::string suffix)
Appends a suffix or an increasing number if the suffix already exists.
Definition world.cpp:642
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:637
const Def * raw_app(const Axm *axm, u8 curry, u8 trip, const Def *type, const Def *callee, const Def *arg)
Definition world.cpp:278
const Def * umax(Defs)
Definition world.cpp:138
const Def * merge(const Def *type, Defs ops)
Definition world.cpp:568
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:662
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
Definition world.cpp:699
const Def * split(const Def *type, const Def *value)
Definition world.cpp:594
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