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
15#include <mim/ast/parser.h>
16#include <mim/phase/optimize.h>
17
18using namespace mim;
19using namespace std::literals;
20
21namespace {
22
23enum Emit { AST, Dot, H, PY, Md, Mim, NestDot, Profile, Num_Emits };
24
25/// Everything the command line configures that neither Flags nor fe::CodeDiag already holds.
26struct Opts {
27 std::string input;
28 std::vector<std::string> plugins, search_paths, import_paths, prefix_paths, plugin_args;
29 std::array<Out, Num_Emits> outs;
30 DotConfig dot;
31 bool no_opt = false;
32};
33
34void emit_help(fe::Cli& cli, Driver& driver, const std::vector<std::string>& plugins, bool md) {
35 for (auto&& plugin : plugins) // a plugin declares its `-X` arguments in its shared library
36 driver.load(plugin);
37
38 if (!driver.known_args().empty()) {
39 cli.section(md ? "Plugin Arguments {#xargs}" : "Plugin Arguments");
40
41 for (const auto& [plugin, args] : driver.known_args()) {
42 auto rows = fe::Cli::Rows();
43 for (const auto& arg : args)
44 rows.emplace_back(arg.syntax, arg.descr);
45 // The Markdown links back to the plugin's page and carries the anchor that page links to.
46 auto title = md ? std::format("[{0}](@ref {0}) {{#xarg_{0}}}", plugin) : plugin;
47 cli.section(std::move(title), "Argument", std::move(rows));
48 }
49 }
50 if (!driver.known_envs().empty()) {
51 cli.section(md ? "Plugin Environment Variables {#envs}" : "Plugin Environment Variables");
52
53 for (const auto& [plugin, envs] : driver.known_envs()) {
54 auto rows = fe::Cli::Rows();
55 for (const auto& env : envs)
56 rows.emplace_back(env.name, env.descr);
57 // Ditto.
58 auto title = md ? std::format("[{0}](@ref {0}) {{#env_{0}}}", plugin) : std::string(plugin);
59 cli.section(std::move(title), "Variable", std::move(rows));
60 }
61 }
62
63 if (md)
64 cli.markdown(std::cout);
65 else
66 std::cout << cli;
67}
68
69void emit_profile(Driver& driver, std::ostream& os) {
70 switch (driver.flags().profile) {
71 case Flags::Profile::Summary: driver.profiler().summary(os); break;
72 case Flags::Profile::Tree: driver.profiler().tree(os); break;
73 case Flags::Profile::Trace: driver.profiler().chrome_trace(os); break;
74 case Flags::Profile::None: break;
75 }
76}
77
78/// Parses `Opts::input` into @p driver's World, optimizes it, and emits whatever `--output-*` asked for.
79int compile(Driver& driver, Opts& opts) {
80 auto& world = driver.world();
81 auto& outs = opts.outs;
82
83 try {
84 auto name = fs::path(opts.input).filename().replace_extension().string();
85 world.set(name);
86
87 auto ast = ast::AST(world);
88 auto parser = ast::Parser(ast);
89 auto file = parser.import_main(opts.input, opts.plugins, outs[Md].os());
90
91 if (!file) {
92 ast.error().ack(); // prefer the parser's own diagnostic, if it recorded one
93 fe::throwf("could not read file `{}`", opts.input);
94 }
95
96 if (auto s = outs[AST].os()) {
97 auto tab = fe::Tab::spaces();
98 file->stream(tab, *s);
99
100 // Md is emitted while parsing, so nothing else needs a World; binding still catches scoping errors.
101 auto only_parse = opts.plugin_args.empty()
102 && std::ranges::none_of(std::views::iota(0, int(Num_Emits)),
103 [&](int i) { return i != AST && i != Md && outs[i].os(); });
104 if (only_parse) {
105 file->bind(ast);
106 ast.error().ack();
107 return EXIT_SUCCESS;
108 }
109 }
110
111 if (auto h = outs[H].os(), py = outs[PY].os(); h || py) {
112 file->bind(ast);
113 ast.error().ack();
114 auto plugin = world.sym(name);
115 if (h) ast.bootstrap(plugin, *h);
116 if (py) ast.bootstrap_py(plugin, *py);
117 return EXIT_SUCCESS;
118 }
119
120 file->compile(ast);
121 std::exception_ptr opt_error;
122 if (opts.no_opt)
123 Cleanup(world).run(); // resolves the Hole%s elaboration solved, as optimize would first
124 else
125 try {
126 optimize(world);
127 } catch (...) {
128 opt_error = std::current_exception(); // still emit the world the failing phase saw
129 }
130
131 if (auto s = outs[Dot].os()) world.dot(*s, opts.dot);
132 if (auto s = outs[Mim].os()) world.dump(*s);
133 if (auto s = outs[NestDot].os()) mim::Nest(world).dot(*s, opts.dot);
134 if (auto s = outs[Profile].os()) emit_profile(driver, *s);
135 if (opt_error) std::rethrow_exception(opt_error);
136 } catch (const Error::Bail& e) {
137 std::cerr << e;
138 return EXIT_FAILURE;
139 }
140
141 return EXIT_SUCCESS;
142}
143
144} // namespace
145
146int main(int argc, char** argv) {
147 fe::term::resolve_mode(); // colors in std::format-ed output depend on Auto being resolved up front
148 Driver driver; // outlives the handlers below: an Error's Locs point into its SrcMap
149
150 try {
151 bool show_help = false;
152 bool show_help_md = false;
153 bool show_version = false;
154 bool list_search_paths = false;
155 int verbose = 0;
156 Opts opts;
157 auto& flags = driver.flags();
158 auto& diag = driver.diag();
159 auto inc_verbose = [&](bool) { ++verbose; };
160#ifdef MIM_ENABLE_CHECKS
161 std::vector<uint32_t> breakpoints, watchpoints;
162#endif
163
164 auto loc_style = [&](const std::string& t) -> std::string {
165 // clang-format off
166 if (t == "full" ) diag.loc_style = fe::Loc::Style::Full;
167 else if (t == "rowcol") diag.loc_style = fe::Loc::Style::RowCol;
168 else if (t == "row" ) diag.loc_style = fe::Loc::Style::Row;
169 else if (t == "msvc" ) diag.loc_style = fe::Loc::Style::MSVC;
170 else return std::format("'{}' is not a location style", t);
171 // clang-format on
172 return {};
173 };
174
175 auto profile = [&](const std::string& t) -> std::string {
176 // clang-format off
177 if (t == "summary") flags.profile = Flags::Profile::Summary;
178 else if (t == "tree" ) flags.profile = Flags::Profile::Tree;
179 else if (t == "trace" ) flags.profile = Flags::Profile::Trace;
180 else return std::format("'{}' is not a profile mode", t);
181 // clang-format on
182 return {};
183 };
184
185 // clang-format off
186 auto cli = fe::Cli("mim", "MimIR is my Intermediate Representation.")
187 .arg(opts.input, "file", "Input file.")
188 .help(show_help)
189 .opt(show_help_md , "" , "" , "--help-md" , "Displays this help as Markdown and exits.")
190 .opt(show_version , "" , "-v", "--version" , "Displays version info and exits.")
191 .opt(list_search_paths , "" , "-l", "--list-search-paths" , "Lists the search paths in order and exits.")
192 .opt(opts.plugins , "plugin" , "-p", "--plugin" , "Dynamically loads a plugin; `foo/bar` finds `libmim_bar` in each search path's `foo`.")
193 .opt(opts.search_paths , "path" , "-P", "--plugin-path" , "Path to search for plugins; also searched for imports.")
194 .opt(opts.import_paths , "path" , "-I", "--import-path" , "Path to search for imports.")
195 .opt(opts.prefix_paths , "path" , "-R", "--prefix-path" , "Install prefix/root to derive plugin, import, and runtime directories from.")
196 .opt(opts.plugin_args , "plugin:arg", "-X", "--plugin-arg" , "Passes an argument to a plugin/phase, e.g. `-X ll:o=output.ll`. Repeatable.")
197 .opt(flags.force_load , "" , "" , "--force-load" , "Loads plugins even on version mismatch.")
198 .opt(flags.bootstrap , "" , "" , "--bootstrap" , "Bootstrap mode: only read Mim AST, don't compile to MimIR.")
199 .opt(inc_verbose , "" , "-V", "--verbose" , "Raises the log level from error to warn, info, verbose, debug, trace; repeatable.").cardinality(0, 5)
200 .grp("Output")
201 .opt(flags.ascii , "" , "-a", "--ascii" , "Uses ASCII alternatives in output instead of UTF-8.")
202 .opt(opts.outs[AST].name() , "file" , "" , "--output-ast" , "Emits the AST of the input.")
203 .opt(opts.outs[Dot].name() , "file" , "" , "--output-dot" , "Emits the Mim program as a MimIR graph using Graphviz' DOT language.")
204 .opt(opts.outs[H].name() , "file" , "" , "--output-h" , "Emits a header file to be used to interface with a plugin in C++.")
205 .opt(opts.outs[Md].name() , "file" , "" , "--output-md" , "Emits the input formatted as Markdown.")
206 .opt(opts.outs[Mim].name() , "file" , "-o", "--output-mim" , "Emits the Mim program again.")
207 .opt(opts.outs[NestDot].name() , "file" , "" , "--output-nest" , "Emits the program's nesting tree using Graphviz' DOT language.")
208 .opt(opts.outs[PY].name() , "file" , "" , "--output-py" , "Emits a Python enum to be used to interface with a plugin in Python.")
209 .grp("DOT Output")
210 .opt(opts.dot.all_annexes , "" , "" , "--dot-all-annexes" , "Emits all annexes in DOT output - even unused ones.")
211 .opt(opts.dot.dark , "" , "" , "--dot-dark" , "Drops the white background of the DOT output and lightens its edges, so that it embeds into a dark backdrop.")
212 .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).")
213 .opt(opts.dot.follow_types , "" , "" , "--dot-follow-types" , "Follows type dependencies in DOT output.")
214 .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.")
215 .opt(opts.dot.lean_labels , "" , "" , "--dot-lean-labels" , "Labels a DOT node `<node_name> <unique_name>` instead of the HTML table; this drops the per-op ports, so an edge no longer docks under the op it stands for.")
216 .opt(opts.dot.no_tooltip , "" , "" , "--dot-no-tooltip" , "Omits the per-node tooltip from DOT output; it accounts for roughly two fifths of the file.")
217 .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.")
218 .grp("Mim Output")
219 .opt(flags.mim_local , "" , "" , "--mim-local" , "Dumps each mutable as its own flat block without scheduling; the result does not read back but works for broken programs.")
220 .opt(flags.mim_typed_let , "" , "" , "--mim-typed-let" , "Ascribes the type of each `let`-bound name; it is inferable from the right-hand side and hence elided by default.")
221 .grp("Diagnostics")
222 .opt(diag.gutter , "width" , "" , "--gutter" , "Width of a diagnostic's line-number column.")
223 .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)`).")
224 .opt(diag.max_errors , "num" , "" , "--max-errors" , "Maximum number of errors to report before dropping the rest; 0 reports all of them.")
225 .opt(diag.max_rows , "num" , "" , "--max-rows" , "Maximum number of rows a diagnostic's snippet renders before eliding its middle; 0 elides nothing.")
226 .opt(diag.no_snippet , "" , "" , "--no-snippet" , "Does not render the offending source line and caret underneath a diagnostic.")
227 .opt(diag.werror , "" , "" , "--werror" , "Treats warnings as errors.")
228 .grp("Profiling")
229 .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.")
230 .opt(profile , "mode" , "" , "--profile" , "Measures how long each phase takes; `<mode>` is `summary`, `tree`, or `trace` (`chrome://tracing` compatible).")
231 .grp("Optimization")
232 .opt(flags.aggressive_lam_spec , "" , "" , "--aggr-lam-spec" , "Overrides LamSpec behavior to follow recursive calls.")
233 .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.")
234 .opt(opts.no_opt , "" , "" , "--no-opt" , "Elaborates the input but skips the optimization pipeline, so no backend runs; `--output-*` still works.")
235 .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.")
236#ifdef MIM_ENABLE_CHECKS
237 .grp("Developer Options")
238 .opt(breakpoints , "gid" , "-b", "--break" , "Triggers a breakpoint when a node with this global id is created.")
239 .opt(flags.break_on_alpha , "" , "" , "--break-on-alpha" , "Triggers a breakpoint as soon as two expressions turn out not to be alpha-equivalent.")
240 .opt(flags.break_on_error , "" , "" , "--break-on-error" , "Triggers a breakpoint on an error log.")
241 .opt(flags.break_on_warn , "" , "" , "--break-on-warn" , "Triggers a breakpoint on a warning log.")
242 .opt(flags.reeval_breakpoints , "" , "" , "--reeval-breakpoints" , "Triggers a breakpoint even upon unifying a node that has already been built.")
243 .opt(flags.trace_gids , "" , "" , "--trace-gids" , "Outputs gids during `World::unify`/`insert`.")
244 .opt(watchpoints , "gid" , "-w", "--watch" , "Triggers a breakpoint when a node with this global id is set.")
245#endif
246 .section("Environment Variables", "Variable", {
247 {"MIM_PLUGIN_PATH", std::format("{}-separated list of plugin search paths, searched after those given via `-P`.", fe::sys::Path_Sep_Word)},
248 {"MIM_IMPORT_PATH", std::format("{}-separated list of import search paths, searched after those given via `-I`.", fe::sys::Path_Sep_Word)},
249 {"MIM_PREFIX_PATH", std::format("{}-separated list of install prefixes, searched after those given via `--prefix-path`.", fe::sys::Path_Sep_Word)},
250 {"NO_COLOR" , "Disables colored output if set to a non-empty value; wins over the two below."},
251 {"CLICOLOR_FORCE" , "Forces colored output if set to a non-empty value other than 0."},
252 {"CLICOLOR" , "Disables colored output if set to 0."},
253 })
254 .epilog(R"(Every output option accepts "-" to write to stdout.)");
255 // clang-format on
256
257 if (auto err = cli.parse(argc, argv)) throw std::invalid_argument(*err);
258
259 // Resolved here and not in the handlers, so that the order of the two profiling options does not matter.
260 auto& profile_file = opts.outs[Profile].name();
261 if (flags.profile == Flags::Profile::None && !profile_file.empty()) flags.profile = Flags::Profile::Trace;
262 if (flags.profile != Flags::Profile::None && profile_file.empty()) profile_file = "-";
263
264 for (auto&& path : opts.search_paths)
265 driver.add_plugin_path(path);
266
267 for (auto&& path : opts.import_paths)
268 driver.add_import_path(path);
269
270 for (auto&& path : opts.prefix_paths)
271 driver.add_prefix_path(path);
272
273 if (show_help || show_help_md) {
274 emit_help(cli, driver, opts.plugins, show_help_md);
275 return EXIT_SUCCESS;
276 }
277
278 if (show_version) {
279 std::cout << "mim " << driver.version() << std::endl;
280 return EXIT_SUCCESS;
281 }
282
283 for (auto&& pa : opts.plugin_args) {
284 auto pos = pa.find(':');
285 if (pos == std::string::npos)
286 throw std::invalid_argument("error: --plugin-arg expects <plugin>:<arg>, got '" + pa + "'");
287 driver.add_arg(std::string_view(pa).substr(0, pos), pa.substr(pos + 1));
288 }
289
290 if (list_search_paths) {
291 auto list = [](std::string_view kind, const fe::Vector<fs::path>& paths) {
292 std::cout << kind << ':' << std::endl;
293 for (auto&& path : paths | std::views::drop(1)) // skip first empty path
294 std::cout << " " << path << std::endl;
295 };
296 list("plugins", driver.plugin_paths());
297 list("imports", driver.import_paths());
298 list("runtimes", driver.rt_paths());
299 return EXIT_SUCCESS;
300 }
301
302 driver.log().set(&std::cerr).set((fe::Log::Level)verbose);
303#ifdef MIM_ENABLE_CHECKS
304 driver.log().break_on_error = flags.break_on_error;
305 driver.log().break_on_warn = flags.break_on_warn;
306 for (auto b : breakpoints)
307 driver.world().breakpoint(b);
308 for (auto w : watchpoints)
309 driver.world().watchpoint(w);
310#endif
311
312 if (opts.input.empty()) throw std::invalid_argument("error: no input given");
313
314 return compile(driver, opts);
315 } catch (const std::exception& e) {
316 std::println(std::cerr, "{}", e.what());
317 return EXIT_FAILURE;
318 } catch (...) {
319 std::println(std::cerr, "error: unknown exception");
320 return EXIT_FAILURE;
321 }
322}
Cleanup(World &world)
Definition phase.h:606
Some "global" variables needed all over the place.
Definition driver.h:64
const auto & known_envs() const
The PluginEnvs each loaded Plugin declares, in load order; only for listing them, see PluginEnv.
Definition driver.h:218
void add_prefix_path(fs::path path)
Definition driver.h:127
void add_import_path(fs::path path)
Definition driver.h:126
void load(std::string_view name)
Definition driver.cpp:143
const Version & version() const
MimIR Version.
Definition driver.h:84
const auto & known_args() const
The PluginArgs each loaded Plugin declares, in load order; only for listing them, see PluginArg.
Definition driver.h:215
World & world()
Definition driver.h:83
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:110
void add_arg(std::string_view plugin, std::string arg)
Definition driver.h:210
fe::Vector< fs::path > rt_paths() const
Where a backend looks for its runtime modules.
Definition driver.cpp:124
Flags & flags()
Definition driver.h:77
void add_plugin_path(fs::path path)
Definition driver.h:125
fe::Vector< fs::path > plugin_paths() const
Where Driver::load looks for libmim_<name>.
Definition driver.cpp:100
fe::Profiler & profiler()
Definition driver.h:81
fe::Log & log()
Definition driver.h:79
Builds a nesting tree for all mutables/binders.
Definition nest.h:30
void dot(std::ostream &os, DotConfig cfg={}) const
Definition dot.cpp:296
void watchpoint(u32 gid)
Trigger breakpoint in your debugger when Def::setting a Def with this gid.
Definition world.cpp:1040
void breakpoint(u32 gid)
Trigger breakpoint in your debugger when creating a Def with this gid.
Definition world.cpp:1039
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:146
Definition Mim.cmake:1
Definition ast.h:16
Definition ast.h:16
bool follow_types
Follow Def::type() dependencies.
Definition def.h:268
bool inline_consts
Wire up literals, axioms, etc. with normal edges instead of detaching them.
Definition def.h:269
void optimize(World &)
Runs _compile or _default_compile, if available (in this order).
Definition optimize.cpp:8
bool no_tooltip
Omit the per-node tooltip; it is by far the bulkiest part of the output.
Definition def.h:274
bool all_annexes
Include all annexes - even if unused (World::dot only).
Definition def.h:267
bool dark
Drop the white background and lighten the edges for a dark backdrop.
Definition def.h:273
bool show_hidden
Render otherwise-transparent detached edges (Var→binder back-edges, shared literals/axioms,...
Definition def.h:271
bool lean_labels
Label a node <node_name> <unique_name> instead of the HTML table.
Definition def.h:275
bool default_filter
Show Lam::filter() even if it has its default value.
Definition def.h:270
@ 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:28