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
351bool isa_indicies(const Def* def) {
352 if (Idx::isa(def)) return true;
353 if (auto sigma = def->isa<Sigma>()) return std::ranges::all_of(sigma->ops(), [](auto op) { return Idx::isa(op); });
354 if (auto arr = def->isa<Arr>()) return Idx::isa(arr->body());
355 return false;
356}
357
358const Def* World::extract(const Def* d, const Def* index) {
359 if (!d || !index) return nullptr; // can happen if frozen
360 d = d->zonk();
361 index = index->zonk();
362
363 if (!isa_indicies(index->type()))
364 error(index->loc(), "index '{}' is not of Idx type but of type '{}'", index, index->type());
365
366 if (auto tuple = index->isa<Tuple>()) {
367 for (auto op : tuple->ops())
368 d = extract(d, op);
369 return d;
370 } else if (auto pack = index->isa<Pack>()) {
371 if (auto a = Lit::isa(index->arity())) {
372 for (nat_t i = 0, e = *a; i != e; ++i) {
373 auto idx = pack->has_var() ? pack->reduce(lit_idx(*a, i)) : pack->body();
374 d = extract(d, idx);
375 }
376 return d;
377 }
378 }
379
380 auto size = Idx::isa(index->type());
381 auto type = d->unfold_type();
382
383 if (size) {
384 if (auto l = Lit::isa(size); l && *l == 1) {
385 if (auto l = Lit::isa(index); !l || *l != 0) WLOG("unknown Idx of size 1: {}", index);
386 if (auto sigma = type->isa_mut<Sigma>(); sigma && sigma->num_ops() == 1) {
387 // mut sigmas can be 1-tuples; TODO mutables Arr?
388 } else {
389 return d;
390 }
391 }
392 }
393
394 if (auto pack = d->isa_imm<Pack>()) return pack->body();
395
396 if (size && !Checker::alpha<Checker::Check>(type->arity(), size))
397 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
398 // TODO if we have indices we need to check as well that this is compatible with `d`
399
400 // extract(insert(x, index, val), index) -> val
401 if (auto insert = d->isa<Insert>()) {
402 if (index == insert->index()) return insert->value();
403 }
404
405 if (auto i = Lit::isa(index)) {
406 if (auto hole = d->isa_mut<Hole>()) d = hole->tuplefy(Idx::as_lit(index->type()));
407 if (auto tuple = d->isa<Tuple>()) return tuple->op(*i);
408
409 // extract(insert(x, j, val), i) -> extract(x, i) where i != j (guaranteed by rule above)
410 if (auto insert = d->isa<Insert>()) {
411 if (insert->index()->isa<Lit>()) return extract(insert->tuple(), index);
412 }
413
414 if (auto sigma = type->isa<Sigma>()) {
415 if (auto var = sigma->has_var()) {
416 if (is_frozen()) return nullptr; // if frozen, we don't risk rewriting
417 auto t = VarRewriter(var, d).rewrite(sigma->op(*i));
418 return unify<Extract>(t, d, index);
419 }
420
421 return unify<Extract>(sigma->op(*i), d, index);
422 }
423 }
424
425 const Def* elem_t;
426 if (auto arr = type->isa<Arr>())
427 elem_t = arr->reduce(index);
428 else
429 elem_t = join(type->as<Sigma>()->ops());
430
431 if (index->isa<Top>()) {
432 if (auto hole = Hole::isa_unset(d)) {
433 auto elem_hole = mut_hole(elem_t);
434 hole->set(pack(size, elem_hole));
435 return elem_hole;
436 }
437 }
438
439 assert(d);
440 return unify<Extract>(elem_t, d, index);
441}
442
443const Def* World::insert(const Def* d, const Def* index, const Def* val) {
444 d = d->zonk();
445 index = index->zonk();
446 val = val->zonk();
447
448 auto type = d->unfold_type();
449 auto size = Idx::isa(index->type());
450 auto lidx = Lit::isa(index);
451
452 if (!size) error(d->loc(), "index '{}' must be of type 'Idx' but is of type '{}'", index, index->type());
453
454 if (!Checker::alpha<Checker::Check>(type->arity(), size))
455 error(index->loc(), "index '{}' does not fit within arity '{}'", index, type->arity());
456
457 if (lidx) {
458 auto elem_type = type->proj(*lidx);
459 auto new_val = Checker::assignable(elem_type, val);
460 if (!new_val) {
461 throw Error()
462 .error(val->loc(), "value to be inserted not assignable to element")
463 .note(val->loc(), "vvv value type vvv \n'{}'\n'{}'", val->type(), elem_type)
464 .note(val->loc(), "^^^ element type ^^^", elem_type);
465 }
466 val = new_val;
467 }
468
469 if (auto l = Lit::isa(size); l && *l == 1)
470 return tuple(d, {val}); // d could be mut - that's why the tuple ctor is needed
471
472 // insert((a, b, c, d), 2, x) -> (a, b, x, d)
473 if (auto t = d->isa<Tuple>(); t && lidx) return t->refine(*lidx, val);
474
475 // insert(‹4; x›, 2, y) -> (x, x, y, x)
476 if (auto pack = d->isa<Pack>(); pack && lidx) {
477 if (auto a = Lit::isa(pack->arity()); a && *a < flags().scalarize_threshold) {
478 auto new_ops = DefVec(*a, pack->body());
479 new_ops[*lidx] = val;
480 return tuple(type, new_ops);
481 }
482 }
483
484 // insert(insert(x, index, y), index, val) -> insert(x, index, val)
485 if (auto insert = d->isa<Insert>()) {
486 if (insert->index() == index) d = insert->tuple();
487 }
488
489 return unify<Insert>(d, index, val);
490}
491
492const Def* World::seq(bool term, const Def* arity, const Def* body) {
493 arity = arity->zonk(); // TODO use zonk_mut all over the place and rmeove zonk from is_shape?
494 body = body->zonk();
495
496 auto arity_ty = arity->unfold_type();
497 if (!is_shape(arity_ty)) error(arity->loc(), "expected arity but got `{}` of type `{}`", arity, arity_ty);
498
499 if (auto a = Lit::isa(arity)) {
500 if (*a == 0) return unit(term);
501 if (*a == 1) return body;
502 }
503
504 // «(a, b, c); body» -> «a; «(b, c); body»»
505 // e.g. when var, but still has array type
506 if (auto arr_arity = arity->type()->isa<Seq>())
507 if (auto lit_arity_arity = Lit::isa(arr_arity->arity())) {
508 DefVec inner_arity(*lit_arity_arity - 1, [&](u64 i) { return arity->proj(*lit_arity_arity, i + 1); });
509 return seq(term, arity->proj(*lit_arity_arity, 0), seq(term, tuple(inner_arity), body));
510 }
511
512
513 if (term) {
514 auto type = arr(arity, body->type());
515 return unify<Pack>(type, body);
516 } else {
517 return unify<Arr>(body->unfold_type(), arity, body);
518 }
519}
520
521const Def* World::seq(bool term, Defs shape, const Def* body) {
522 if (shape.empty()) return body;
523 return seq(term, shape.rsubspan(1), seq(term, shape.back(), body));
524}
525
526const Lit* World::lit(const Def* type, u64 val) {
527 if (!type) return nullptr;
528 type = type->zonk();
529
530 if (auto size = Idx::isa(type)) {
531 if (size->isa<Top>()) {
532 // unsafe but fine
533 } else if (auto s = Lit::isa(size)) {
534 if (*s != 0 && val >= *s) error(type->loc(), "index '{}' does not fit within arity '{}'", size, val);
535 } else if (val != 0) { // 0 of any size is allowed
536 error(type->loc(), "cannot create literal '{}' of 'Idx {}' as size is unknown", val, size);
537 }
538 }
539
540 return unify<Lit>(type, val);
541}
542
543/*
544 * set
545 */
546
547template<bool Up>
548const Def* World::ext(const Def* type) {
549 type = type->zonk();
550
551 if (auto arr = type->isa<Arr>()) return pack(arr->arity(), ext<Up>(arr->body()));
552 if (auto sigma = type->isa<Sigma>())
553 return tuple(sigma, DefVec(sigma->num_ops(), [&](size_t i) { return ext<Up>(sigma->op(i)); }));
554 return unify<TExt<Up>>(type);
555}
556
557template<bool Up>
558const Def* World::bound(Defs ops_) {
559 auto ops = DefVec();
560 for (size_t i = 0, e = ops_.size(); i != e; ++i) {
561 auto op = ops_[i]->zonk();
562 if (!op->isa<TExt<!Up>>()) ops.emplace_back(op); // ignore: ext<!Up>
563 }
564
565 auto kind = umax<UMax::Type>(ops);
566
567 // has ext<Up> value?
568 if (std::ranges::any_of(ops, [&](const Def* op) -> bool { return op->isa<TExt<Up>>(); })) return ext<Up>(kind);
569
570 // sort and remove duplicates
571 std::ranges::sort(ops, GIDLt<const Def*>());
572 ops.resize(std::distance(ops.begin(), std::unique(ops.begin(), ops.end())));
573
574 if (ops.size() == 0) return ext<!Up>(kind);
575 if (ops.size() == 1) return ops[0];
576
577 // TODO simplify mixed terms with joins and meets?
578 return unify<TBound<Up>>(kind, ops);
579}
580
581const Def* World::merge(const Def* type, Defs ops_) {
582 type = type->zonk();
583 auto ops = Def::zonk(ops_);
584
585 if (type->isa<Meet>()) {
586 auto types = DefVec(ops.size(), [&](size_t i) { return ops[i]->type(); });
587 return unify<Merge>(meet(types), ops);
588 }
589
590 assert(ops.size() == 1);
591 return ops[0];
592}
593
594const Def* World::merge(Defs ops_) {
595 auto ops = Def::zonk(ops_);
596 return merge(umax<UMax::Term>(ops), ops);
597}
598
599const Def* World::inj(const Def* type, const Def* value) {
600 type = type->zonk();
601 value = value->zonk();
602
603 if (type->isa<Join>()) return unify<Inj>(type, value);
604 return value;
605}
606
607const Def* World::split(const Def* type, const Def* value) {
608 type = type->zonk();
609 value = value->zonk();
610
611 return unify<Split>(type, value);
612}
613
614const Def* World::match(Defs ops_) {
615 auto ops = Def::zonk(ops_);
616 if (ops.size() == 1) return ops.front();
617
618 auto scrutinee = ops.front();
619 auto arms = ops.span().subspan(1);
620 auto join = scrutinee->type()->isa<Join>();
621
622 if (!join) error(scrutinee->loc(), "scrutinee of a test expression must be of union type");
623
624 if (arms.size() != join->num_ops())
625 error(scrutinee->loc(), "test expression has {} arms but union type has {} cases", arms.size(),
626 join->num_ops());
627
628 for (auto arm : arms)
629 if (!arm->type()->isa<Pi>())
630 error(arm->loc(), "arm of test expression does not have a function type but is of type '{}'", arm->type());
631
632 std::ranges::sort(arms, [](const Def* arm1, const Def* arm2) {
633 return arm1->type()->as<Pi>()->dom()->gid() < arm2->type()->as<Pi>()->dom()->gid();
634 });
635
636 const Def* type = nullptr;
637 for (size_t i = 0, e = arms.size(); i != e; ++i) {
638 auto arm = arms[i];
639 auto pi = arm->type()->as<Pi>();
640 if (!Checker::alpha<Checker::Check>(pi->dom(), join->op(i)))
641 error(arm->loc(),
642 "domain type '{}' of arm in a test expression does not match case type '{}' in union type", pi->dom(),
643 join->op(i));
644 type = type ? this->join({type, pi->codom()}) : pi->codom();
645 }
646
647 return unify<Match>(type, ops);
648}
649
650const Def* World::uniq(const Def* inhabitant) {
651 inhabitant = inhabitant->zonk();
652 return unify<Uniq>(inhabitant->type()->unfold_type(), inhabitant);
653}
654
655Sym World::append_suffix(Sym symbol, std::string suffix) {
656 auto name = symbol.str();
657
658 auto pos = name.find(suffix);
659 if (pos != std::string::npos) {
660 auto num = name.substr(pos + suffix.size());
661 if (num.empty()) {
662 name += "_1";
663 } else {
664 num = num.substr(1);
665 num = std::to_string(std::stoi(num) + 1);
666 name = name.substr(0, pos + suffix.size()) + "_" + num;
667 }
668 } else {
669 name += suffix;
670 }
671
672 return sym(std::move(name));
673}
674
675Defs World::reduce(const Var* var, const Def* arg) {
676 auto mut = var->mut();
677 auto offset = mut->reduction_offset();
678 auto size = mut->num_ops() - offset;
679
680 if (auto i = move_.substs.find({var, arg}); i != move_.substs.end()) return i->second->defs();
681
682 auto buf = move_.arena.substs.allocate(sizeof(Reduct) + size * sizeof(const Def*), alignof(const Def*));
683 auto reduct = new (buf) Reduct(size);
684 auto rw = VarRewriter(var, arg);
685 for (size_t i = 0; i != size; ++i)
686 reduct->defs_[i] = rw.rewrite(mut->op(i + offset));
687 assert_emplace(move_.substs, std::pair{var, arg}, reduct);
688 return reduct->defs();
689}
690
691void World::for_each(bool elide_empty, std::function<void(Def*)> f) {
693 for (auto mut : externals().muts())
694 queue.push(mut);
695
696 while (!queue.empty()) {
697 auto mut = queue.pop();
698 if (mut && mut->is_closed() && (!elide_empty || mut->is_set())) f(mut);
699
700 for (auto op : mut->deps())
701 for (auto mut : op->local_muts())
702 queue.push(mut);
703 }
704}
705
706/*
707 * debugging
708 */
709
710#ifdef MIM_ENABLE_CHECKS
711
712void World::breakpoint(u32 gid) { state_.breakpoints.emplace(gid); }
713void World::watchpoint(u32 gid) { state_.watchpoints.emplace(gid); }
714
715const Def* World::gid2def(u32 gid) {
716 auto i = std::ranges::find_if(move_.defs, [=](auto def) { return def->gid() == gid; });
717 if (i == move_.defs.end()) return nullptr;
718 return *i;
719}
720
722 for (auto mut : externals().muts())
723 assert(mut->is_closed() && mut->is_set());
724 for (auto anx : annexes())
725 assert(anx->is_closed());
726 return *this;
727}
728
729#endif
730
731#ifndef DOXYGEN
732template const Def* World::umax<UMax::Term>(Defs);
733template const Def* World::umax<UMax::Type>(Defs);
734template const Def* World::umax<UMax::Kind>(Defs);
735template const Def* World::umax<UMax::Univ>(Defs);
736template const Def* World::ext<true>(const Def*);
737template const Def* World::ext<false>(const Def*);
738template const Def* World::bound<true>(Defs);
739template const Def* World::bound<false>(Defs);
740template const Def* World::app<true>(const Def*, const Def*);
741template const Def* World::app<false>(const Def*, const Def*);
742template const Def* World::implicit_app<true>(const Def*, const Def*);
743template const Def* World::implicit_app<false>(const Def*, const Def*);
744#endif
745
746} // namespace mim
A (possibly paramterized) Array.
Definition tuple.h:117
Definition axm.h:9
static constexpr u8 Trip_End
Definition axm.h:135
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:114
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:252
const Def * proj(nat_t a, nat_t i) const
Similar to World::extract while assuming an arity of a, but also works on Sigmas and Arrays.
Definition def.cpp:593
Defs deps() const noexcept
Definition def.cpp:475
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:306
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
Definition def.h:498
const Def * unfold_type() const
Yields the type of this Def and builds a new Type (UInc n) if necessary.
Definition def.cpp:457
Muts local_muts() const
Mutables reachable by following immutable deps(); mut->local_muts() is by definition the set { mut }...
Definition def.cpp:332
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
Definition def.cpp:452
bool is_external() const noexcept
Definition def.h:479
Loc loc() const
Definition def.h:519
Sym sym() const
Definition def.h:520
const Def * var_type()
If this is a binder, compute the type of its Variable.
Definition def.cpp:315
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
Definition def.h:271
virtual const Def * arity() const
Definition def.cpp:558
const T * isa_imm() const
Definition def.h:492
bool is_closed() const
Has no free_vars()?
Definition def.cpp:418
Some "global" variables needed all over the place.
Definition driver.h:19
Log & log() const
Definition driver.h:27
Flags & flags()
Definition driver.h:25
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:899
static const Def * isa(const Def *def)
Checks if def is a Idx s and returns s or nullptr otherwise.
Definition def.cpp:616
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:843
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
Base class for Arr and Pack.
Definition tuple.h:84
A dependent tuple type.
Definition tuple.h:20
static const Def * infer(World &, Defs)
Definition check.cpp:291
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:284
@ Type
Definition def.h:764
@ Univ
Definition def.h:764
@ Term
Definition def.h:764
@ Kind
Definition def.h:764
Extends Rewriter for variable substitution.
Definition rewrite.h:113
const Def * rewrite(const Def *) final
Definition rewrite.cpp:182
A variable introduced by a binder (mutable).
Definition def.h:719
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:488
const Def * insert(const Def *d, const Def *i, const Def *val)
Definition world.cpp:443
const Def * meet(Defs ops)
Definition world.h:530
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:526
const Def * seq(bool is_pack, const Def *arity, const Def *body)
Definition world.cpp:492
auto & muts()
Definition world.h:622
const Lit * lit_i8()
Definition world.h:482
void watchpoint(u32 gid)
Trigger breakpoint in your debugger when Def::setting a Def with this gid.
Definition world.cpp:713
const Type * type(const Def *level)
Definition world.cpp:108
const Driver & driver() const
Definition world.h:89
const Lit * lit_tt()
Definition world.h:515
const Def * filter(Lam::Filter filter)
Definition world.h:333
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:410
const Def * app(const Def *callee, const Def *arg)
Definition world.cpp:201
const Def * match(Defs)
Definition world.cpp:614
const Pi * pi(const Def *dom, const Def *codom, bool implicit=false)
Definition world.h:309
const Def * unit(bool is_pack)
Definition world.h:429
World & verify()
Verifies that all externals() and annexes() are Def::is_closed(), if MIM_ENABLE_CHECKS.
Definition world.cpp:721
const Idx * type_idx()
Definition world.h:548
const Lit * lit_univ_0()
Definition world.h:473
Sym name() const
Definition world.h:93
void for_each(bool elide_empty, std::function< void(Def *)>)
Definition world.cpp:691
const Lit * lit_univ_1()
Definition world.h:474
const Nat * type_nat()
Definition world.h:547
Hole * mut_hole(const Def *type)
Definition world.h:276
const Lam * lam(const Pi *pi, Lam::Filter f, const Def *body)
Definition world.h:337
const Def * tuple(Defs ops)
Definition world.cpp:293
const Def * gid2def(u32 gid)
Lookup Def by gid.
Definition world.cpp:715
Flags & flags()
Retrieve compile Flags.
Definition world.cpp:87
const Def * implicit_app(const Def *callee, const Def *arg)
Definition world.cpp:194
const Def * inj(const Def *type, const Def *value)
Definition world.cpp:599
const Type * type()
Definition world.h:265
const Axm * axm(NormalizeFn n, u8 curry, u8 trip, const Def *type, plugin_t p, tag_t t, sub_t s)
Definition world.h:291
const Def * extract(const Def *d, const Def *i)
Definition world.cpp:358
bool is_frozen() const
Definition world.h:143
const Def * arr(const Def *arity, const Def *body)
Definition world.h:409
Sym sym(std::string_view)
Definition world.cpp:90
const Lit * lit_ff()
Definition world.h:514
const Def * bound(Defs ops)
Definition world.cpp:558
const Def * join(Defs ops)
Definition world.h:529
const Def * ext(const Def *type)
Definition world.cpp:548
Sym append_suffix(Sym name, std::string suffix)
Appends a suffix or an increasing number if the suffix already exists.
Definition world.cpp:655
const Lit * lit_idx_1_0()
Definition world.h:479
const Lit * lit_univ(u64 level)
Definition world.h:472
const Def * var(Def *mut)
Definition world.cpp:180
const Tuple * tuple()
the unit value of type []
Definition world.h:445
const Def * uniq(const Def *inhabitant)
Definition world.cpp:650
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 Externals & externals() const
Definition world.h:252
const Def * umax(Defs)
Definition world.cpp:138
const Def * merge(const Def *type, Defs ops)
Definition world.cpp:581
const Sigma * sigma()
The unit type within Type 0.
Definition world.h:397
const Lit * lit_nat(nat_t a)
Definition world.h:475
const State & state() const
Definition world.h:88
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:675
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
Definition world.cpp:712
const Def * split(const Def *type, const Def *value)
Definition world.cpp:607
auto annexes() const
Definition world.h:192
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:77
u64 nat_t
Definition types.h:44
Vector< const Def * > DefVec
Definition def.h:78
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:46
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:43
TExt< true > Top
Definition lattice.h:172
uint32_t u32
Definition types.h:35
static void flatten_umax(DefVec &ops, const Def *def)
Definition world.cpp:129
uint64_t u64
Definition types.h:35
bool isa_indicies(const Def *def)
Definition world.cpp:351
uint8_t u8
Definition types.h:35
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