MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <cstdlib>
2
3#include <string>
4
5#include <fe/cli.h>
6#include <fe/sys.h>
7#include <fe/term.h>
8
9#include <mim/config.h>
10#include <mim/driver.h>
11#include <mim/flags.h>
12#include <mim/phase.h>
13#include <mim/plugin.h>
14#include <mim/sexpr.h>
15
16#include <mim/ast/parser.h>
17#include <mim/phase/optimize.h>
18
19using namespace mim;
20using namespace std::literals;
21
22namespace {
23
24enum Emit { AST, Dot, H, PY, Md, Mim, NestDot, SExpr, Slotted, Profile, Num_Emits };
25
26/// Everything the command line configures that neither Flags nor fe::CodeDiag already holds.
27struct Opts {
28 std::string input;
29 std::vector<std::string> plugins, search_paths, import_paths, prefix_paths, plugin_args;
30 std::array<Out, Num_Emits> outs;
31 DotConfig dot;
32 bool sexpr_include_types = false;
33};
34
35void emit_help(fe::Cli& cli, Driver& driver, const std::vector<std::string>& plugins, bool md) {
36 for (auto&& plugin : plugins) // a plugin declares its `-X` arguments in its shared library
37 driver.load(plugin);
38
39 if (!driver.known_args().empty()) {
40 cli.section("Plugin Arguments");
41
42 for (const auto& [plugin, args] : driver.known_args()) {
43 auto rows = fe::Cli::Rows();
44 for (const auto& arg : args)
45 rows.emplace_back(arg.syntax, arg.descr);
46 // The Markdown gets an anchor, so that a plugin's own page can link to its table.
47 auto title = md ? std::format("{0} {{#xarg_{0}}}", plugin) : plugin;
48 cli.section(std::move(title), "Argument", std::move(rows));
49 }
50 }
51 if (!driver.known_envs().empty()) {
52 cli.section("Plugin Environment Variables");
53
54 for (const auto& [plugin, envs] : driver.known_envs()) {
55 auto rows = fe::Cli::Rows();
56 for (const auto& env : envs)
57 rows.emplace_back(env.name, env.descr);
58 // The Markdown gets an anchor, so that a plugin's own page can link to its table.
59 auto title = md ? std::format("{0} {{#env_{0}}}", plugin) : std::string(plugin);
60 cli.section(std::move(title), "Variable", std::move(rows));
61 }
62 }
63
64 if (md)
65 cli.markdown(std::cout);
66 else
67 std::cout << cli;
68}
69
70void emit_profile(Driver& driver, std::ostream& os) {
71 switch (driver.flags().profile) {
72 case Flags::Profile::Summary: driver.profiler().summary(os); break;
73 case Flags::Profile::Tree: driver.profiler().tree(os); break;
74 case Flags::Profile::Trace: driver.profiler().chrome_trace(os); break;
75 case Flags::Profile::None: break;
76 }
77}
78
79/// Parses `Opts::input` into @p driver's World, optimizes it, and emits whatever `--output-*` asked for.
80int compile(Driver& driver, Opts& opts) {
81 auto& world = driver.world();
82 auto& outs = opts.outs;
83
84 try {
85 auto name = fs::path(opts.input).filename().replace_extension().string();
86 world.set(name);
87
88 auto ast = ast::AST(world);
89 auto parser = ast::Parser(ast);
90 auto file = parser.import_main(opts.input, opts.plugins, outs[Md].os());
91
92 if (!file) {
93 ast.error().ack(); // prefer the parser's own diagnostic, if it recorded one
94 fe::throwf("could not read file `{}`", opts.input);
95 }
96
97 if (auto s = outs[AST].os()) {
98 auto tab = fe::Tab::spaces();
99 file->stream(tab, *s);
100 }
101
102 if (auto h = outs[H].os(), py = outs[PY].os(); h || py) {
103 file->bind(ast);
104 ast.error().ack();
105 auto plugin = world.sym(name);
106 if (h) ast.bootstrap(plugin, *h);
107 if (py) ast.bootstrap_py(plugin, *py);
108 return EXIT_SUCCESS;
109 }
110
111 file->compile(ast);
112 optimize(world);
113
114 auto types = opts.sexpr_include_types;
115 if (auto s = outs[Dot].os()) world.dot(*s, opts.dot);
116 if (auto s = outs[Mim].os()) world.dump(*s);
117 if (auto s = outs[NestDot].os()) mim::Nest(world).dot(*s);
118 if (auto s = outs[SExpr].os()) (types ? sexpr::emit_typed : sexpr::emit)(world, *s);
119 if (auto s = outs[Slotted].os()) (types ? sexpr::emit_slotted_typed : sexpr::emit_slotted)(world, *s);
120 if (auto s = outs[Profile].os()) emit_profile(driver, *s);
121 } catch (const Error::Bail& e) {
122 std::cerr << e;
123 return EXIT_FAILURE;
124 }
125
126 return EXIT_SUCCESS;
127}
128
129} // namespace
130
131int main(int argc, char** argv) {
132 fe::term::resolve_mode(); // colors in std::format-ed output depend on Auto being resolved up front
133 Driver driver; // outlives the handlers below: an Error's Locs point into its SrcMap
134
135 try {
136 bool show_help = false;
137 bool show_help_md = false;
138 bool show_version = false;
139 bool list_search_paths = false;
140 int verbose = 0;
141 Opts opts;
142 auto& flags = driver.flags();
143 auto& diag = driver.diag();
144 auto inc_verbose = [&](bool) { ++verbose; };
145#ifdef MIM_ENABLE_CHECKS
146 std::vector<uint32_t> breakpoints, watchpoints;
147#endif
148
149 auto loc_style = [&](const std::string& t) -> std::string {
150 // clang-format off
151 if (t == "full" ) diag.loc_style = fe::Loc::Style::Full;
152 else if (t == "rowcol") diag.loc_style = fe::Loc::Style::RowCol;
153 else if (t == "row" ) diag.loc_style = fe::Loc::Style::Row;
154 else if (t == "msvc" ) diag.loc_style = fe::Loc::Style::MSVC;
155 else return std::format("'{}' is not a location style", t);
156 // clang-format on
157 return {};
158 };
159
160 auto profile = [&](const std::string& t) -> std::string {
161 // clang-format off
162 if (t == "summary") flags.profile = Flags::Profile::Summary;
163 else if (t == "tree" ) flags.profile = Flags::Profile::Tree;
164 else if (t == "trace" ) flags.profile = Flags::Profile::Trace;
165 else return std::format("'{}' is not a profile mode", t);
166 // clang-format on
167 return {};
168 };
169
170 // clang-format off
171 auto cli = fe::Cli("mim", "MimIR is my Intermediate Representation.")
172 .arg(opts.input, "file", "Input file.")
173 .help(show_help)
174 .opt(show_help_md , "" , "" , "--help-md" , "Displays this help as Markdown and exits.")
175 .opt(show_version , "" , "-v", "--version" , "Displays version info and exits.")
176 .opt(list_search_paths , "" , "-l", "--list-search-paths" , "Lists the search paths in order and exits.")
177 .opt(opts.plugins , "plugin" , "-p", "--plugin" , "Dynamically loads a plugin.")
178 .opt(opts.search_paths , "path" , "-P", "--plugin-path" , "Path to search for plugins; also searched for imports.")
179 .opt(opts.import_paths , "path" , "-I", "--import-path" , "Path to search for imports.")
180 .opt(opts.prefix_paths , "path" , "-R", "--prefix-path" , "Install prefix/root to derive plugin, import, and runtime directories from.")
181 .opt(opts.plugin_args , "plugin:arg", "-X", "--plugin-arg" , "Passes an argument to a plugin/phase, e.g. `-X ll:o=output.ll`. Repeatable.")
182 .opt(flags.force_load , "" , "" , "--force-load" , "Loads plugins even on version mismatch.")
183 .opt(flags.bootstrap , "" , "" , "--bootstrap" , "Bootstrap mode: only read Mim AST, don't compile to MimIR.")
184 .opt(inc_verbose , "" , "-V", "--verbose" , "Raises the log level from error to warn, info, verbose, debug, trace; repeatable.").cardinality(0, 5)
185 .grp("Output")
186 .opt(flags.ascii , "" , "-a", "--ascii" , "Uses ASCII alternatives in output instead of UTF-8.")
187 .opt(opts.outs[AST].name() , "file" , "" , "--output-ast" , "Emits the AST of the input.")
188 .opt(opts.outs[Dot].name() , "file" , "" , "--output-dot" , "Emits the Mim program as a MimIR graph using Graphviz' DOT language.")
189 .opt(opts.outs[H].name() , "file" , "" , "--output-h" , "Emits a header file to be used to interface with a plugin in C++.")
190 .opt(opts.outs[Md].name() , "file" , "" , "--output-md" , "Emits the input formatted as Markdown.")
191 .opt(opts.outs[Mim].name() , "file" , "-o", "--output-mim" , "Emits the Mim program again.")
192 .opt(flags.dump_recursive , "" , "" , "--dump-recursive" , "Dumps the Mim program with a simple recursive algorithm; the result is not readable again but works for broken programs.")
193 .opt(opts.outs[NestDot].name() , "file" , "" , "--output-nest" , "Emits the program's nesting tree using Graphviz' DOT language.")
194 .opt(opts.outs[PY].name() , "file" , "" , "--output-py" , "Emits a Python enum to be used to interface with a plugin in Python.")
195 .opt(opts.outs[SExpr].name() , "file" , "" , "--output-sexpr" , "Emits the program as symbolic expression.")
196 .opt(opts.outs[Slotted].name() , "file" , "" , "--output-sexpr-slotted", "Emits the program as symbolic expression that follows the format required by slotted-egraphs.")
197 .opt(opts.sexpr_include_types , "" , "" , "--sexpr-include-types" , "Wraps each term of a symbolic expression in a type annotation; types themselves stay unwrapped.")
198 .grp("DOT Output")
199 .opt(opts.dot.all_annexes , "" , "" , "--dot-all-annexes" , "Emits all annexes in DOT output - even unused ones.")
200 .opt(opts.dot.default_filter , "" , "" , "--dot-default-filter" , "Always shows a lambda's filter in DOT output - even if it is the default one (`ff` for continuations, `tt` for direct-style functions).")
201 .opt(opts.dot.follow_types , "" , "" , "--dot-follow-types" , "Follows type dependencies in DOT output.")
202 .opt(opts.dot.inline_consts , "" , "" , "--dot-inline-consts" , "Wires up literals, axioms, etc. with normal edges in DOT output instead of detaching them into a separate row; useful for small graphs.")
203 .opt(opts.dot.show_hidden , "" , "" , "--dot-show-hidden" , "Renders otherwise-transparent detached edges in DOT output - back-edges from a Var to its binder, shared literals/axioms, and type edges - in a subtle gray.")
204 .grp("Diagnostics")
205 .opt(diag.gutter , "width" , "" , "--gutter" , "Width of a diagnostic's line-number column.")
206 .opt(loc_style , "style" , "" , "--loc-style" , "How a diagnostic spells out a source location: `full` (`path:row:col-row:col`), `rowcol` (`path:row:col`), `row` (`path:row`), or `msvc` (`path(row,col)`).")
207 .opt(diag.max_errors , "num" , "" , "--max-errors" , "Maximum number of errors to report before dropping the rest; 0 reports all of them.")
208 .opt(diag.max_rows , "num" , "" , "--max-rows" , "Maximum number of rows a diagnostic's snippet renders before eliding its middle; 0 elides nothing.")
209 .opt(diag.no_snippet , "" , "" , "--no-snippet" , "Does not render the offending source line and caret underneath a diagnostic.")
210 .opt(diag.werror , "" , "" , "--werror" , "Treats warnings as errors.")
211 .grp("Profiling")
212 .opt(opts.outs[Profile].name() , "file" , "" , "--output-profile" , "Where to write the profiling information; defaults to stdout and implies --profile trace, if no `<mode>` is given.")
213 .opt(profile , "mode" , "" , "--profile" , "Measures how long each phase takes; `<mode>` is `summary`, `tree`, or `trace` (`chrome://tracing` compatible).")
214 .grp("Optimization")
215 .opt(flags.aggressive_lam_spec , "" , "" , "--aggr-lam-spec" , "Overrides LamSpec behavior to follow recursive calls.")
216 .opt(flags.max_fp_iters , "num" , "" , "--max-fp-iters" , "Maximum number of fixed-point iterations before a phase errors out; guards against non-monotone analyses.")
217 .opt(flags.scalarize_threshold , "threshold" , "" , "--scalarize-threshold" , "MimIR will not scalarize tuples/packs/sigmas/arrays with a number of elements greater than or equal this threshold.")
218#ifdef MIM_ENABLE_CHECKS
219 .grp("Developer Options")
220 .opt(breakpoints , "gid" , "-b", "--break" , "Triggers a breakpoint when a node with this global id is created.")
221 .opt(flags.break_on_alpha , "" , "" , "--break-on-alpha" , "Triggers a breakpoint as soon as two expressions turn out not to be alpha-equivalent.")
222 .opt(flags.break_on_error , "" , "" , "--break-on-error" , "Triggers a breakpoint on an error log.")
223 .opt(flags.break_on_warn , "" , "" , "--break-on-warn" , "Triggers a breakpoint on a warning log.")
224 .opt(flags.reeval_breakpoints , "" , "" , "--reeval-breakpoints" , "Triggers a breakpoint even upon unifying a node that has already been built.")
225 .opt(flags.trace_gids , "" , "" , "--trace-gids" , "Outputs gids during `World::unify`/`insert`.")
226 .opt(watchpoints , "gid" , "-w", "--watch" , "Triggers a breakpoint when a node with this global id is set.")
227#endif
228 .section("Environment Variables", "Variable", {
229 {"MIM_PLUGIN_PATH", std::format("{}-separated list of plugin search paths, searched after those given via `-P`.", fe::sys::Path_Sep_Word)},
230 {"MIM_IMPORT_PATH", std::format("{}-separated list of import search paths, searched after those given via `-I`.", fe::sys::Path_Sep_Word)},
231 {"MIM_PREFIX_PATH", std::format("{}-separated list of install prefixes, searched after those given via `--prefix-path`.", fe::sys::Path_Sep_Word)},
232 {"NO_COLOR" , "Disables colored output if set to a non-empty value; wins over the two below."},
233 {"CLICOLOR_FORCE" , "Forces colored output if set to a non-empty value other than 0."},
234 {"CLICOLOR" , "Disables colored output if set to 0."},
235 })
236 .epilog(R"(Every output option accepts "-" to write to stdout.)");
237 // clang-format on
238
239 if (auto err = cli.parse(argc, argv)) throw std::invalid_argument(*err);
240
241 // Resolved here and not in the handlers, so that the order of the two profiling options does not matter.
242 auto& profile_file = opts.outs[Profile].name();
243 if (flags.profile == Flags::Profile::None && !profile_file.empty()) flags.profile = Flags::Profile::Trace;
244 if (flags.profile != Flags::Profile::None && profile_file.empty()) profile_file = "-";
245
246 for (auto&& path : opts.search_paths)
247 driver.add_plugin_path(path);
248
249 for (auto&& path : opts.import_paths)
250 driver.add_import_path(path);
251
252 for (auto&& path : opts.prefix_paths)
253 driver.add_prefix_path(path);
254
255 if (show_help || show_help_md) {
256 emit_help(cli, driver, opts.plugins, show_help_md);
257 return EXIT_SUCCESS;
258 }
259
260 if (show_version) {
261 std::cout << "mim " << driver.version() << std::endl;
262 return EXIT_SUCCESS;
263 }
264
265 for (auto&& pa : opts.plugin_args) {
266 auto pos = pa.find(':');
267 if (pos == std::string::npos)
268 throw std::invalid_argument("error: --plugin-arg expects <plugin>:<arg>, got '" + pa + "'");
269 driver.add_arg(std::string_view(pa).substr(0, pos), pa.substr(pos + 1));
270 }
271
272 if (list_search_paths) {
273 auto list = [](std::string_view kind, const fe::Vector<fs::path>& paths) {
274 std::cout << kind << ':' << std::endl;
275 for (auto&& path : paths | std::views::drop(1)) // skip first empty path
276 std::cout << " " << path << std::endl;
277 };
278 list("plugins", driver.plugin_paths());
279 list("imports", driver.import_paths());
280 list("runtimes", driver.rt_paths());
281 return EXIT_SUCCESS;
282 }
283
284 driver.log().set(&std::cerr).set((fe::Log::Level)verbose);
285#ifdef MIM_ENABLE_CHECKS
286 driver.log().break_on_error = flags.break_on_error;
287 driver.log().break_on_warn = flags.break_on_warn;
288 for (auto b : breakpoints)
289 driver.world().breakpoint(b);
290 for (auto w : watchpoints)
291 driver.world().watchpoint(w);
292#endif
293
294 if (opts.input.empty()) throw std::invalid_argument("error: no input given");
295
296 return compile(driver, opts);
297 } catch (const std::exception& e) {
298 std::println(std::cerr, "{}", e.what());
299 return EXIT_FAILURE;
300 } catch (...) {
301 std::println(std::cerr, "error: unknown exception");
302 return EXIT_FAILURE;
303 }
304}
Some "global" variables needed all over the place.
Definition driver.h:63
const auto & known_envs() const
The PluginEnvs each loaded Plugin declares, in load order; only for listing them, see PluginEnv.
Definition driver.h:209
void add_prefix_path(fs::path path)
Definition driver.h:126
void add_import_path(fs::path path)
Definition driver.h:125
void load(std::string_view name)
Definition driver.cpp:126
const Version & version() const
MimIR Version.
Definition driver.h:83
const auto & known_args() const
The PluginArgs each loaded Plugin declares, in load order; only for listing them, see PluginArg.
Definition driver.h:206
World & world()
Definition driver.h:82
fe::Vector< fs::path > import_paths() const
Where ast::Parser looks for <name>.mim; plugin directories are included, as a plugin ships both halve...
Definition driver.cpp:102
void add_arg(std::string_view plugin, std::string arg)
Definition driver.h:201
fe::Vector< fs::path > rt_paths() const
Where a backend looks for its runtime modules.
Definition driver.cpp:116
Flags & flags()
Definition driver.h:76
void add_plugin_path(fs::path path)
Definition driver.h:124
fe::Vector< fs::path > plugin_paths() const
Where Driver::load looks for libmim_<name>.
Definition driver.cpp:92
fe::Profiler & profiler()
Definition driver.h:80
fe::Log & log()
Definition driver.h:78
Builds a nesting tree for all mutables/binders.
Definition nest.h:31
void dot(std::ostream &os) const
Definition dot.cpp:247
void watchpoint(u32 gid)
Trigger breakpoint in your debugger when Def::setting a Def with this gid.
Definition world.cpp:776
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
Definition world.cpp:775
Owns the arena all AST nodes live in as well as the AnnexInfos of all plugins.
Definition ast.h:99
Parses Mim code as AST.
Definition parser.h:30
int main(int argc, char **argv)
Definition main.cpp:131
Definition Mim.cmake:1
Definition ast.h:16
void emit_slotted(World &, std::ostream &)
Definition sexpr.cpp:953
void emit_typed(World &, std::ostream &)
Definition sexpr.cpp:948
void emit(World &, std::ostream &)
Definition sexpr.cpp:943
void emit_slotted_typed(World &, std::ostream &)
Definition sexpr.cpp:958
Definition ast.h:16
bool follow_types
Follow Def::type() dependencies.
Definition def.h:232
bool inline_consts
Wire up literals, axioms, etc. with normal edges instead of detaching them.
Definition def.h:233
void optimize(World &)
Runs _compile or _default_compile, if available (in this order).
Definition optimize.cpp:8
bool all_annexes
Include all annexes - even if unused (World::dot only).
Definition def.h:231
bool show_hidden
Render otherwise-transparent detached edges (Var→binder back-edges, shared literals/axioms,...
Definition def.h:235
bool default_filter
Show Lam::filter() even if it has its default value.
Definition def.h:234
@ Summary
Flat table aggregated by Phase name.
Definition flags.h:15
@ Tree
Indented tree preserving the order in which Phasees ran.
Definition flags.h:16
@ None
No profiling.
Definition flags.h:14
@ Trace
chrome://tracing compatible output.
Definition flags.h:17
Profile profile
Definition flags.h:27