Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 22:13:49 -05:00
commit 05756094ac
706 files changed
+135430

No files matched your search

+475
View File
@@ -0,0 +1,475 @@
#! @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 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<u32, u32>; #! The layout of each type.
var laying: u32; #! How many layouts are being made, one within another.
var referents: vector<u32>; #! References and pointers laid out, each with the type it reaches, which is laid out once the outermost is.
var signature_ids: dict<u32, u32>; #! The signature of each function type.
var function_ids: dict<u64, u32>; #! The function of each declaration and instance, by `pair_key(decl, instance)`, the instance one more than its index.
var builtin_ids: dict<u64, u32>; #! The function giving each built-in type each method, by `pair_key(type, name)`.
var lambda_ids: dict<u64, u32>; #! The function of each anonymous function, by `pair_key(table, node)`.
var adapter_ids: dict<u64, u32>; #! The adapter of each function named as a value of another function type, by `pair_key(table, node)`.
var global_ids: dict<u32, u64>; #! Where each global is among the globals, by its declaration.
var begun_globals: hashset<u32>; #! The globals whose initializers are lowered, or being lowered.
var vtable_ids: dict<u64, u32>; #! The vtable of each type for each trait's type, by `pair_key(type, trait)`.
var retrait_ids: dict<u64, u32>; #! The map of each conversion between traits' types, by `pair_key(from, to)`.
var linked_ids: dict<u32, u32>; #! The C function each foreign declaration calls.
var texts: interner<string>; #! Each text a datum holds.
var text_data: vector<u32>; #! The datum holding each text, by its ID in `texts`.
var dispatches: dict<u32, u32>; #! The run of the methods of each trait in the order its vtables hold them, in `lists`.
var lists: runs<u32>; #! The runs `dispatches` names.
var queue: vector<u32>; #! The functions waiting to be lowered.
pub var problems: vector<string>; #! What lowering could not lower, which a program the checker passes never has.
var summaries: dict<u64, keeping>; #! What each function does with what it is given, by `pair_key(decl, instance)`, once found for good.
var pending: vector<pending_scan>; #! The functions whose summaries are being found, in the order they were reached.
var pending_ids: dict<u64, u32>; #! The place of each in `pending`, by its key.
var reader_of: vector<u32>; #! Of each link of a pending function's readers, the reader, by its place.
var reader_next: vector<u32>; #! Of each link, one more than the next link of the same function, or 0.
var read_pairs: hashset<u64>; #! 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<evaluation>; #! Of a program evaluating constants, what it evaluates.
pub var evaluation_ids: dict<u64, u32>; #! 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<u64, u32>; #! 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::<u32, u32>::new(),
referents = vector::<u32>::new(),
signature_ids = dict::<u32, u32>::new(),
function_ids = dict::<u64, u32>::new(),
builtin_ids = dict::<u64, u32>::new(),
lambda_ids = dict::<u64, u32>::new(),
adapter_ids = dict::<u64, u32>::new(),
global_ids = dict::<u32, u64>::new(),
begun_globals = hashset::<u32>::new(),
vtable_ids = dict::<u64, u32>::new(),
retrait_ids = dict::<u64, u32>::new(),
linked_ids = dict::<u32, u32>::new(),
texts = interner::<string>::new(),
text_data = vector::<u32>::new(),
dispatches = dict::<u32, u32>::new(),
lists = runs::<u32>::new(),
queue = vector::<u32>::new(),
problems = vector::<string>::new(),
summaries = dict::<u64, keeping>::new(),
pending = vector::<pending_scan>::new(),
pending_ids = dict::<u64, u32>::new(),
reader_of = vector::<u32>::new(),
reader_next = vector::<u32>::new(),
read_pairs = hashset::<u64>::new(),
scanning = no_scan,
dispatch = no_function,
evaluations = vector::<evaluation>::new(),
evaluation_ids = dict::<u64, u32>::new(),
evaluated = outcomes::new(),
constant_data = dict::<u64, u32>::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 {
# A program evaluating constants computes them, and runs nothing else.
if this.options.evaluating {
this.lower_evaluations();
this.drain();
this.fill_retraits();
this.drain();
return this.problems.length == 0;
}
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();
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 {
var at: u64 = 0;
while at < this.queue.length {
val point := mark_scratch();
this.lower_function(this.queue[at]);
release_scratch(point);
at++;
}
this.queue.clear();
}
#! 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 One more than 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 - 1].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 One more than 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 - 1].table == 0 {
this.check_instances();
}
val held: u32 = this.checker.instances[instance - 1].table;
return held - 1 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 One more than 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);
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;
}
#! 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.view(), 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::<u32>::new(),
named = vector::<u32>::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.view() {
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<i64>` and `list<i64>::push`.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than 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 - 1].args) : span::<u32>::empty();
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, `<i64, bool>`, 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<u32>, from: u64, to: u64, out: &mut string): void {
out.append("<");
this.checker.describe_args(span::<u32>::over(args.data + 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();
}
#! 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::<u8>::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::<relocation>::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;
}
#! 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);
}