MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
dump.cpp
Go to the documentation of this file.
1#include <fstream>
2
3#include <fe/assert.h>
4
5#include "mim/driver.h"
6
8#include "mim/ast/tok.h"
9#include "mim/util/util.h"
10
11using namespace std::literals;
12
13// During dumping, we classify Defs according to the following logic:
14// * Inline: These Defs are *always* displayed with all of its operands "inline".
15// E.g.: (1, 2, 3).
16// * All other Defs are referenced by its name/unique_name (see id) when they appear as an operand.
17// * Mutables are either classifed as "decl" (see isa_decl).
18// In this case, recursing through the Defs' operands stops and this particular Decl is dumped as its own thing.
19// * Or - if they are not a "decl" - they are basicallally handled like immutables.
20
21namespace mim {
22
23namespace {
24
25Def* isa_decl(const Def* def) {
26 if (auto mut = def->isa_mut()) {
27 if (mut->is_external() || mut->isa<Lam>() || (mut->sym() && mut->sym() != '_')) return mut;
28 }
29 return nullptr;
30}
31
32std::string id(const Def* def) {
33 if (def->is_external() || (!def->is_set() && def->isa<Lam>())) return def->sym().str();
34 return def->unique_name();
35}
36
37std::string_view external(const Def* def) {
38 if (def->is_external()) return "extern "sv;
39 return ""sv;
40}
41
42/*
43 * Inline + LRPrec
44 */
45
46/// This is a wrapper to dump a Def "inline" and print it with all of its operands.
47struct Inline {
48 Inline(const Def* def, int dump_gid)
49 : def_(def)
50 , dump_gid_(dump_gid) {}
51 Inline(const Def* def)
52 : Inline(def, def->world().flags().dump_gid) {}
53
54 const Def* operator->() const { return def_; }
55 const Def* operator*() const { return def_; }
56 explicit operator bool() const {
57 if (def_->dep_const()) return true;
58
59 if (auto mut = def_->isa_mut()) {
60 if (isa_decl(mut)) return false;
61 return true;
62 }
63
64 if (auto app = def_->isa<App>()) {
65 if (app->type()->isa<Pi>()) return true; // curried apps are printed inline
66 if (app->type()->isa<Type>()) return true;
67 if (app->callee()->isa<Axiom>()) return app->callee_type()->num_doms() <= 1;
68 return false;
69 }
70
71 return true;
72 }
73
74private:
75 const Def* def_;
76 const int dump_gid_;
77
78 friend std::ostream& operator<<(std::ostream&, Inline);
79};
80
81#define MY_PREC(m) \
82 /* left prec, right */ \
83 m(Nil, Bot, Nil) m(Nil, Nil, Nil) m(Lam, Arrow, Arrow) m(Nil, Lam, Pi) m(Nil, Pi, App) m(App, App, Extract) \
84 m(Extract, Extract, Lit) m(Nil, Lit, Lit)
85
86enum class MyPrec {
87#define CODE(l, p, r) p,
89#undef CODE
90};
91
92static constexpr std::array<MyPrec, 2> my_prec(MyPrec p) {
93 switch (p) {
94#define CODE(l, p, r) \
95 case MyPrec::p: return {MyPrec::l, MyPrec::r};
96 default: fe::unreachable(); MY_PREC(CODE)
97#undef CODE
98 }
99}
100
101// clang-format off
102MyPrec my_prec(const Def* def) {
103 if (def->isa<Pi >()) return MyPrec::Arrow;
104 if (def->isa<App >()) return MyPrec::App;
105 if (def->isa<Extract>()) return MyPrec::Extract;
106 if (def->isa<Lit >()) return MyPrec::Lit;
107 return MyPrec::Bot;
108}
109// clang-format on
110
111// TODO prec is currently broken
112template<bool L> struct LRPrec {
113 LRPrec(const Def* l, const Def* r)
114 : l(l)
115 , r(r) {}
116
117private:
118 const Def* l;
119 const Def* r;
120
121 friend std::ostream& operator<<(std::ostream& os, const LRPrec& p) {
122 if constexpr (L) {
123 if (Inline(p.l) && my_prec(my_prec(p.r))[0] > my_prec(p.r)) return print(os, "({})", p.l);
124 return print(os, "{}", p.l);
125 } else {
126 if (Inline(p.r) && my_prec(p.l) > my_prec(my_prec(p.l))[1]) return print(os, "({})", p.r);
127 return print(os, "{}", p.r);
128 }
129 }
130};
131
132using LPrec = LRPrec<true>;
133using RPrec = LRPrec<false>;
134
135std::ostream& operator<<(std::ostream& os, Inline u) {
136 if (u.dump_gid_ == 2 || (u.dump_gid_ == 1 && !u->isa<Var>() && u->num_ops() != 0)) print(os, "/*{}*/", u->gid());
137 if (auto mut = u->isa_mut(); mut && !mut->is_set()) return os << "unset";
138
139 bool ascii = u->world().flags().ascii;
140 auto arw = ascii ? "->" : "→";
141 auto al = ascii ? "<<" : "«";
142 auto ar = ascii ? ">>" : "»";
143 auto pl = ascii ? "(<" : "‹";
144 auto pr = ascii ? ">)" : "›";
145
146 if (auto type = u->isa<Type>()) {
147 if (auto level = Lit::isa(type->level()); level && !ascii) {
148 if (level == 0) return print(os, "★");
149 if (level == 1) return print(os, "□");
150 }
151 return print(os, "(Type {})", type->level());
152 } else if (u->isa<Nat>()) {
153 return print(os, "Nat");
154 } else if (u->isa<Idx>()) {
155 return print(os, "Idx");
156 } else if (auto ext = u->isa<Ext>()) {
157 auto x = ext->isa<Bot>() ? (ascii ? ".bot" : "⊥") : (ascii ? ".top" : "⊤");
158 if (ext->type()->isa<Nat>()) return print(os, "{}:{}", x, ext->type());
159 return print(os, "{}:({})", x, ext->type());
160 } else if (auto top = u->isa<Top>()) {
161 return print(os, "{}:({})", ascii ? ".top" : "⊤", top->type());
162 } else if (auto axiom = u->isa<Axiom>()) {
163 const auto name = axiom->sym();
164 return print(os, "{}{}", name[0] == '%' ? "" : "%", name);
165 } else if (auto lit = u->isa<Lit>()) {
166 if (lit->type()->isa<Nat>()) {
167 switch (lit->get()) {
168 // clang-format off
169 case 0x0'0000'0100_n: return os << "i8";
170 case 0x0'0001'0000_n: return os << "i16";
171 case 0x1'0000'0000_n: return os << "i32";
172 // clang-format on
173 default: return print(os, "{}", lit->get());
174 }
175 } else if (auto size = Idx::size(lit->type())) {
176 if (auto s = Lit::isa(size)) {
177 switch (*s) {
178 // clang-format off
179 case 0x0'0000'0002_n: return os << (lit->get<bool>() ? "tt" : "ff");
180 case 0x0'0000'0100_n: return os << lit->get() << "I8";
181 case 0x0'0001'0000_n: return os << lit->get() << "I16";
182 case 0x1'0000'0000_n: return os << lit->get() << "I32";
183 case 0_n: return os << lit->get() << "I64";
184 default: {
185 os << lit->get();
186 std::vector<uint8_t> digits;
187 for (auto z = *s; z; z /= 10) digits.emplace_back(z % 10);
188
189 if (ascii) {
190 os << '_';
191 for (auto d : digits | std::ranges::views::reverse)
192 os << char('0' + d);
193 } else {
194 for (auto d : digits | std::ranges::views::reverse)
195 os << uint8_t(0xE2) << uint8_t(0x82) << (uint8_t(0x80 + d));
196 }
197 return os;
198 }
199 // clang-format on
200 }
201 }
202 }
203 if (lit->type()->isa<App>()) return print(os, "{}:({})", lit->get(), lit->type()); // HACK prec magic is broken
204 return print(os, "{}:{}", lit->get(), lit->type());
205 } else if (auto ex = u->isa<Extract>()) {
206 if (ex->tuple()->isa<Var>() && ex->index()->isa<Lit>()) return print(os, "{}", ex->unique_name());
207 return print(os, "{}#{}", ex->tuple(), ex->index());
208 } else if (auto var = u->isa<Var>()) {
209 return print(os, "{}", var->unique_name());
210 } else if (auto pi = u->isa<Pi>()) {
211 /*return os << "TODO";*/
212 if (Pi::isa_cn(pi)) return print(os, "Cn {}", pi->dom());
213 if (auto mut = pi->isa_mut<Pi>(); mut && mut->var())
214 return print(os, "Π {}: {} {} {}", mut->var(), pi->dom(), arw, pi->codom());
215 return print(os, "Π {} {} {}", pi->dom(), arw, pi->codom());
216 } else if (auto lam = u->isa<Lam>()) {
217 return print(os, "{}, {}", lam->filter(), lam->body());
218 } else if (auto app = u->isa<App>()) {
219 if (auto size = Idx::size(app)) {
220 if (auto l = Lit::isa(size)) {
221 // clang-format off
222 switch (*l) {
223 case 0x0'0000'0002_n: return os << "Bool";
224 case 0x0'0000'0100_n: return os << "I8";
225 case 0x0'0001'0000_n: return os << "I16";
226 case 0x1'0000'0000_n: return os << "I32";
227 case 0_n: return os << "I64";
228 default: break;
229 }
230 // clang-format on
231 }
232 }
233 return print(os, "{} {}", LPrec(app->callee(), app), RPrec(app, app->arg()));
234 } else if (auto sigma = u->isa<Sigma>()) {
235 if (auto mut = sigma->isa_mut<Sigma>(); mut && mut->var()) {
236 size_t i = 0;
237 return print(os, "[{, }]", Elem(sigma->ops(), [&](auto op) {
238 if (auto v = mut->var(i++))
239 print(os, "{}: {}", v, op);
240 else
241 os << op;
242 }));
243 }
244 return print(os, "[{, }]", sigma->ops());
245 } else if (auto tuple = u->isa<Tuple>()) {
246 print(os, "({, })", tuple->ops());
247 return tuple->type()->isa_mut() ? print(os, ":{}", tuple->type()) : os;
248 } else if (auto arr = u->isa<Arr>()) {
249 if (auto mut = arr->isa_mut<Arr>(); mut && mut->var())
250 return print(os, "{}{}: {}; {}{}", al, mut->var(), mut->shape(), mut->body(), ar);
251 return print(os, "{}{}; {}{}", al, arr->shape(), arr->body(), ar);
252 } else if (auto pack = u->isa<Pack>()) {
253 if (auto mut = pack->isa_mut<Pack>(); mut && mut->var())
254 return print(os, "{}{}: {}; {}{}", pl, mut->var(), mut->shape(), mut->body(), pr);
255 return print(os, "{}{}; {}{}", pl, pack->shape(), pack->body(), pr);
256 } else if (auto proxy = u->isa<Proxy>()) {
257 return print(os, ".proxy#{}#{} {, }", proxy->pass(), proxy->tag(), proxy->ops());
258 } else if (auto bound = u->isa<Bound>()) {
259 auto op = bound->isa<Join>() ? "∪" : "∩"; // TODO ascii
260 if (auto mut = u->isa_mut()) print(os, "{}{}: {}", op, mut->unique_name(), mut->type());
261 return print(os, "{}({, })", op, bound->ops());
262 }
263
264 // other
265 if (u->flags() == 0) return print(os, "(.{} {, })", u->node_name(), u->ops());
266 return print(os, "(.{}#{} {, })", u->node_name(), u->flags(), u->ops());
267}
268
269/*
270 * Dumper
271 */
272
273/// This thing operates in two modes:
274/// 1. The output of decls is driven by the DepTree.
275/// 2. Alternatively, decls are output as soon as they appear somewhere during recurse%ing.
276/// Then, they are pushed to Dumper::muts.
277class Dumper {
278public:
279 Dumper(std::ostream& os, const DepTree* dep = nullptr)
280 : os(os)
281 , dep(dep) {}
282
283 void dump(Def*);
284 void dump(Lam*);
285 void dump_let(const Def*);
286 void dump_ptrn(const Def*, const Def*);
287 void recurse(const DepNode*);
288 void recurse(const Def*, bool first = false);
289
290 std::ostream& os;
291 const DepTree* dep;
292 Tab tab;
293 unique_queue<MutSet> muts;
294 DefSet defs;
295};
296
297void Dumper::dump(Def* mut) {
298 if (auto lam = mut->isa<Lam>()) {
299 dump(lam);
300 return;
301 }
302
303 auto mut_prefix = [&](const Def* def) {
304 if (def->isa<Sigma>()) return "Sigma";
305 if (def->isa<Arr>()) return ".Arr";
306 if (def->isa<Pack>()) return ".pack";
307 if (def->isa<Pi>()) return ".Pi";
308 fe::unreachable();
309 };
310
311 auto mut_op0 = [&](const Def* def) -> std::ostream& {
312 if (auto sig = def->isa<Sigma>()) return print(os, ", {}", sig->num_ops());
313 if (auto arr = def->isa<Arr>()) return print(os, ", {}", arr->shape());
314 if (auto pack = def->isa<Pack>()) return print(os, ", {}", pack->shape());
315 if (auto pi = def->isa<Pi>()) return print(os, ", {}", pi->dom());
316 fe::unreachable();
317 };
318
319 if (!mut->is_set()) {
320 tab.print(os, "{}: {} = {{ <unset> }};", id(mut), mut->type());
321 return;
322 }
323
324 tab.print(os, "{} {}{}: {}", mut_prefix(mut), external(mut), id(mut), mut->type());
325 mut_op0(mut);
326 if (mut->var()) { // TODO rewrite with dedicated methods
327 if (auto e = mut->num_vars(); e != 1) {
328 print(os, "{, }", Elem(mut->vars(), [&](auto def) {
329 if (def)
330 os << def->unique_name();
331 else
332 os << "<TODO>";
333 }));
334 } else {
335 print(os, ", @{}", mut->var()->unique_name());
336 }
337 }
338 tab.println(os, " = {{");
339 ++tab;
340 if (dep) recurse(dep->mut2node(mut));
341 recurse(mut);
342 tab.print(os, "{, }\n", mut->ops());
343 --tab;
344 tab.print(os, "}};\n");
345}
346
347void Dumper::dump(Lam* lam) {
348 // TODO filter
349 auto ptrn = [&](auto&) { dump_ptrn(lam->var(), lam->type()->dom()); };
350
351 if (Lam::isa_cn(lam))
352 tab.println(os, "con {}{} {}@({}) = {{", external(lam), id(lam), ptrn, lam->filter());
353 else
354 tab.println(os, "lam {}{} {}: {} = {{", external(lam), id(lam), ptrn, lam->type()->codom());
355
356 ++tab;
357 if (lam->is_set()) {
358 if (dep) recurse(dep->mut2node(lam));
359 recurse(lam->filter());
360 recurse(lam->body(), true);
361 if (lam->body()->isa_mut())
362 tab.print(os, "{}\n", lam->body());
363 else
364 tab.print(os, "{}\n", Inline(lam->body()));
365 } else {
366 tab.print(os, " <unset>\n");
367 }
368 --tab;
369 tab.print(os, "}};\n");
370}
371
372void Dumper::dump_let(const Def* def) {
373 tab.print(os, "let {}: {} = {};\n", def->unique_name(), def->type(), Inline(def, 0));
374}
375
376void Dumper::dump_ptrn(const Def* def, const Def* type) {
377 if (!def) {
378 os << type;
379 } else {
380 auto projs = def->tprojs();
381 if (projs.size() == 1 || std::ranges::all_of(projs, [](auto def) { return !def; })) {
382 print(os, "{}: {}", def->unique_name(), type);
383 } else {
384 size_t i = 0;
385 print(os, "{}::[{, }]", def->unique_name(),
386 Elem(projs, [&](auto proj) { dump_ptrn(proj, type->proj(i++)); }));
387 }
388 }
389}
390
391void Dumper::recurse(const DepNode* node) {
392 for (auto child : node->children())
393 if (auto mut = isa_decl(child->mut())) dump(mut);
394}
395
396void Dumper::recurse(const Def* def, bool first /*= false*/) {
397 if (auto mut = isa_decl(def)) {
398 if (!dep) muts.push(mut);
399 return;
400 }
401
402 if (!defs.emplace(def).second) return;
403
404 for (auto op : def->partial_ops()) {
405 if (!op) continue;
406 recurse(op);
407 }
408
409 if (!first && !Inline(def)) dump_let(def);
410}
411
412} // namespace
413
414/*
415 * Def
416 */
417
418std::ostream& operator<<(std::ostream& os, Ref ref) { return os << *ref; }
419
420/// This will stream @p def as an operand.
421/// This is usually `id(def)` unless it can be displayed Inline.
422std::ostream& operator<<(std::ostream& os, const Def* def) {
423 if (def == nullptr) return os << "<nullptr>";
424 if (Inline(def)) {
425 auto freezer = World::Freezer(def->world());
426 return os << Inline(def);
427 }
428 return os << id(def);
429}
430
431std::ostream& Def::stream(std::ostream& os, int max) const {
432 auto freezer = World::Freezer(world());
433 auto dumper = Dumper(os);
434
435 if (max == 0) {
436 os << this << std::endl;
437 } else if (auto mut = isa_decl(this)) {
438 dumper.muts.push(mut);
439 } else {
440 dumper.recurse(this);
441 dumper.tab.print(os, "{}\n", Inline(this));
442 --max;
443 }
444
445 for (; !dumper.muts.empty() && max > 0; --max) dumper.dump(dumper.muts.pop());
446
447 return os;
448}
449
450void Def::dump() const { std::cout << this << std::endl; }
451void Def::dump(int max) const { stream(std::cout, max) << std::endl; }
452
453void Def::write(int max, const char* file) const {
454 auto ofs = std::ofstream(file);
455 stream(ofs, max);
456}
457
458void Def::write(int max) const {
459 auto file = id(this) + ".mim"s;
460 write(max, file.c_str());
461}
462
463/*
464 * World
465 */
466
467void World::dump(std::ostream& os) {
468 auto freezer = World::Freezer(*this);
469 auto old_gid = curr_gid();
470
471 if (flags().dump_recursive) {
472 auto dumper = Dumper(os);
473 for (const auto& [_, mut] : externals()) dumper.muts.push(mut);
474 while (!dumper.muts.empty()) dumper.dump(dumper.muts.pop());
475 } else {
476 auto dep = DepTree(*this);
477 auto dumper = Dumper(os, &dep);
478
479 for (auto [_, name] : driver().imports())
480 print(os, ".{} {};\n", driver().is_loaded(name) ? "mim/plugin" : "import", name);
481 dumper.recurse(dep.root());
482 }
483
484 assertf(old_gid == curr_gid(), "new nodes created during dump. old_gid: {}; curr_gid: {}", old_gid, curr_gid());
485}
486
487void World::dump() { dump(std::cout); }
488
490 if (log().level() == Log::Level::Debug) dump(log().ostream());
491}
492
493void World::write(const char* file) {
494 auto ofs = std::ofstream(file);
495 dump(ofs);
496}
497
499 auto file = name().str() + ".mim"s;
500 write(file.c_str());
501}
502
503} // namespace mim
Base class for all Defs.
Definition def.h:223
void dump() const
Definition dump.cpp:450
World & world() const
Definition def.cpp:415
void write(int max) const
Definition dump.cpp:458
std::ostream & stream(std::ostream &, int max) const
Definition dump.cpp:431
const DepNode * mut2node(Def *mut) const
Definition deptree.h:46
static Ref size(Ref def)
Checks if def is a Idx s and returns s or nullptr otherwise.
Definition def.cpp:556
static std::optional< T > isa(Ref def)
Definition def.h:763
static const Pi * isa_cn(Ref d)
Is this a continuation - i.e. is the Pi::codom mim::Bottom?
Definition lam.h:50
Helper class to retrieve Infer::arg if present.
Definition def.h:86
std::ostream & println(std::ostream &os, const char *s, Args &&... args)
Same as Tab::print but appends a std::endl to os.
Definition print.h:220
std::ostream & print(std::ostream &os, const char *s, Args &&... args)
Definition print.h:211
void dump()
Dump to std::cout.
Definition dump.cpp:487
void write()
Same above but file name defaults to World::name.
Definition dump.cpp:498
void debug_dump()
Dump in Debug build if World::log::level is Log::Level::Debug.
Definition dump.cpp:489
#define MY_PREC(m)
Definition dump.cpp:81
Ref op(trait o, Ref type)
Definition core.h:33
Definition cfg.h:11
std::ostream & print(std::ostream &os, const char *s)
Base case.
Definition print.cpp:5
TBound< true > Join
Definition lattice.h:180
TExt< true > Top
Definition lattice.h:178
GIDSet< const Def * > DefSet
Definition def.h:59
TExt< false > Bot
Definition lattice.h:177
std::ostream & operator<<(std::ostream &, const CFNode *)
Definition cfg.cpp:22
#define assertf(condition,...)
Definition print.h:172
Use to World::freeze and automatically unfreeze at the end of scope.
Definition world.h:140
#define CODE(t, str)
Definition tok.h:53