#! @file compiler.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the compiler, which lowers a checked program to a program of #! intermediate code: `main`, the code initializing the globals, and every #! function they reach, each lowered once something that runs names it. What #! each node means comes from the checker's tables: a function's nodes from #! its file's result table, and those of an instance of a generic from the #! instance's. What lowering does with each part of the language is split #! across the files of the `emitter` directory, as the checker's are. import std::containers; import sakura::analyzer; module sakura::compiler; #! How the code is lowered. pub struct lowering { pub var keep_locals: bool; #! Whether every named local is kept in a cell of its own, as debugging information wants. pub var describe: bool; #! Whether the variables of optimized code are noted for debugging information, which changes nothing of the code. pub var verify: bool; #! Whether each function is verified once lowered. pub var everything: bool; #! Whether every function that is no generic's template is lowered, not only those `main` reaches. pub var evaluating: bool; #! Whether the program evaluates constants while compiling, rather than running. pub var checks: bool; #! Whether what each reference and pointer reaches is checked as the program runs, as `run --checks` asks. pub var overflow_files: u32; #! How many files, from the first, are the program's own, whose integer arithmetic stops where it overflows, as `--checks` asks, or 0 for none. pub var level: u32; #! How much the code is optimized: 0 not at all, 1 within each function, 2 inlining too. pub var inline_limit: u32; #! The most instructions a function inlined may have, but for its constants, or 0 for `inline_limit`. pub var threads: u32; #! How many threads optimize and assemble functions at once, the compiler's own among them; 0 or 1 for it alone. } #! The compiler. pub struct lowerer { pub var checker: &mut checker; #! The checker, whose tables say what the program means. pub var program: program; #! What is made. var options: lowering; #! How the code is lowered. var layout_ids: dict; #! The layout of each type. var laying: u32; #! How many layouts are being made, one within another. var referents: vector; #! References and pointers laid out, each with the type it reaches, which is laid out once the outermost is. var signature_ids: dict; #! The signature of each function type. var function_ids: dict; #! The function of each declaration and instance, by `pair_key(decl, instance)`, the instance 0 for a declaration's own. var builtin_ids: dict; #! The function giving each built-in type each method, by `pair_key(type, name)`. var lambda_ids: dict; #! The function of each anonymous function, by `pair_key(table, node)`. var adapter_ids: dict; #! The adapter of each function named as a value of another function type, by `pair_key(table, node)`. var global_ids: dict; #! Where each global is among the globals, by its declaration. var instance_globals: dict; #! Where each instance of a variable of a generic type is among the globals, by the instance. var begun_globals: hashset; #! The globals whose initializers are lowered, or being lowered. var globals_lowered: bool; #! Whether `` is lowered, after which a global checking reaches has no value. var vtable_ids: dict; #! The vtable of each type for each trait's type, by `pair_key(type, trait)`. var retrait_ids: dict; #! The map of each conversion between traits' types, by `pair_key(from, to)`. var linked_ids: dict; #! The C function each foreign declaration calls. var texts: interner; #! Each text a datum holds. var text_data: vector; #! The datum holding each text, by its ID in `texts`. var dispatches: dict; #! The run of the methods of each trait in the order its vtables hold them, in `lists`. var lists: runs; #! The runs `dispatches` names. var queue: vector; #! The functions waiting to be lowered. var drained: u64; #! How many of `queue` were begun. var draining: u32; #! How many drains of `queue` are under way, one within another. pub var problems: vector; #! What lowering could not lower, which a program the checker passes never has. var summaries: dict; #! What each function does with what it is given, by `pair_key(decl, instance)`, once found for good. var pending: vector; #! The functions whose summaries are being found, in the order they were reached. var pending_ids: dict; #! The place of each in `pending`, by its key. var reader_of: vector; #! Of each link of a pending function's readers, the reader, by its place. var reader_next: vector; #! Of each link, one more than the next link of the same function, or 0. var read_pairs: hashset; #! The pending functions each reader read, by `pair_key(read, reader)`. var scanning: u32; #! The pending function whose scan is being made, or `no_scan`. pub var dispatch: u32; #! The function safe points call, `system::dispatch`, or `no_function` where the program handles no signal. pub var evaluations: vector; #! Of a program evaluating constants, what it evaluates. pub var evaluation_ids: dict; #! The evaluation of each constant, condition, or text, by its key. pub var evaluated: outcomes; #! What evaluating worked out, which the program holds as data. var constant_data: dict; #! The datum holding each constant evaluated, by its key. } #! Provides read only access to how much the code is optimized: 0 not at all, #! 1 within each function, 2 inlining too. #! @param this The compiler. #! @returns How much. pub val lowerer::level: u32 { get => this.options.level; } #! Makes a compiler of a program the checker has checked. #! @param checker The checker. #! @param options How the code is lowered. #! @returns The compiler. pub def lowerer::new(checker: &mut checker, options: lowering): lowerer { return lowerer { checker = checker, program = program::new(), options = options, layout_ids = dict::::new(), referents = vector::::new(), signature_ids = dict::::new(), function_ids = dict::::new(), builtin_ids = dict::::new(), lambda_ids = dict::::new(), adapter_ids = dict::::new(), global_ids = dict::::new(), instance_globals = dict::::new(), begun_globals = hashset::::new(), vtable_ids = dict::::new(), retrait_ids = dict::::new(), linked_ids = dict::::new(), texts = interner::::new(), text_data = vector::::new(), dispatches = dict::::new(), lists = runs::::new(), queue = vector::::new(), problems = vector::::new(), summaries = dict::::new(), pending = vector::::new(), pending_ids = dict::::new(), reader_of = vector::::new(), reader_next = vector::::new(), read_pairs = hashset::::new(), scanning = no_scan, dispatch = no_function, evaluations = vector::::new(), evaluation_ids = dict::::new(), evaluated = outcomes::new(), constant_data = dict::::new() }; } #! Lowers the program: the code initializing the globals, `main`, and every #! function they reach, then fills the vtables' maps between traits. #! @param this The compiler. #! @returns Whether everything was lowered, with nothing it could not lower. pub def lowerer::compile(&mut this): bool { val main := this.checker.modules.decl(0, word::main); if main != 0 && this.checker.decls.kinds.p[main] == dk::function { this.program.main = this.function_of(main, 0); } this.find_dispatch(); val point := mark_scratch(); this.program.init = this.lower_globals(); this.globals_lowered = true; release_scratch(point); if this.options.everything { this.want_everything(); } this.drain(); this.fill_retraits(); this.drain(); this.optimize(); return this.problems.length == 0; } #! Lowers the functions waiting, and those they reach in turn, each freeing #! the scratch memory it took as it ends. #! @param this The compiler. pub def lowerer::drain(&mut this): void { # Lowering a function may lower others within it, as evaluating while # checking does, which go on from where this goes, so the queue is let go of # only where the outermost ends. this.draining++; while this.drained < this.queue.length { val at := this.drained; this.drained++; val point := mark_scratch(); this.lower_function(this.queue[at]); release_scratch(point); } this.draining--; if this.draining == 0 { this.queue.clear(); this.drained = 0; } } #! Notes what lowering could not lower. #! @param this The compiler. #! @param file The file it is in. #! @param node Its node. #! @param what What it is, said in words. pub def lowerer::problem(&mut this, file: u32, node: u32, what: strview): void { val held := &this.checker.units[file].source; val at := held.lines.place_of(this.node_offset(file, node)); this.problems.append($"{held.path}:{at.line}:{at.column}: {what}"); } #! The type of a function, or of an instance of it. #! @param this The compiler. #! @param decl The function's declaration. #! @param instance The instance, or 0. #! @returns The type. pub def lowerer::type_of_function(&this, decl: u32, instance: u32): u32 { return instance != 0 ? this.checker.instances[instance].kind : this.checker.decls.types.p[decl]; } #! The table of nodes a function's body was checked in: its instance's, whose #! instances are checked where they were not yet, or its file's, where it is no #! instance or the instance's body was never checked. #! @param this The compiler. #! @param decl The function's declaration. #! @param instance The instance, or 0. #! @returns The table. pub def lowerer::body_table(&mut this, decl: u32, instance: u32): u32 { if instance != 0 { if this.checker.instances[instance].table == 0 { this.check_instance(instance); } val held: u32 = this.checker.instances[instance].table; return held if held != 0; } return this.checker.units[this.checker.decls.files.p[decl]].table; } #! The function a declaration is lowered to, given the instance of a generic it #! is, made and waiting to be lowered where it is new. #! @param this The compiler. #! @param decl The function's declaration. #! @param instance The instance of the checker it is, or 0. #! @returns The function's index. pub def lowerer::function_of(&mut this, decl: u32, instance: u32): u32 { val key := pair_key(decl, instance); if this.function_ids.get(&key) is some(got) { return got; } this.checker.resolve(decl); if instance == 0 { this.check_late(decl); } val kind := this.type_of_function(decl, instance); val index := this.add_function(this.function_name(decl, instance), this.signature_of(this.call_type(this.function_type(decl, kind)))); this.function_ids.set(key, index); val node: u32 = this.checker.decls.nodes.p[decl]; val file: u32 = this.checker.decls.files.p[decl]; this.program.functions[index].decl = decl; this.program.functions[index].instance = instance; this.program.functions[index].file = file; this.program.functions[index].offset = this.node_offset(file, node); this.program.functions[index].callback = this.checker.decls.has(decl, df::callback); this.program.functions[index].inline = this.checker.decls.has(decl, df::inline); val name: u32 = this.checker.decls.names.p[decl]; this.program.functions[index].stepping = this.checker.decls.has(decl, df::method) && (name == word::next || name == word::next_back || name == word::invoke); this.want(index); return index; } #! Checks a declaration lowering reaches that checking did not, as a library's #! function only the compiler calls, or a method only a vtable holds, with what #! it reaches in turn. Notes it makes are a problem, as is a global it reaches #! once `` is lowered, which would never be given its value. #! @param this The compiler. #! @param decl The declaration. pub def lowerer::check_late(&mut this, decl: u32): void { if !this.checker.decls.has(decl, df::checked) { val notes := this.checker.notes_made; val globals := this.checker.checked_globals; this.checker.reach(decl); this.checker.check_decl(decl); if this.checker.notes_made != notes { this.problems.append("Checking a function lowering asked for made notes."); } if this.globals_lowered && this.checker.checked_globals != globals { this.problems.append("Lowering reached a global nothing checked had reached, after the globals were given their values."); } } # What checking found an error in is never run while compiling. if this.options.evaluating && this.checker.decls.has(decl, df::flawed) { this.problems.append("A function it calls had an error checking it."); } } #! The function type a function is lowered with: its own, where a trait's #! default method takes `this` as a reference to the trait rather than to #! `self`, which only what implements it knows. A default compiled for each #! type takes its own type, as its type says. #! @param this The compiler. #! @param decl The function's declaration. #! @param kind Its function type, given its type arguments. #! @returns The function type. pub def lowerer::function_type(&mut this, decl: u32, kind: u32): u32 { val holder: u32 = this.checker.decls.owners.p[decl]; val owner: u32 = holder != 0 && this.checker.decls.kinds.p[holder] == dk::property ? this.checker.decls.owners.p[holder] : holder; return kind if owner == 0 || this.checker.decls.kinds.p[owner] != dk::trait_type || !this.checker.decls.has(decl, df::method) || this.checker.typed_default(decl); # An instance of a generic trait's default already takes the trait, given # its arguments. var params := this.checker.types.parts_of(kind); return kind if params.length == 0; val taken := this.checker.unalias(this.checker.types.first_of(params[0])); return kind if this.checker.named_kind(taken) == dk::trait_type; val writes := this.checker.decls.has(decl, df::mut_this); params[0] = this.checker.types.reference(this.checker.decls.types.p[owner], writes); return this.checker.types.function(params.span, this.checker.types.first_of(kind), this.checker.types.second_of(kind) != 0); } #! Adds a function of the program, lowered later. #! @param this The compiler. #! @param name Its name, as a trace writes it. #! @param signature How it is called. #! @returns Its index. pub def lowerer::add_function(&mut this, name: string, signature: u32): u32 { this.program.functions.append(function { name = move(&mut name), signature = signature, body = code::new(), compiled = bytecode::new(), order = vector::::new(), named = vector::::new() }); return (this.program.functions.length - 1) as u32; } #! Notes that a function's code names another as a value, each once. #! @param this The compiler. #! @param function The function naming it. #! @param named The function named. pub def lowerer::names(&mut this, function: u32, named: u32): void { for &each in this.program.functions[function].named.span { return if each == named; } this.program.functions[function].named.append(named); } #! Marks a function as named by code that runs, so it is lowered. #! @param this The compiler. #! @param index The function. pub def lowerer::want(&mut this, index: u32): void { return if this.program.functions[index].queued; this.program.functions[index].queued = true; this.queue.append(index); } #! The name of a function as a trace writes it, as the C compiler names it: a #! method's names its type, as `vec2::normalize`, and an instance of a generic #! names its type arguments, as `max` and `list::push`. #! @param this The compiler. #! @param decl The function's declaration. #! @param instance The instance of a generic it is, or 0. #! @returns The name. pub def lowerer::function_name(&mut this, decl: u32, instance: u32): string { var holder: u32 = this.checker.decls.owners.p[decl]; if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property { holder = this.checker.decls.owners.p[holder]; } # The type arguments of an instance are its owner's, then its own. val args := instance != 0 ? this.checker.types.parts_view(this.checker.instances[instance].args) : span::::blank(); val own := this.checker.own_param_count(decl) as u64; val outer := args.length > own ? args.length - own : 0; var made := string::new(nothing {}); if holder != 0 { made.append(this.checker.names.text(this.checker.decls.names.p[holder])); if outer != 0 { this.type_args(args, 0, outer, &mut made); } made.append("::"); } made.append(this.checker.names.text(this.checker.decls.names.p[decl])); if own != 0 && args.length > outer { this.type_args(args, outer, args.length, &mut made); } return made; } #! Writes type arguments as a name shows them, ``, a pack's types as #! the arguments they are, and an empty pack as none, as the checker writes them. #! @param this The compiler. #! @param args The type arguments. #! @param from The first written. #! @param to The one past the last written. #! @param out Where they are written. def lowerer::type_args(&this, args: span, from: u64, to: u64, out: &mut string): void { out.append("<"); this.checker.describe_args(args[from:to - from], out); out.append(">"); } #! The byte of a file a node begins at. #! @param this The compiler. #! @param file The file. #! @param node The node. #! @returns The byte. pub def lowerer::node_offset(&this, file: u32, node: u32): u32 { val syntax := &this.checker.units[file].syntax; return syntax.token_offsets[syntax.node_tokens[node]]; } #! Lowers a function waiting to be lowered. #! @param this The compiler. #! @param index The function. def lowerer::lower_function(&mut this, index: u32): void { return if this.program.functions[index].lowered; this.program.functions[index].lowered = true; var made := emitter::new(this, index); made.lower(); made.finish(); this.program.functions[index].finished = true; } #! The datum holding text, made where it is new: its bytes, followed by a zero #! the length does not count. #! @param this The compiler. #! @param text The text. #! @returns The datum's index. pub def lowerer::text_datum(&mut this, text: strview): u32 { # A text new to `texts` is given the next ID, which has no datum yet. val id := this.texts.intern_view(text); if id < this.text_data.length { return this.text_data[id]; } var bytes := vector::::new(); bytes.extend(text); bytes.append(0); val index := this.program.data.length as u32; this.program.data.append(datum { bytes = move(&mut bytes), align = 1, relocations = vector::::new() }); this.text_data.append(index); return index; } #! Places a global after those placed before it, where it is not yet placed. #! @param this The compiler. #! @param decl The global's declaration. #! @returns Where it is among the globals. pub def lowerer::global_of(&mut this, decl: u32): u64 { if this.global_ids.get(&decl) is some(got) { return got; } this.checker.resolve(decl); val held := this.shape_of(this.checker.decls.types.p[decl]); this.program.globals = round_up(this.program.globals, held.align); val offset := this.program.globals; this.global_ids.set(decl, offset); this.program.globals += held.size; # Evaluating, a byte between globals keeps an address just past one from being # where the next begins, so an empty view at the end of a constant's array is # still that constant's. if this.options.evaluating { this.program.globals += 1; } return offset; } #! Where the instance of a variable or constant of a generic type is among the #! globals, placed after those placed before it where it is new. #! @param this The compiler. #! @param instance The instance. #! @returns Where it is. pub def lowerer::instance_global(&mut this, instance: u32): u64 { if this.instance_globals.get(&instance) is some(got) { return got; } val held := this.shape_of(this.checker.instances[instance].kind); this.program.globals = round_up(this.program.globals, held.align); val offset := this.program.globals; this.instance_globals.set(instance, offset); this.program.globals += held.size; if this.options.evaluating { this.program.globals += 1; } return offset; } #! Places a global no declaration names after those placed before it, as what #! a global refers to that was made for it is. #! @param this The compiler. #! @param kind Its type. #! @returns Where it is among the globals. pub def lowerer::unnamed_global(&mut this, kind: u32): u64 { val held := this.shape_of(kind); this.program.globals = round_up(this.program.globals, held.align); val offset := this.program.globals; this.program.globals += held.size == 0 ? 1 : held.size; return offset; } #! Asks for every function that is no generic's template, and has a body, as a #! library's tests want, rather than only those `main` reaches. #! @param this The lowerer. def lowerer::want_everything(&mut this): void { for id in 1..this.checker.decls.count { val decl := id as u32; continue if this.checker.decls.kinds.p[decl] != dk::function || this.checker.decls.has(decl, df::generic); continue if this.checker.decls.has(decl, df::intrinsic) || this.checker.decls.has(decl, df::failed); continue if !this.checker.has_body(decl) || this.trait_of_method(decl) != 0; this.function_of(decl, 0); } } #! Gives the program safe points where it handles a signal, which is where #! anything calls `system::handle`: each calls `system::dispatch`, which runs #! the handlers of the signals that have come. #! @param this The lowerer. def lowerer::find_dispatch(&mut this): void { val sys := this.checker.modules.find(0, word::system); return if sys == 0; val handle := this.checker.modules.decl(sys, this.checker.names.intern(&"handle")); val dispatch := this.checker.modules.decl(sys, this.checker.names.intern(&"dispatch")); return if handle == 0 || dispatch == 0 || this.checker.decls.kinds.p[dispatch] != dk::function; return if !this.checker.is_depended(handle); this.dispatch = this.function_of(dispatch, 0); } #! Whether a declaration is `core`'s, std's, or `system`'s, whose code has no #! safe points. #! @param this The lowerer. #! @param decl The declaration. #! @returns Whether it is. pub def lowerer::in_std(&this, decl: u32): bool { var at: u32 = this.checker.decls.modules.p[decl]; var steps := 0; while at != 0 && this.checker.modules.parents[at] != 0 && steps < 64 { at = this.checker.modules.parents[at]; steps++; } return at != 0 && (this.checker.modules.names[at] == word::std || this.checker.modules.names[at] == word::core || this.checker.modules.names[at] == word::system); }