module compiler.assembler
Idea for an assembler
pub class Assembler
var m_line_parser: LineParser
fn assemble(source: str)
struct ParsedLine
mnemonic: strarguments: List[str]
class LineParser
var m_tokenizer: Tokenizer
pub fn parse_line(line: str) -> ParsedLine
fn unexpected(tok: Token, expected: str)
fn error(message?: str)
fn next_token() -> Token
class Tokenizer
var m_index: int64
var m_size: int64
var m_line: str
pub fn set_line(line: str)
pub fn next_token() -> Token
class Token
pub var kind: TokenKind
var pos: int64
pub fn to_string() -> str
enum TokenKind
Id(str)Number(int64)String(str)ColonCommaComment(str)End
module compiler.ast
pub struct NodeId
name: uint32id: int64
fn node_id_equal(node_id1: NodeId, node_id2: NodeId) -> bool
pub fn node_id_to_string(strtab: StringTable, id?: NodeId) -> str
pub fn new_hashmap_nodeid[T]() -> HashMap[NodeId,T]
fn node_id_hash(a?: NodeId) -> uint32
pub struct DocString
A docstring (like this one 8-))
lines: List[str]
pub class Type
pub var kind: TypeKind
pub var was_generic: bool
pub fn change_to(to_type: Type)
pub fn is_enum() -> bool
pub fn get_enum_def() -> EnumDef
pub fn get_enum_variant_from_type(attr: uint32) -> Option
pub fn get_enum_variant_names() -> List[uint32]
pub fn is_class() -> bool
pub fn is_interface() -> bool
pub fn is_int() -> bool
pub fn is_signed_int() -> bool
pub fn get_bits() -> int64
pub fn is_void() -> bool
pub fn is_unreachable() -> bool
pub fn is_undefined() -> bool
pub fn is_str() -> bool
pub fn is_char() -> bool
pub fn is_bool() -> bool
pub fn is_float() -> bool
pub fn is_base_type() -> bool
pub fn get_base_type() -> BaseType
pub fn is_opaque() -> bool
pub fn is_array() -> bool
pub fn get_element_type() -> Type
pub fn get_array_size() -> int64
pub fn is_struct() -> bool
pub fn is_union_struct() -> bool
pub fn get_struct_def() -> StructDef
pub fn get_interface_def() -> InterfaceDef
pub fn has_field(attr: uint32) -> bool
pub fn get_field_type(attr: uint32) -> Type
pub fn maybe_get_field_type(attr: uint32, also_private: bool) -> Option
pub fn get_field_types() -> Vector[Type]
pub fn has_method(name?: uint32) -> bool
pub fn is_sequence_like(strtab: StringTable) -> bool
pub fn is_iterable_like(strtab: StringTable) -> bool
pub fn is_nullable() -> bool
pub fn is_function_type() -> bool
pub fn get_parameter_types() -> Vector[ParameterType]
pub fn get_return_type() -> Type
pub fn get_except_type() -> Type
pub fn get_class_def() -> ClassDef
pub fn is_tycon_app() -> bool
pub fn get_tycon() -> TyCon
pub fn get_type_arguments() -> Vector[Type]
pub fn is_type_parameter() -> bool
pub fn get_type_parameter() -> TypeParameter
pub fn is_type_var() -> bool
pub fn get_type_var() -> TypeVariable
pub fn clone_type(ty?: Type) -> Type
pub fn new_type(kind: TypeKind) -> Type
fn types_to_string(strtab: StringTable, typs: Vector[Type]) -> str
pub fn type_to_string(strtab: StringTable, ty?: Type) -> str
fn change_type_to(ty: Type, to_type: Type)
pub fn apply_tycon(tycon: TyCon, type_arguments: Vector[Type]) -> Type
pub fn subst(ty: Type, m: HashMap[uint32,Type]) -> Type
fn subst_many(typs: Vector[Type], m: HashMap[uint32,Type]) -> Vector[Type]
pub fn create_subst_mapping(type_parameters: List[TypeParameter], type_arguments: Vector[Type]) -> HashMap[uint32,Type]
pub fn is_some_integer_type(ty?: Type) -> bool
pub fn get_bits_from_some_integer_type(ty?: Type) -> int64
pub fn deref_type_var(ty?: Type) -> Type
pub fn get_types_from_parameter_types(p2?: Vector[ParameterType]) -> Vector[Type]
pub fn get_enum_variant(enum_def: EnumDef, attr: uint32) -> Option
fn get_subst_map(ty: Type) -> HashMap[uint32,Type]
pub fn get_variant_payload_types(ty: Type, variant: EnumVariant) -> Vector[Type]
pub fn get_struct_field_index(ty: Type, attr: uint32) -> int64
pub fn get_method_ref_from_type(ty: Type, attr: uint32, location: int64) -> Expression
pub struct QualName
location: int64parts: List[uint32]
pub fn qual_name_to_string(strtab: StringTable, name: QualName) -> str
pub fn dotted(strtab: StringTable, parts2?: List[uint32]) -> str
pub fn commas(strtab: StringTable, names?: List[NameAtLocation]) -> str
pub enum TypeKind
Base(BaseType)UndefinedSomeInteger(int64)OpaqueVoidUnreachableNameRef(QualName)Function(Vector[ParameterType], FunctionInfo)TypeParam(TypeParameter)TypeVar(TypeVariable)Array(Type, int64)Pointer(Type)UnApp(TyCon)App(TyCon, Vector[Type])Def(TypeDef)
fn type_kind_to_string(strtab: StringTable, kind: TypeKind) -> str
pub struct ParameterType
label: Optionty: Type
enum BaseType
BoolInt(bool, int64)StrCharFloat(int64)
fn base_type_to_str(base: BaseType) -> str
pub fn base_type_equal(base_type1: BaseType, base_type2: BaseType) -> bool
pub struct TypeVariable
unique: int64ty: Option
pub enum TyCon
Struct(StructDef)Enum(EnumDef)Class(ClassDef)Interface(InterfaceDef)Ref(NodeId)NameRef(QualName)
fn tycon_to_str(strtab: StringTable, tycon: TyCon) -> str
pub fn tycon_equal(tycon1: TyCon, tycon2: TyCon) -> bool
pub fn tycon_get_type_parameters(tycon: TyCon) -> List[TypeParameter]
pub fn make_typectx() -> TypeContext
pub class TypeContext
Global type context with all types.
var table: Vector[Type]
var m_undefined: Type
var m_void: Type
var m_bool: Type
var m_int: Type
var m_str: Type
var m_opaque: Type
var m_float: Type
var m_char: Type
pub fn init()
pub fn get_type(index: int64) -> Type
pub fn undefined_type() -> Type
pub fn opaque_type() -> Type
Opaque type, void*
pub fn void_type() -> Type
pub fn bool_type() -> Type
pub fn int_type() -> Type
pub fn str_type() -> Type
pub fn float_type() -> Type
pub fn char_type() -> Type
fn void_type2() -> Type
pub fn unreachable_type() -> Type
fn new_base_type(base: BaseType) -> Type
pub fn specific_int_type(signed: bool, bits: int64) -> Type
pub fn uint8_type() -> Type
pub fn uint16_type() -> Type
pub fn uint32_type() -> Type
pub fn uint64_type() -> Type
pub fn int8_type() -> Type
pub fn int16_type() -> Type
pub fn int32_type() -> Type
pub fn int64_type() -> Type
pub fn specific_float_type(bits: int64) -> Type
pub fn float32_type() -> Type
pub fn float64_type() -> Type
pub fn undefined_type() -> Type
fn pointer_type(pointed_type: Type) -> Type
pub fn array_type(element_type: Type, size: int64) -> Type
pub fn function_type(parameter_types: Vector[ParameterType], info: FunctionInfo) -> Type
pub fn type_parameter_ref(type_parameter: TypeParameter) -> Type
pub fn new_type_var_ref(type_var: TypeVariable) -> Type
pub fn new_type_var(unique: int64) -> TypeVariable
pub fn type_var_equals(type_var1: TypeVariable, type_var2: TypeVariable) -> bool
pub struct NamespaceDef
Module namespace
name: uint32scope: Scope
pub class ModuleDef
pub var libname: Option
pub var namespace: List[uint32]
pub var location: int64
pub var filename: Option
pub var docstring: Option
pub var imports: Vector[Import]
pub var definitions: Vector[Definition]
pub var scope: Scope
pub fn get_name(strtab: StringTable) -> str
fn define_symbol(definition: Definition)
pub fn define_function(function_def: FunctionDef)
pub fn define_enum(enum_def: EnumDef)
pub fn new_module(libname: Option, namespace: List[uint32], location: int64, filename: Option, docstring: Option, imports: Vector[Import], definitions: Vector[Definition]) -> ModuleDef
pub fn new_empty_module(libname: Option, namespace: List[uint32], location: int64) -> ModuleDef
pub fn import_names(names: List[NameAtLocation], location: int64) -> Import
pub fn import_names_from(namespace: List[uint32], names: List[NameAtLocation], location: int64) -> Import
pub struct Import
location: int64namespace: Optionnames: List[NameAtLocation]
pub struct NameAtLocation
name: uint32location: int64
pub fn extern_function_def(is_pub: bool, libname: str, name: uint32, docstring: Option, type_parameters: List[TypeParameter], parameters: List[ParameterDef], return_type: Type, location: int64) -> FunctionDef
pub class Scope
var symbols: HashMap[uint32,Symbol]
pub var class_scope: bool
pub fn define(is_pub: bool, name: uint32, kind: SymbolKind, location: int64)
pub fn is_empty() -> bool
pub fn is_defined(name: uint32) -> bool
pub fn lookup(name: uint32) -> Option
fn dump(strtab: StringTable)
pub fn get_symbols() -> List[Symbol]
pub enum SymbolKind
Namespace(NamespaceDef)Macro(MacroDef)Function(FunctionDef)Parameter(ParameterDef)Var(Variable)TypeConstructor(TyCon)Typ(Type)Variant(EnumVariant)Field(StructField)
pub class Symbol
pub var is_pub: bool
pub var name: uint32
pub var kind: SymbolKind
pub var location: int64
var references: List[int64]
pub fn add_reference(location: int64)
Register a reference this symbol
pub fn get_references() -> int64
pub fn symbol_to_string(strtab: StringTable, symbol?: Symbol) -> str
pub enum Definition
Macro(MacroDef)Function(FunctionDef)Enum(EnumDef)Struct(StructDef)Class(ClassDef)Interface(InterfaceDef)Impl(ImplDef)Var(VariableDef)Type(TypeDef)
pub fn definition_to_str(strtab: StringTable, definition: Definition) -> str
pub struct MacroDef
name: uint32location: int64
fn macro_def_to_str(strtab: StringTable, macro_def: MacroDef) -> str
pub struct VariableDef
is_pub: boolvariable: Variablevalue: VariableDefValue
pub enum VariableDefValue
Intern(Option)Extern(str, bool)
fn variable_def_to_str(strtab: StringTable, variable_def: VariableDef) -> str
pub fn new_type_parameter(name: uint32, id: int64, location: int64) -> TypeParameter
pub fn type_parameter_equals(tp1: TypeParameter, tp2: TypeParameter) -> bool
pub struct TypeParameter
id: NodeIdlocation: int64
pub fn struct_def(is_pub: bool, name: uint32, id: int64, docstring: Option, type_parameters: List[TypeParameter], fields: Vector[StructField], location: int64) -> StructDef
pub struct StructDef
is_pub: boolid: NodeIddocstring: Optionis_union: booltype_parameters: List[TypeParameter]fields: Vector[StructField]location: int64scope: Scope
fn struct_def_to_str(strtab: StringTable, struct_def: StructDef) -> str
pub class StructBuilder
var nodeId: NodeId
var is_pub: bool
var is_union: bool
var location: int64
var type_parameters: List[TypeParameter]
var fields: Vector[StructField]
pub fn set_name(name: uint32)
pub fn set_id(id?: int64)
pub fn set_pub(is_pub?: bool)
pub fn set_is_union(is_union?: bool)
pub fn add_type_parameter(name: uint32, id: int64, location: int64) -> Type
pub fn add_field(name: uint32, ty: Type, location: int64)
pub fn finish() -> StructDef
pub struct StructField
name: uint32ty: Typelocation: int64
pub fn enum_def(is_pub: bool, name: uint32, id: int64, docstring: Option, location: int64, type_parameters: List[TypeParameter], variants: List[EnumVariant]) -> EnumDef
pub struct EnumDef
is_pub: boolid: NodeIddocstring: Optionlocation: int64type_parameters: List[TypeParameter]variants: List[EnumVariant]scope: Scope
fn enum_def_to_str(strtab: StringTable, enum_def: EnumDef) -> str
pub struct EnumVariant
name: uint32tag_value: int64location: int64payload: Vector[Type]
pub struct ClassDef
is_pub: boolid: NodeIddocstring: Optionlocation: int64is_extern: Optiontype_parameters: List[TypeParameter]definitions: Vector[Definition]scope: Scope
fn class_def_to_str(strtab: StringTable, class_def: ClassDef) -> str
pub struct InterfaceDef
is_pub: boolid: NodeIdtype_parameters: List[TypeParameter]docstring: Optionlocation: int64is_extern: Optiondefinitions: Vector[Definition]scope: Scope
pub struct ImplDef
id: NodeIdinterface_type: Typetarget_type: Typedocstring: Optionlocation: int64definitions: Vector[Definition]scope: Scope
pub struct TypeDef
is_pub: boolid: NodeIdty: Typelocation: int64
fn type_def_to_str(strtab: StringTable, type_def: TypeDef) -> str
pub fn function_def(is_pub: bool, name: uint32, docstring: Option, type_parameters: List[TypeParameter], this_parameter: Option, parameters: List[ParameterDef], return_type: Type, except_type: Type, body: Statement, location: int64) -> FunctionDef
pub struct FunctionInfo
return_type: Typeexcept_type: Type
pub struct FunctionDef
name: uint32docstring: Optionis_pub: boolinfo: FunctionInfotype_parameters: List[TypeParameter]this_parameter: Optionparameters: List[ParameterDef]body: FunctionDefBodylocation: int64
enum FunctionDefBody
Intern(ScopedBlock)Extern(str)None
pub fn function_decl_def(name: uint32, type_parameters: List[TypeParameter], this_parameter: Option, parameters: List[ParameterDef], return_type: Type, except_type: Type, location: int64) -> FunctionDef
pub fn function_def_to_str(strtab: StringTable, function_def: FunctionDef) -> str
pub fn function_ref(function_def: FunctionDef, type_arguments: Vector[Type], location: int64) -> Expression
fn get_parameter_types_from_parameters(parameters: List[ParameterDef]) -> Vector[ParameterType]
fn get_function_type(function_def: FunctionDef) -> Type
pub fn get_function_type2(function_def: FunctionDef, type_arguments: Vector[Type]) -> Type
fn get_function_type3(type_parameters: List[TypeParameter], type_arguments: Vector[Type], parameter_types: Vector[ParameterType], info: FunctionInfo) -> Type
pub fn parameter_def(name: uint32, id: int64, label_is_optional: bool, ty: Type, location: int64) -> ParameterDef
pub class ParameterDef
pub var id: NodeId
pub var label_is_optional: bool
pub var ty: Type
pub var location: int64
pub fn ref(location: int64) -> Expression
pub fn unlabeled_parameter(name: uint32, ty: Type) -> ParameterDef
pub fn labeled_parameter(name: uint32, ty: Type) -> ParameterDef
pub fn variable(name: uint32, id: int64, ty: Type, location: int64) -> Variable
pub class Variable
pub var id: NodeId
pub var ty: Type
pub var location: int64
pub var writable: bool
pub var escapes: bool
pub fn ref(location: int64) -> Expression
pub struct ScopedBlock
scope: Scopebody: Statement
pub fn scoped_block(body: Statement) -> ScopedBlock
pub class Statement
pub var kind: StatementKind
pub var location: int64
pub var ty: Type
pub fn is_breakable() -> bool
Can we use break / continue within this statement?
pub fn last_is_expr() -> bool
Determine if the last statement is an expression
fn statement(kind: StatementKind, location: int64) -> Statement
pub enum StatementKind
If(IfStatement)While(WhileStatement)Loop(LoopStatement)For(ForStatement)Case(CaseStatement)Switch(SwitchStatement)Let(LetStatement)Try(TryStatement)Compound(Vector[Statement])Expr(Expression)Assignment(Expression, Option, Expression)Return(Option)Raise(Expression)UnreachablePassBreakContinue
pub fn if_statement(condition: Expression, body: Statement, false_body: Statement, location: int64) -> Statement
pub struct IfStatement
condition: Expressiontrue_block: ScopedBlockfalse_block: ScopedBlock
pub struct WhileStatement
condition: Expressionblock: ScopedBlock
pub fn while_statement(condition: Expression, body: Statement, location: int64) -> Statement
pub fn loop_statement(body: Statement, location: int64) -> Statement
struct LoopStatement
block: ScopedBlock
pub fn for_statement(iter_var: Variable, iter_value: Expression, body: Statement, location: int64) -> Statement
pub struct ForStatement
iter_var: Variableiter_value: Expressionblock: ScopedBlock
pub fn try_statement(try_body: Statement, except_var: Variable, except_type: Type, except_body: Statement, location: int64) -> Statement
pub struct TryStatement
try_block: ScopedBlockexcept_var: Variableexcept_type: Typeexcept_block: ScopedBlock
pub fn case_statement(value: Expression, arms: List[CaseArm], else_clause: Option, location: int64) -> Statement
pub struct CaseStatement
value: Expressionarms: List[CaseArm]else_block: Option
pub struct CaseArm
location: int64name: uint32variables: List[Variable]block: ScopedBlock
pub fn switch_statement(value: Expression, arms: List[SwitchArm], default_body: Statement, location: int64) -> Statement
pub struct SwitchStatement
value: Expressionarms: List[SwitchArm]default_block: ScopedBlock
pub struct SwitchArm
location: int64value: Expressionblock: ScopedBlock
pub fn let_statement(variable: Variable, type_hint: Option, value: Expression, location: int64) -> Statement
struct LetStatement
variable: Variabletype_hint: Optionvalue: Expression
pub fn compound(inner: Vector[Statement], location: int64) -> Statement
pub fn expression_statement(expr: Expression) -> Statement
pub fn assignment_statement(target: Expression, op: Option, value: Expression, location: int64) -> Statement
pub fn return_statement(value: Option, location: int64) -> Statement
pub fn raise_statement(value: Expression, location: int64) -> Statement
pub fn pass_statement(location: int64) -> Statement
pub fn break_statement(location: int64) -> Statement
pub fn continue_statement(location: int64) -> Statement
pub fn unreachable_statement(location: int64) -> Statement
pub class Expression
pub var kind: ExpressionKind
pub var ty: Type
pub var location: int64
pub var writable: bool
pub fn is_this(strtab: StringTable) -> bool
Check if the expression is a reference to the 'this' parameter
pub fn is_null() -> bool
pub fn call_method(method: uint32, arguments: List[LabeledExpression], location: int64) -> Expression
pub fn call_it(arguments: List[LabeledExpression], location: int64) -> Expression
pub fn add(rhs: Expression, location: int64) -> Expression
pub fn less(typectx: TypeContext, rhs: Expression, location: int64) -> Expression
pub fn equals(typectx: TypeContext, rhs: Expression, location: int64) -> Expression
pub fn get_attr_typed(attr: uint32, location: int64) -> Expression
pub fn change_to(to: Expression)
pub fn clone() -> Expression
pub fn clone_expression(value: Expression) -> Expression
fn change_expression_to(expression: Expression, to: Expression)
pub enum ExpressionKind
Call(FunctionCall)GetAttr(Expression, uint32)GetIndex(Expression, List[Expression])Binop(BinopExpression)Unop(UnaryOperator, Expression)NameRef(uint32)VariableRef(Variable)FunctionRef(FunctionDef, Vector[Type])ParameterRef(ParameterDef)LoadSymbol(Symbol)IntLiteral(int64)FloatLiteral(float64)StringLiteral(str)CharLiteral(char)BoolLiteral(bool)StructLiteral(Type, List[Expression])UnionLiteral(Type, uint32, Expression)ClassLiteral(Type, List[LabeledExpression])ArrayLiteral(List[Expression])ArrayLiteral2(Expression, Type)TypeCast(Type, Expression)Box(Expression)Unbox(Expression, Type)ToString(Expression)Typ(Type)Variant(Type, EnumVariant)EnumLiteral(Type, EnumVariant, List[Expression])Stmt(Statement)If(IfExpression)Null
pub struct LabeledExpression
location: int64name: Optionvalue: Expression
pub fn struct_literal(ty: Type, values: List[Expression], location: int64) -> Expression
pub fn union_literal(ty: Type, field: uint32, value: Expression, location: int64) -> Expression
pub fn array_literal(values: List[Expression], location: int64) -> Expression
pub fn array_literal2(size: Expression, ty: Type, location: int64) -> Expression
pub fn parameter_ref(parameter_def: ParameterDef, location: int64) -> Expression
pub fn call(callee: Expression, arguments: List[LabeledExpression], ty: Type, location: int64) -> Expression
Function call expression
pub fn get_attr(base: Expression, field: uint32, ty: Type, location: int64) -> Expression
pub fn box_expression(value: Expression, location: int64) -> Expression
pub fn unbox_expression(value: Expression, to_type: Type, location: int64) -> Expression
pub struct FunctionCall
callee: Expressionarguments: List[LabeledExpression]
pub fn subscript(base: Expression, indici: List[Expression], ty: Type, location: int64) -> Expression
pub fn statement_expression(statement: Statement) -> Expression
fn variable_ref(variable: Variable, location: int64) -> Expression
pub fn name_ref(typectx: TypeContext, name: uint32, location: int64) -> Expression
pub struct BinopExpression
lhs: Expressionop: BinaryOperatorrhs: Expression
pub enum BinaryOperator
AndOrLessLessEqualsGreaterGreaterEqualsEqualsNotEqualsBitAndBitXorBitOrShiftLeftShiftRightAddSubMulDivMod
pub fn is_comparison_op(op: BinaryOperator) -> bool
pub fn binop(lhs: Expression, op: BinaryOperator, rhs: Expression, ty: Type, location: int64) -> Expression
pub struct IfExpression
condition: Expressiontrue_value: Expressionfalse_value: Expression
pub enum UnaryOperator
NotMinus
pub fn unop(op: UnaryOperator, value: Expression, ty: Type, location: int64) -> Expression
pub fn bool_literal(typectx: TypeContext, value: bool, location: int64) -> Expression
pub fn integer_literal(typectx: TypeContext, value: int64, location: int64) -> Expression
pub fn float_literal(typectx: TypeContext, value: float64, location: int64) -> Expression
pub fn string_literal(typectx: TypeContext, value: str, location: int64) -> Expression
pub fn char_literal(typectx: TypeContext, value: char, location: int64) -> Expression
pub fn to_string(typectx: TypeContext, value: Expression, location: int64) -> Expression
pub fn null_value(typectx: TypeContext, location: int64) -> Expression
pub fn print_ast2(strtab: StringTable, module_defs: List[ModuleDef])
pub fn print_ast(strtab: StringTable, module_def: ModuleDef)
fn import_to_string(strtab: StringTable, imp: Import) -> str
pub fn new_print_visitor(printer: AstPrinter) -> Visitor
pub class AstPrinter
var indent_level: int64
pub var strtab: StringTable
pub fn indent()
pub fn dedent()
fn get_prefix() -> str
pub fn print2(txt: str)
fn print_ast_definition(printer: AstPrinter, definition: Definition, phase: VisitPhase)
fn print_ast_type(printer: AstPrinter, ty: Type, phase: VisitPhase)
pub fn statement_to_string(strtab: StringTable, statement: Statement) -> str
fn print_ast_statement(printer: AstPrinter, statement: Statement, phase: VisitPhase)
pub fn expression_to_string(strtab: StringTable, expression?: Expression) -> str
fn print_ast_expression(printer: AstPrinter, expression: Expression, phase: VisitPhase)
fn print_ast_node(printer: AstPrinter, node: VisitNode, phase: VisitPhase)
pub fn binary_op_to_str(op?: BinaryOperator) -> str
fn unary_op_to_str(op: UnaryOperator) -> str
pub struct Visitor[D]
data: Don_definition: fn (D, Definition, VisitPhase)on_type: fn (D, Type, VisitPhase)on_statement: fn (D, Statement, VisitPhase)on_expression: fn (D, Expression, VisitPhase)on_node: fn (D, VisitNode, VisitPhase)
pub enum VisitPhase
PreMidPost
pub enum VisitNode
Arm(CaseArm)Arm2(SwitchArm)ScopeNode(Scope)ModuleNode(ModuleDef)
pub fn visit_module_defs[T](visitor: Visitor, module_defs: List[ModuleDef])
pub fn visit_module[T](visitor: Visitor, module_def: ModuleDef)
fn visit_definition[T](visitor: Visitor, definition: Definition)
fn visit_type[T](visitor: Visitor, ty: Type)
pub fn visit_statement[T](visitor: Visitor, statement: Statement)
pub fn visit_expression[T](visitor: Visitor, expression: Expression)
module compiler.bc_to_sil
Transform BC into SIL

Features of this pass:

- Compile structured types into pointers with load/store operations
- Implement multiply and divide by either physical instructions or a function call to a library
pub struct SilGenOptions
Target specific options
has_div: boolhas_mul: boolhas_fpu: boolword_size: int64
pub fn to_sil(program: Program, bits: int64) -> Program
struct StructLayout
Information how a structure is mapped into memory
size: int64alignment: int64fields: Vector[StructField]
struct StructField
offset: int64ty: Type
struct TypedValue
value: Valuety: Type
struct TypedAddress
address: Addressty: Type
struct ReturnSlot
address: TypedAddressty: Type
enum LocalStorage
Mutable(TypedAddress)UndefinedDefined(TypedValue)
class SilGen
var m_bc_program: Program
var m_bits: int64
var m_externs: Vector[Extern]
var m_globals: Vector[TypedAddress]
var m_structs: Vector[StructLayout]
var m_functions: Vector[Function]
var m_blobs: Vector[DataBlob]
var m_blocks: Vector[Block]
var m_current_block: Option
var m_block_is_terminated: bool
var m_parameters: List[TypedAddress]
var m_locals: Vector[LocalStorage]
var m_return_slots: List[ReturnSlot]
var m_vm: VirtualMachine
var m_tmp_number: int64
var m_lit_id_number: int64
var m_value_stack: Vector[TypedValue]
var m_stack_offset: int64
pub fn gen_program() -> Program
fn gen_global(global: Global)
fn gen_vm_value(ty: Type, value: Value) -> List[BlobContent]
fn calc_struct_layout(struct_def: Struct)
fn get_size_of(ty?: Type) -> int64
fn get_word_size() -> int64
fn get_ptr_type() -> Type
fn get_word_type() -> Type
fn get_int_type(bits: int64) -> Type
fn get_float_type(bits: int64) -> Type
fn get_sil_type(ty: Type) -> Type
fn gen_function(function: Function)
fn make_label(x?: uint32) -> str
fn gen_opcode(opcode: Instruction)
fn get_function_name(index: int64) -> str
fn gen_load(address: TypedAddress)
Load value from address
fn gen_store(address: TypedAddress, value: TypedValue)
fn gen_element_address(base: TypedValue, index: TypedValue) -> TypedAddress
base + index * sizeof
fn gen_struct_address(base: TypedValue, index: int64) -> TypedAddress
fn gen_call(callee: Address, n_args: int64, return_types: Vector[Type])
fn call_rt_malloc(size: Value, ty: Type)
fn call_rt_function_1(name: str, ty: Type, argument: Value)
fn call_rt_function(name: str, ty: Type, arguments: Vector[Value])
Invoke runtime helper function
fn load_int(value: int64) -> Value
fn new_block(name: str) -> Block
fn new_tmp(ty: Type) -> Value
fn new_stack_slot(size: int64) -> Address
fn new_tmp_id() -> uint32
fn new_id() -> int64
fn new_global(name?: str) -> Address
fn add_f64_blob(value: float64) -> TypedAddress
fn add_data_blob(data?: Bytes) -> Address
fn push_int(value?: int64)
fn push(value?: Value, ty: Type)
fn pop() -> TypedValue
fn pop_n(count: int64) -> Vector[Value]
fn pop_n_typed(count: int64) -> List[TypedValue]
fn set_current_block(block?: Block)
fn emit(op?: OpCode)
fn pack_f64(value: float64) -> Bytes
Place 64 bits float into 8 bytes
fn pack_f32(value: float32) -> Bytes
Place 32 bits float into 4 bytes
fn pack_i64(value: int64) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_i32(value: int32) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_i16(value: int16) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_i8(value: int8) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_u64(value: uint64) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_u32(value: uint32) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_u16(value: uint16) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_u8(value: uint8) -> Bytes
Place 64 bits integer into 8 bytes
fn pack_str(text: str) -> Bytes
module compiler.c_gen
C code backend

Translate bytecode into C code.
pub fn gen_c_code(program: Program, output_filename: Option, create_header: bool)
struct Value
ty: Typename: str
struct Local
value: Valuewritable: bool
fn is_heap(ty?: Type) -> bool
Test if type is heap like type
fn has_heap_field(struct_def: Struct) -> bool
class CGenerator
var out: TextGenerator
var out_source: TextGenerator
var out_header: TextGenerator
var stack: Vector[Value]
var next_id: int64
var local_variables: Vector[Local]
var local_parameters: Vector[Value]
var local_return_ptrs: Vector[Value]
var m_vm: VirtualMachine
pub var structs: Vector[Struct]
pub var globals: Vector[Global]
pub var functions: Vector[Function]
pub var extern_functions: Vector[ExternFunction]
pub fn gen_program(program: Program)
fn gen_struct_def(struct_def: Struct)
fn gen_extern_function_decl(extern_function: ExternFunction)
fn gen_global(global: Global)
fn gen_vm_value(ty: Type, value: Value) -> str
fn gen_function_decl(function: Function)
fn gen_function_signature(return_types: Vector[Type], name: str, parameters: Vector[TypedName], fill_param: bool)
fn gen_function(function: Function)
fn gen_instruction(instruction: Instruction)
fn gen_literal(literal: LiteralValue)
fn gen_to_opaque(ty3: Type)
fn gen_from_opaque(ty: Type)
fn get_function_callee(index: int64) -> str
fn gen_field_access(index: int64, field: TypedName)
fn get_struct_field(ty: Type, index: int64) -> TypedName
fn gen_call(callee: str, parameter_types: Vector[TypedName], return_types: Vector[Type])
fn gen_typed_name(ty: Type, name: str)
fn gen_typed_name_2(is_const: bool, ty: Type, name: str)
fn push(value?: Value)
fn pop_n(count: int64) -> List[Value]
fn pop() -> Value
fn gen_label_str(index?: uint32)
fn gen_goto(label?: uint32)
fn new_local_var() -> str
fn new_named_local_var(name: str) -> str
fn new_id() -> int64
fn indent()
fn dedent()
fn emit(text?: str)
fn write(text?: str)
fn writeln(text?: str)
module compiler.c_gen_v2
Generate C code directly from AST.

This is similar to the way python code is generated.

Alternative to c_gen module
pub fn gen_c_code_v2(strtab: StringTable, module_defs: List[ModuleDef], output_filename: Option, create_header: bool)
enum BlockType
TryLoop
class CGenerator2
var out: TextGenerator
var out_source: TextGenerator
var out_header: TextGenerator
var next_id: int64
var m_blocks: List[BlockType]
var strtab: StringTable
pub fn gen_module_defs(module_defs: List[ModuleDef])
fn gen_header(module_defs: List[ModuleDef])
fn gen_forward_declarations1(module_defs: List[ModuleDef])
fn gen_forward_declarations2(module_defs: List[ModuleDef])
fn gen_struct_defs(module_defs: List[ModuleDef])
fn gen_variable_def(variable_def: VariableDef)
fn gen_global_expression(expression?: Expression) -> str
fn gen_function_defs(module_defs: List[ModuleDef])
fn gen_struct_decl(struct_def: StructDef) -> str
fn gen_struct(struct_def: StructDef)
fn gen_struct_ctor_decl(struct_def: StructDef)
fn gen_struct_ctor(struct_def: StructDef)
fn gen_function_decl(function_def: FunctionDef)
fn gen_function(function_def: FunctionDef)
fn gen_typed_name(ty: Type, name: str)
fn gen_typed_name2(ty: Type, name: str) -> str
fn gen_block(statement?: Statement, target: Option)
fn gen_statement(statement?: Statement, target: Option)
fn gen_if_statement(if_statement: IfStatement, kw: str, target: Option)
fn enter_block(bt?: BlockType)
fn leave_block()
fn unwind_blocks(stop_on_loop: bool)
fn gen_expression(expression?: Expression)
fn gen_expression_list(values: List[Expression])
fn gen_box_value(value: Expression)
fn gen_unbox_value(to_type: Type)
fn gen_id(id: NodeId) -> str
fn new_var(name: str) -> str
fn indent()
fn dedent()
fn emit(text?: str)
fn write(text?: str)
fn binary_op_to_str(op: BinaryOperator) -> str
module compiler.backend.codegen
Machine code generation.
pub struct CodegenOptions
filename: Optionreport: Reportprofiler: Profilerdebug: Option
pub fn cgen[C,V](program: Program, backend: Backend, options: CodegenOptions)
class Codegen[C,V]
Machine independent code generator
var backend: Backend
var options: CodegenOptions
pub fn gen_program(program: Program, out: BinaryOutput)
fn gen_function(function: Function, out: BinaryOutput)
fn select_function(function: Function, context: SelectionContext[V]) -> Function
Turn abstract instructions into abstract machine specific instructions.
fn gen_blob(blob: DataBlob, out: BinaryOutput)
module compiler.dwarf
DWARF debug info.

See also: www.dwarfstd.org
var DW_AT_sibling: int64
var DW_AT_location: int64
var DW_AT_name: int64
var DW_AT_low_pc: int64
var DW_AT_high_pc: int64
var DW_AT_decl_column: int64
var DW_AT_decl_file: int64
var DW_AT_decl_line: int64
var DW_FORM_addr: int64
var DW_FORM_block2: int64
var DW_FORM_data2: int64
var DW_FORM_data4: int64
var DW_FORM_data8: int64
var DW_FORM_udata: int64
var DW_FORM_strp: int64
var DW_FORM_sec_offset: int64
var DW_ATE_float: int64
var DW_ATE_signed: int64
var DW_TAG_compile_unit: int64
var DW_TAG_subprogram: int64
var DW_CHILDREN_no: int64
var DW_CHILDREN_yes: int64
pub fn gen_debug_info(info: DbgInfo, out: BinaryOutput, emit_data: fn (DataItem, BinaryOutput))
Generate DWARF debug info into binary output.
class DwarfWriter
var m_out: BinaryOutput
var string_table: StringTable
pub fn write_debug_info(sub_programs: List[SubProgram], emit_data: fn (DataItem, BinaryOutput))
pub fn write_abbrevs(abbrevs: List[Abbrev])
Write abbreviations to .debug_abbrev section
fn write_abbrev(abbrev: Abbrev)
pub fn write_string_table()
fn write_byte(value?: int64)
fn write_u16(value?: int64)
fn write_u32(value?: int64)
fn uleb128(value?: int64)
Encode as unsigend LEB128 in output
struct SubProgram
name: strline: int64column: int64begin: strend: str
struct Abbrev
id: int64tag: int64children: boolattrs: List[AttrSpec]
struct AttrSpec
name: int64form: int64
module compiler.elf
ELF file format
var PT_NULL: int64
var PT_LOAD: int64
var PT_DYNAMIC: int64
var PT_INTERP: int64
var PT_NOTE: int64
var PT_SHLIB: int64
var PT_PHDR: int64
var PT_TLS: int64
var PF_X: int64
var PF_W: int64
var PF_R: int64
var SHN_UNDEF: int64
var SHT_NULL: int64
var SHT_PROGBITS: int64
pub var SHT_SYMTAB: int64
pub var SHT_STRTAB: int64
pub var SHT_RELA: int64
var SHT_HASH: int64
var SHT_DYNAMIC: int64
var SHT_NOTE: int64
var SHT_NOBITS: int64
var SHT_REL: int64
pub var SHF_WRITE: int64
pub var SHF_ALLOC: int64
pub var SHF_EXECINSTR: int64
pub var SHF_INFO_LINK: int64
var STB_LOCAL: int64
var STB_GLOBAL: int64
var STB_WEAK: int64
var STT_NOTYPE: int64
var STT_OBJECT: int64
var STT_FUNC: int64
var STT_SECTION: int64
var STT_FILE: int64
var STT_COMMON: int64
var STT_TLS: int64
pub fn section_header_type_to_string(t?: int64) -> str
pub fn program_header_flags_to_string(flags?: int64) -> str
pub fn program_header_type_to_string(t?: int64) -> str
pub fn flags_to_string(flags?: int64) -> str
pub fn write_elf(filename: Path, object: Object)
Write ELF file.
fn fill_symbols(writer: ElfWriter, object: Object, symbols: List[Symbol], symbol_map: HashMap[str,int64])
Fill symbol index map
fn write_section(writer: ElfWriter, section: Section, symbol_map: HashMap[str,int64])
Write a single section
fn is_global_symbol(symbol: Symbol) -> bool
fn write_symbol_table(writer: ElfWriter, symbols: List[Symbol])
pub fn write_section_headers(writer: ElfWriter)
pub fn read_elf(filename: Path) -> ElfReader
fn new_64bit_header() -> ElfHeader
fn new_sh() -> SectionHeader
pub struct ElfHeader
e_type: int64e_machine: int64e_version: int64e_entry: int64e_phoff: int64e_shoff: int64e_flags: int64e_ehsize: int64e_phentsize: int64e_phnum: int64e_shentsize: int64e_shnum: int64e_shstrndx: int64
pub struct ProgramHeader
p_type: int64p_flags: int64p_offset: int64p_vaddr: int64p_paddr: int64p_filesz: int64p_memsz: int64p_align: int64
pub struct SectionHeader
sh_name: int64sh_type: int64sh_flags: int64sh_addr: int64sh_offset: int64sh_size: int64sh_link: int64sh_info: int64sh_addralign: int64sh_entsize: int64
struct SymbolTableEntry
st_name: int64st_value: int64st_size: int64st_info: int64st_other: int64st_shndx: int64
struct RelaTableEntry
r_offset: int64r_info: int64r_addend: int64
pub struct Error
message: str
pub class ElfReader
var handle: int64
var is_32bit: bool
var is_big_endian: bool
pub fn close()
pub fn read_header() -> ElfHeader except Error
pub fn read_program_headers(header: ElfHeader) -> Vector[ProgramHeader]
fn read_program_header() -> ProgramHeader
pub fn read_section_headers(header: ElfHeader) -> Vector[SectionHeader]
fn read_section_header() -> SectionHeader
pub fn read_section(header: SectionHeader) -> Bytes
pub fn read_strtab(header: SectionHeader) -> StringTable
pub fn read_symbol_table(symtab_section: SectionHeader) -> Vector[SymbolTableEntry]
fn read_symtab_entry() -> SymbolTableEntry
pub fn read_relas(reloc_section: SectionHeader) -> Vector[RelaTableEntry]
fn read_rela_entry() -> RelaTableEntry
fn seek(pos: int64)
fn read_bytes(n: int64) -> Bytes
fn read_size_t() -> int64
fn read64() -> int64
fn read32() -> int64
fn read16() -> int64
fn read8() -> int64
pub class ElfWriter
var handle: int64
pub var is_32bit: bool
var is_big_endian: bool
pub var m_header: ElfHeader
pub var sh_string_table: StringTable
pub var section_headers: List[SectionHeader]
var section_ids: HashMap[str,int64]
pub var symbol_table: List[SymbolTableEntry]
pub var strtab: StringTable
var out: ByteArray
pub fn set_bitsize(bits: int64)
pub fn new_symbol(name: str) -> SymbolTableEntry
pub fn new_section(name: str) -> SectionHeader
pub fn get_section_index(name: str) -> int64
pub fn write_section_data(sh: SectionHeader, data: Bytes)
Write data, recording offset and size
pub fn write_header()
pub fn write_section_header(sh?: SectionHeader)
fn write_program_header(ph?: ProgramHeader)
pub fn write_symtab_entry(ste?: SymbolTableEntry)
pub fn write_rela_entry(rte?: RelaTableEntry)
pub fn seek(pos: int64)
pub fn tell() -> int64
pub fn write_bytes(data?: Bytes)
fn flush()
fn write_u8_array(buffer: [uint8], bufsize: int64)
fn write_array(value?: [int64], size: int64)
fn write8(value?: int64)
fn write32(value?: int64)
fn write16(value?: int64)
fn write64(value?: int64)
fn write_size_t(value?: int64)
pub class StringTable
var m_data: ByteArray
pub fn add_name(name?: str) -> int64
pub fn get_name(index?: int64) -> str
pub fn get_data() -> Bytes
pub fn set_data(data: Bytes)
module compiler.hexfile
Implement INTEL HEX format.
See also: https://en.wikipedia.org/wiki/Intel_HEX
pub class HexFile
var m_lines: List[HexLine]
pub fn add_bytes(address: int64, data: Bytes)
pub fn add_eof()
fn add_record(address: int64, record: int64, data: Bytes)
pub fn print_hex_file()
fn to_chunks(data: Bytes) -> List[Bytes]
struct HexLine
address: int64record: int64data: Bytes
fn hex_line_to_text(line: HexLine) -> str
module compiler.html
Module to create documentation from parsed code
pub fn create_docs(strtab: StringTable, module_defs: List[ModuleDef], output_filename: Option)
class HtmlGenerator
var strtab: StringTable
var out: TextGenerator
pub fn gen_module(module_def: ModuleDef)
fn gen_definition(definition: Definition)
fn gen_struct(struct_def: StructDef)
fn gen_enum(enum_def: EnumDef)
fn gen_class(class_def: ClassDef)
fn gen_variable(variable_def: VariableDef)
fn gen_function(function_def: FunctionDef)
pub fn gen_docstring(docstring?: Option)
fn gen_type(ty?: Type)
fn gen_type_parameters(parameters?: List[TypeParameter])
fn gen_type_arguments(arguments?: Vector[Type])
fn gen_kw(kw?: str)
fn gen_anchor(id?: NodeId)
fn gen_id(id?: NodeId)
fn gen_name(name?: uint32)
fn text(t?: str)
fn spanned(t?: str, cls: str)
fn enter_span(cls?: str)
fn leave_span()
fn enter_div()
fn leave_div()
module compiler.igraph
Interference graph.
pub class ControlFlowGraph[V]
pub var m_nodes: List[ControlFlowGraphNode[V]]
var m_edges: HashMap[str,Set[str]]
var m_nodes_by_name: HashMap[str,ControlFlowGraphNode[V]]
pub fn add_node(node?: ControlFlowGraphNode[V])
pub fn get_node(name?: str) -> ControlFlowGraphNode[V]
pub fn add_edge(name: str, dst: str)
pub fn get_successors(node: ControlFlowGraphNode[V]) -> List[ControlFlowGraphNode[V]]
typedef-LiveSet$2718:class(BitSet$72)
pub class ControlFlowGraphNode[V]
pub var m_gen: BitSet
pub var m_kill: BitSet
pub var m_live_in: BitSet
pub var m_live_out: BitSet
pub var block: Block
fn new_ig_for_vregs(vregs: Vector[Register]) -> InterferenceGraph
pub fn create_interference_graph[V](mfunc: Function, vregs: Vector[Register]) -> InterferenceGraph
Create interference graph

See also:
https://en.wikipedia.org/wiki/Live-variable_analysis
fn add_reg_interference(ig: InterferenceGraph, reg: Register, live_registers: BitSet)
pub class InterferenceGraph
var m_nodes: Vector[IGNode]
var m_adj: Vector[BitSet]
pub fn mask(n?: IGNode)
pub fn unmask(n?: IGNode)
pub fn is_masked(n?: IGNode) -> bool
pub fn get_node(id: uint32) -> IGNode
pub fn nodes() -> Vector[IGNode]
pub fn adjecent(n?: IGNode) -> AdjecentIter
Get a list of all non-masked neighbours
pub fn add_edge(a?: IGNode, b?: IGNode)
pub fn has_edge(a?: IGNode, b?: IGNode) -> bool
fn get_adj_set(n?: IGNode) -> BitSet
pub class IGNode
Node in the interference graph.
pub var id: uint32
pub var degree: int64
pub var masked: bool
pub var reg: Register
pub fn set_color(c?: int64)
pub fn is_colored() -> bool
pub fn to_string() -> str
pub class AdjecentIter
Dedicated iterator over adjecent nodes
var m_nodes: Vector[IGNode]
var m_set_iter: BitSetIter
pub fn iter() -> AdjecentIter
pub fn next() -> Option
pub fn dump_ig(ig: InterferenceGraph, report: Report)
module compiler.ir_gen
generate bytecode
pub fn gen_bytecode(strtab: StringTable, module_defs: List[ModuleDef], debug: Option) -> Program
pub fn gen_expression_bytecode(strtab: StringTable, expression: Expression) -> Vector[Instruction]
enum ControlBlock
LoopBlock(Loop)TryBlock(Try)Scope(List[Variable])
struct Loop
continue_label: uint32break_label: uint32
struct Try
except_label: uint32except_var_index: int64
class BytecodeGenerator
var id_counter: int64
var is_reachable: bool
var m_referenced_labels: Set[uint32]
var m_except_type: Type
var m_return_type: Type
var code: Vector[Instruction]
pub var global_variables: Vector[Global]
var global_var_mapping: HashMap[NodeId,int64]
var local_variables: Vector[Local]
var local_var_mapping: HashMap[NodeId,int64]
var label_mapping: HashMap[uint32,uint32]
var struct_mapping: HashMap[NodeId,int64]
pub var extern_functions: Vector[ExternFunction]
pub var structs: Vector[Struct]
pub var functions: Vector[Function]
var function_map: HashMap[uint32,int64]
var block_stack: List[ControlBlock]
var m_debug: Option
var strtab: StringTable
pub fn forward_declarations(module_defs: List[ModuleDef])
pub fn gen_prog(module_def: ModuleDef)
fn gen_global_variable(variable_def: VariableDef)
Create global variable
fn gen_global_init(variable_def: VariableDef)
Initialize global variable
fn gen_extern_function(libname: Option, function_def: FunctionDef)
fn gen_func(function_def: FunctionDef)
fn goto_inner_loop() -> Loop
fn goto_inner_try() -> Option
fn gen_scoped_block(scoped_block?: ScopedBlock, target: Option)
fn gen_statement(statement?: Statement, target: Option)
fn gen_return(opt_val: Option)
fn gen_raise(value: Expression)
fn actual_do_raise()
Do local jump, or return special marker value, which lives on top of stack now.
fn gen_assignment(target: Expression, op: Option, value: Expression)
fn gen_try_statement(try_statement: TryStatement)
fn gen_while_statement(while_statement: WhileStatement)
fn gen_if_statement(if_statement: IfStatement, target: Option)
fn gen_condition(condition: Expression, true_label: uint32, false_label: uint32)
fn gen_comparison(lhs: Expression, op: ComparisonOperator, rhs: Expression, true_label: uint32, false_label: uint32)
fn jump_if_true(true_label: uint32, false_label: uint32)
fn condition_as_value(condition: Expression)
pub fn gen_expression(expression?: Expression)
fn gen_if_expression(if_expression: IfExpression)
fn gen_call(call: FunctionCall)
fn gen_indirect_call(callee: Expression)
fn gen_binop_expr(binop: BinopExpression)
fn gen_binop(op: BinaryOperator, ty: Type)
fn new_label() -> uint32
fn set_label(label?: uint32)
fn translate_label(label?: uint32) -> uint32
fn begin_code()
pub fn get_relocated_instructions() -> Vector[Instruction]
fn jump(label?: uint32)
fn jump_if(op: ComparisonOperator, true_label: uint32, false_label: uint32)
fn add_local(variable: Variable, writable: bool) -> int64
fn new_local(name: str, ty: Type, writable: bool) -> int64
fn is_local_variable(variable: Variable) -> bool
fn get_local_index(variable: Variable) -> int64
fn get_global_index(variable: Variable) -> int64
fn get_parameter_index(parameter_def: ParameterDef) -> int64
fn get_bc_type(ty2?: Type) -> Type
fn enter_block(block: ControlBlock)
fn leave_block()
fn block_cleanup(block: ControlBlock)
pub fn emit(instruction?: Instruction)
fn get_name(id?: NodeId) -> str
fn gen_id() -> int64
fn get_attr_index(ty: Type, attr: uint32) -> int64
module compiler.isel
Instruction selection related code.
pub struct Backend[C,V]
Backend based on first instruction selection, then register allocation.
ctx: Cbits: int64all_regs: Vector[Vector[int64]]enter: fn (C, SelectionContext[V], Function)selector: fn (C, SelectionContext[V], Instruction)to_str: fn (V) -> strmaterializer: fn (SelectionContext[V], Instruction[V], BinaryOutput)emit_prologue: fn (Frame, BinaryOutput)emit_epilogue: fn (Frame, BinaryOutput)fixer: fn (ByteArray, int64, int64, int64, int64)is_pic_reloc: fn (int64) -> boolemit_data: fn (DataItem, BinaryOutput)
pub struct Frame
stacksize: int64exit_label: strvregs: Vector[Register]
pub class SelectionContext[V]
var codes: Vector[Instruction[V]]
var m_tmp_regs: HashMap[uint32,Register]
var m_pre_colored_regs: HashMap[uint32,Register]
pub var frame: Frame
pub fn get_value_vreg(value?: Value) -> Register
pub fn set_vreg_for_value(value: Value, register: Register)
fn get_vreg_for_tmp(id: uint32, ty: Type) -> Register
pub fn get_pre_colored(color: int64, kind: int64) -> Register
pub fn emit(instruction?: V)
fn emit_full(instruction?: V)
pub fn emit_minst(instruction: Instruction[V])
pub fn emit_and_get(instruction?: V) -> Instruction[V]
pub fn get_instructions() -> Vector[Instruction[V]]
pub fn new_vreg(kind: int64, color: int64) -> Register
module compiler.mil
Machine intermediate language.

Machine instructions are selected in this representation.
pub struct Function[X]
name: strblocks: Vector[Block]
pub struct Block[X]
Basic block
name: strinstructions: Vector[Instruction[X]]jump_targets: List[str]
pub class Instruction[X]
pub var instruction: X
pub var uses: Vector[Register]
pub var defs: Vector[Register]
pub var clobbers: Vector[Register]
pub var is_move: bool
pub fn add_use(r?: Register)
pub fn is_reg_used(r?: Register) -> bool
pub fn add_def(r?: Register)
pub fn is_reg_defined(r?: Register) -> bool
pub fn add_clobber(r?: Register)
fn does_contain(registers: Vector[Register], register: Register) -> bool
pub struct Register
id: uint32kind: int64color: int64
pub fn dump_mfunc[V](report: Report, mfunc: Function, to_str: fn (V) -> str)
fn regs_to_str(label: str, regs: Vector[Register]) -> str
pub fn vr_to_str(reg?: Register) -> str
module compiler.opt
Optimize SIL program.
pub fn optimize_sil(program: Program, level: int64)
fn optimize_function(function: Function)
pub fn skip_jump_blocks(function: Function) -> bool
If a block contains a single jump, we can bypass that block.

We can rewrite this:
jmp foo
...
foo:
jmp bar
...
bar:

To this:
jmp bar
...
bar:
fn block_fusion(function: Function, m: HashMap[str,Block]) -> bool
Combine blocks, if possible.

Criteria:
- block B must have only a single predecessor: block A
fn inc_pred(pred_count: HashMap[str,int64], target: str)
fn opt_clean(function: Function, m: HashMap[str,Block]) -> bool
Remove unreachable blocks.
module compiler.outstream
Logic for binary object code.

Use the Outstream to contrapt an Object struct, with code and data section.
pub struct Object
Code object
bits: int64little_endian: boolsections: Vector[Section]symbols: Vector[Symbol]
pub struct Section
name: strdata: ByteArrayrelocations: Vector[Relocation]alignment: int64allocate: boolexecutable: boolwritable: bool
pub struct Relocation
symbol: stroffset: int64typ: int64addend: int64
pub struct Symbol
name: strkind: SymbolKind
pub enum SymbolKind
ExternIntern(Section, int64, bool)
fn make_section(name: str) -> Section
struct Fixup
symbol: strsection: Sectionoffset: int64typ: int64addend: int64
pub class BinaryOutput
var m_bits: int64
var little_endian: bool
var sections: HashMap[str,Section]
var current_section: Option
var symbols: HashMap[str,Symbol]
var fixups: Queue[Fixup]
var tmp_labels: Queue[str]
pub fn set_bitsize(bits: int64)
pub fn select_section(name: str)
fn get_current_section() -> Section
pub fn import_symbol(name?: str)
Define symbol which lives externally
pub fn export_symbol(name?: str)
Define symbol, which can be used elsewhere
pub fn local_symbol(name?: str)
pub fn define_label(name?: str)
pub fn set_allocate()
pub fn set_writable()
pub fn set_executable()
fn define(name: str, global: bool)
Define a symbol at the current cursor
fn define_symbol(name: str, kind: SymbolKind)
pub fn is_extern_symbol(name: str) -> bool
pub fn add_fixup(symbol: str, typ: int64, addend: int64)
Add relocation information at the current position.
pub fn do_fixups(fixer: fn (ByteArray, int64, int64, int64, int64), is_pic_reloc: fn (int64) -> bool)
pub fn write_byte(value?: int64)
pub fn write_bytes(data: Bytes)
pub fn write_u32_le(value?: int64)
pub fn write_u64_le(value?: int64)
pub fn get_offset() -> int64
pub fn write_bytes_at(data: Bytes, offset: int64)
pub fn get_section(name: str) -> Section
pub fn get_object() -> Object
pub enum DataItem
Raw(Bytes)AbsPointer64(str)RelPointer32(str, int64)
module compiler.pygenerator
Generate python code from AST.
pub fn gen_python(strtab: StringTable, module_defs: List[ModuleDef], output_filename: Option)
class PyGenerator
var out: TextGenerator
var global_header: str
var imported_modules: Set[str]
var strtab: StringTable
var external_names: HashMap[uint32,str]
pub fn generate(module_defs: List[ModuleDef])
pub fn gen_module(module_def: ModuleDef)
fn gen_definition(definition: Definition)
fn gen_definition_variables(definition: Definition)
fn gen_block(block?: ScopedBlock, target: Option)
fn gen_statement(statement?: Statement, target: Option)
fn gen_if_statement(if_statement: IfStatement, kw: str, target: Option)
fn gen_expression(expression?: Expression, parens: bool) -> str
fn gen_expression_list(expressions: List[Expression]) -> str
fn get_id(id: NodeId) -> str
fn name_ref(name?: uint32) -> str
fn emit(txt?: str)
fn indent()
fn dedent()
fn wrap_int(value: str, ty: Type) -> str
fn binary_operator_to_str(op: BinaryOperator, float_division: bool) -> str
pub fn escape_string(text?: str) -> str
Prefix double quotes and backslashes with an extra backslash
pub fn needs_escaping(c: char) -> bool
pub fn escape_char(c: char) -> str
module compiler.register_allocation
Register allocation

This function is machine independant.
It assigns colors to use / def registers.
pub fn reg_alloc[C,V](report: Report, backend: Backend, mfunc: Function, frame: Frame)
Implement iterated register allocation
class RegisterAllocator[C,V]
Perform graph coloring
Take out nodes that can be colored
When the graph is empty, place the nodes back in reverse order,
and assign them a color
var m_regs_by_class: Vector[Vector[int64]]
var m_ig: InterferenceGraph
var m_select_stack: Vector[IGNode]
var m_simplify_worklist: Queue[IGNode]
var m_spill_worklist: HashMap[uint32,IGNode]
var m_freeze_worklist: HashMap[uint32,IGNode]
var m_pre_colored: HashMap[uint32,IGNode]
var m_spill_rounds: int64
var m_report: Report
var m_backend: Backend
var m_frame: Frame
pub fn alloc(mfunc: Function)
fn fill_data(mfunc: Function)
fn simplify()
fn spill(mfunc: Function)
Spill nodes with too many edges into memory locations.
fn rewrite_program(mfunc: Function, register: Register)
Introduce load before each use and store each definition
fn assign_colors()
Assign colors
fn is_colorable(m?: IGNode) -> bool
fn calculate_num_blocked(m?: IGNode) -> int64
fn q(B: int64, C: int64) -> int64
Number of registers from class B that can be block by a register in class C.
fn is_move_related(m?: IGNode) -> bool
module compiler.report
Internal reporting.

Useful for debugging the compilation stages.
pub class Report
var m_file: int64
var m_enabled: bool
pub fn set_enabled(v?: bool)
pub fn is_enabled() -> bool
pub fn heading(text?: str)
pub fn writeln(text?: str)
module compiler.riscv
RISCV encoding.

There are a couple of formats:
R/I/S/U

Register conventions:
register | name | saver | description
x0 | zero | - | zero constant
x1 | ra | callee | return address
x2 | sp | callee | stack pointer
x3 | gp | - | global pointer
x4 | tp | - | thread pointer
x5-x7 | t0-t2 | caller | temporaries
x8 | s0/fp | callee | saved / frame pointer
x9 | s1 | callee | saved register
x10-x11 | a0-a1 | caller | function arguments / return values
x12-x17 | a2-a7 | caller | function arguments
x18-x27 | s2-s11| callee | Saved registers
x28-x31 | t3-t6 | caller | temporaries
var R_BRANCH: int64
var R_JAL: int64
var R_CALL: int64
var R_HI20: int64
var R_LO12_I: int64
fn encode_R_type(funct7: int64, rs2: int64, rs1: int64, funct3: int64, rd: int64, opcode: int64) -> int64
fn encode_I_type(imm: int64, rs1: int64, funct3: int64, rd: int64, opcode: int64) -> int64
fn encode_S_type(imm: int64, rs2: int64, rs1: int64, funct3: int64, opcode: int64) -> int64
fn encode_U_type(imm: int64, rd: int64, opcode: int64) -> int64
fn encode_J_type(imm: int64, rd: int64, opcode: int64) -> int64
fn encode_B_type(imm: int64, rs2: int64, rs1: int64, funct3: int64, opcode: int64) -> int64
pub enum Instruction
LUI(int64, int64)AUIPC(int64, int64)JAL(int64, int64)JALR(int64, int64, int64)Branch(Cond, int64, int64, str)Load(LoadOp, int64, int64, int64)Store(StoreOp, int64, int64, int64)RegImm(ImmOp, int64, int64, int64)SLLI(int64, int64, int64)SRLI(int64, int64, int64)SRAI(int64, int64, int64)ThreeRegsOp(RegOp, int64, int64, int64)ECALLEBREAKLA(int64, str)LI(int64, int64)MOV(int64, int64)J(str)CALL(str)RET
pub enum Cond
EQNELTGELTUGEU
pub enum LoadOp
LBLHLWLBULHU
pub enum StoreOp
SBSHSW
pub enum ImmOp
ADDISLTISLTIUXORIORIANDI
pub enum RegOp
ADDSUBSLLSLTSLTUXORSRLSRAORAND
pub fn do_emit(instruction: Instruction, outstream: BinaryOutput)
fn emit_int_code(code: int64, outstream: BinaryOutput)
fn cond_code(cond: Cond) -> int64
fn imm_op_code(op: ImmOp) -> int64
fn reg_op_code(op: RegOp) -> int64
fn load_op_code(op: LoadOp) -> int64
fn store_op_code(op: StoreOp) -> int64
pub fn instruction_to_string(instruction: Instruction) -> str
pub fn cond_to_string(cond: Cond) -> str
pub fn imm_op_to_string(op: ImmOp) -> str
pub fn reg_op_to_string(op: RegOp) -> str
pub fn load_op_to_string(op: LoadOp) -> str
pub fn store_op_to_string(op: StoreOp) -> str
fn reg_to_string(reg?: int64) -> str
pub enum Relocation
Abs64(str)
pub fn is_pic_reloc(typ: int64) -> bool
Check if the relocation type is position independant
pub fn apply_reloc(data: ByteArray, offset: int64, typ: int64, addend: int64, symbol: int64)
fn read_int_at(data: ByteArray, offset: int64) -> int64
fn write_int_at(data: ByteArray, offset: int64, value: int64)
module compiler.riscv_gen
Generate riscv code

Register usage convention: (saver)
x0 -> zero -> hardwired 0
x1 -> ra -> return address (caller)
x2 -> sp -> stack pointer (caller)
x3 -> gp -> global pointer
x4 -> tp -> thread pointer
x5-x7 -> temporaries (caller)
x8
x9
x18-x27 -> s2-11 -> saved registers (callee)
x28-31 -> t3-6 -> temporaries (caller)

Pseudo instructions:
NOP > ADDI x0, x0, 0
RET > JALR x0, 0(ra)
J offset > JAL x0, offset
MV rd, rs > ADDI rd, rs, 0
pub fn gen_riscv(program: Program, options: CodegenOptions)
struct Ctx
y: int64
enum VirtInst
JalExitBranch(Cond, Register, Register, str)Mov(Register, Register)LoadImmediate(Register, int64)LoadAddress(Register, str)RegRegImm(ImmOp, Register, Register, int64)RegRegReg(RegOp, Register, Register, Register)Load(LoadOp, Register, Address)Store(StoreOp, Register, Address)Actual(Instruction)
struct Address
reg: Registeroffset: int64
fn vinst_to_str(vi: VirtInst) -> str
fn addr_to_str(addr: Address) -> str
fn enter_function(ctx: Ctx, context: SelectionContext[VirtInst], function: Function)
fn select_instruction(ctx: Ctx, context: SelectionContext[VirtInst], instruction: Instruction)
Select machine instruction based on sil operator
fn load_addr(context: SelectionContext[VirtInst], addr: Address) -> Address
fn emit_regregreg(context: SelectionContext[VirtInst], op: RegOp, dst_reg: Register, src1_reg: Register, src2_reg: Register)
fn emit_regregimm(context: SelectionContext[VirtInst], op: ImmOp, dst_reg: Register, src_reg: Register, imm: int64)
fn emit_move(context: SelectionContext[VirtInst], dst: Register, src: Register)
fn materialize(context: SelectionContext[VirtInst], v: Instruction[VirtInst], outstream: BinaryOutput)
Apply actual registers to instruction now.
fn mat_reg(reg: Register) -> int64
fn gen_prologue(frame: Frame, outstream: BinaryOutput)
fn gen_epilogue(frame: Frame, outstream: BinaryOutput)
fn gen_data_item(item: DataItem, out: BinaryOutput)
module compiler.sil
SIL (slang intermediate language)

An intermediate language for an abstract register based machine.

Properties:
- SSA (static single assignment)
- Closer to hardware, but still abstract (infinite registers)
- Basic operators
- basic types, integers and floating points
- Load and store from memory

Optimizers might operate on SIL

SSA IL
Similar to QBE IL
See: https://c9x.me/compile/doc/il.html
pub class Program
pub var externs: Vector[Extern]
pub var functions: Vector[Function]
pub var blobs: Vector[DataBlob]
pub fn dump(report: Report)
pub class Extern
pub var name: str
pub class DataBlob
Data block
pub var name: str
pub var is_local: bool
pub var readonly: bool
pub var contents: List[BlobContent]
pub fn dump(report: Report)
pub enum BlobContent
Raw(Bytes)Ptr(str)
pub class Function
A graph of control flow between blocks
pub var name: str
pub var parameters: Vector[Value]
pub var stacksize: int64
pub var start: Block
pub var blocks: Vector[Block]
pub fn to_string() -> str
pub fn dump(report: Report)
pub class Block
A linear flow of instructions
pub var name: str
pub var instructions: Vector[Instruction]
pub fn to_string() -> str
pub fn dump(report: Report)
pub class Instruction
pub var op: OpCode
pub fn to_string() -> str
fn comma_sep(values: Vector[Value]) -> str
pub enum OpCode
Const(Value, int64)Binop(Value, BinaryOp, Value, Value)Bitop(Value, BitwiseOp, Value, Value)GetAddress(Value, Address)Load(Value, Address)Store(Address, Value)Convert(bool, Value, Value)Jump(str)JumpIf(Value, CompOp, Value, str, str)Call(Option, Address, Vector[Value])Return(Option)Halt
pub fn is_terminating_op(op: OpCode) -> bool
pub enum BinaryOp
AddSubMulDivMod
pub enum BitwiseOp
AndOrXorShlShrSar
fn op_to_string(op?: BinaryOp) -> str
pub enum CompOp
EqNeqGtLtGteLte
fn comparison_to_string(op?: CompOp) -> str
pub struct Value
id: uint32ty: Type
pub enum Type
F64F32I64I32I16I8
pub fn type_to_string(ty?: Type) -> str
pub enum Address
Global(str, bool)StackSlot(int64)Ptr(Value)
pub fn value_to_string(value?: Value) -> str
pub fn address_to_string(address?: Address) -> str
pub fn print_sil_program_to_file(program: Program, filename: Option)
module compiler.slang_gen
Slang backend
Idea: This backend emits slang code, sort of a no-op operation?

Also useful for debugging transformed code
pub fn gen_slang(strtab: StringTable, module_defs: List[ModuleDef], output_filename: Option)
Create slang-lang source code.
class SlangGenerator
pub var out: TextGenerator
var strtab: StringTable
pub fn gen_module(module_def: ModuleDef)
fn gen_definition(definition: Definition)
fn gen_type(ty?: Type) -> str
fn gen_block(block?: ScopedBlock)
fn gen_statement(statement?: Statement)
fn gen_if_statement(if_statement: IfStatement, kw: str)
fn gen_expression(expression?: Expression, parens: bool) -> str
fn gen_expression_list(expressions: List[Expression]) -> str
fn get_id(id?: NodeId) -> str
fn emit(txt?: str)
fn write(txt?: str)
fn indent()
fn dedent()
module compiler.text_gen
Helper class to emit text code
pub class TextGenerator
var m_indentation: int64
var m_start_of_line: bool
var use_file: bool
var outf: int64
pub var m_one_tab: str
pub fn begin(output_filename: Option)
pub fn end()
pub fn indent()
pub fn dedent()
pub fn emit(text?: str)
pub fn write(text?: str)
pub fn writeln(text?: str)
fn write_indent()
module compiler.wasm_gen
WebAssembly backend
===================

Generate WebAssembly from AST.

WASM 3.0:
- strings are javascript strings via (ref extern)
- opaque pointers are (ref any)
- structs are mapped to GC structs

WASM 1.0:
- Pointers are mapped to i32 type
- floats are mapped to f64
- ints are mapped to i64
- linear memory is imported from javascript side
pub fn gen_webassembly_text(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext, output_filename: Option)
pub fn gen_webassembly_binary(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext, filename: Path)
pub fn gen_webassembly_module(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext) -> Module
class WasmGenerator
var strtab: StringTable
var typectx: TypeContext
var types: List[CompType]
var imports: List[Import]
var globals: List[Global]
var functions: List[Function]
var exports: List[Export]
var datas: List[Data]
var code: List[Instruction]
var struct_mapping: HashMap[NodeId,int64]
var global_mapping: HashMap[NodeId,int64]
var n_parameters: int64
var local_variables: List[ValueType]
var index_mapping: HashMap[str,int64]
var literal_offset: int64
var block_stack: List[bool]
var m_string_data: ByteArray
var array_i16_type: int64
var f64_box_type: int64
var f32_box_type: int64
var i64_box_type: int64
var i32_box_type: int64
var mk_string_fn_index: int64
var func_counter: int64
var global_counter: int64
fn add_i16_array()
fn add_num_box_type(num_type?: NumType) -> int64
fn add_builtin()
pub fn gen_module_defs(modules: List[ModuleDef]) -> Module
fn gen_external_function(function_def: FunctionDef)
fn gen_module(module_def: ModuleDef)
fn get_struct_def_index(struct_def: StructDef) -> int64
fn get_array_type_index(element_type: Type) -> int64
fn get_wasm_type(ty?: Type) -> ValueType
fn reg_signature(parameter_types: Vector[Type], return_type: Type) -> int64
fn inject_type(ty?: CompType) -> int64
fn gen_function(function_def: FunctionDef)
fn gen_statement(statement?: Statement, target: Option)
fn gen_try(try_statement: TryStatement)
fn gen_assignment(target: Expression, op: Option, value: Expression)
fn gen_op_for_type(op: BinaryOperator, ty: Type)
fn gen_condition(expression?: Expression)
Generate condition, keeping track of short circuit logic.
fn gen_expression(expression?: Expression)
fn box_value(value: Expression)
fn unbox_value(to_type: Type)
fn gen_call(call: FunctionCall)
fn get_func_index(function_def: FunctionDef) -> int64
fn gen_binop(binop: BinopExpression)
fn gen_unop(op: UnaryOperator, value: Expression)
fn gen_type_cast(from_type: Type, to_type: Type)
fn get_local_index(id: NodeId) -> int64
fn create_parameter(id: NodeId, ty: Type) -> int64
fn create_local(id: NodeId, ty: Type) -> int64
fn create_anonymous_local(ty: Type) -> int64
fn emit(instruction?: Instruction)
fn enter_block(is_loop: bool)
fn leave_block()
fn get_loop() -> int64
module compiler.x86
X86 instruction set

Calling conventions 64 bit / system V ABI

arguments: rdi, rsi, rdx, rcx, r8, r9
return value: rax
callee save: rbx, rsp, rbp, r12, r13, r14, r15
caller save: the other registers

SSE (linux/mac/unix):
arguments: xmm0 .. xmm7
return value: xmm0
callee save: -
caller save: xmm0 .. xmm15
var R_X86_64_NONE: int64
var R_X86_64_64: int64
var R_X86_64_PC32: int64
var R_X86_64_GOT32: int64
var R_X86_64_PLT32: int64
var R_X86_64_GOTPCREL: int64
var R_X86_64_32: int64
var R_X86_64_16: int64
var R_X86_64_GOTPCRELX: int64
var R_X86_64_REX_GOTPCRELX: int64
var R_X86_64_CODE_4_GOTPCRELX: int64
var R_X86_64_CODE_5_GOTPCRELX: int64
var R_X86_64_CODE_6_GOTPCRELX: int64
pub enum Instruction
OpRmReg(BitMode, Op, Rm, int64)OpRegRm(BitMode, Op, int64, Rm)MulRegRm(int64, Rm)CqoDivMul(DivMulOp, Rm)Call(str)CallRm(Rm)Jmp(str)Jcc(Cond, str)AddRmImm(Rm, int64)SubRmImm(Rm, int64)ShiftRmCl(ShiftOp, Rm)Lea(int64, Rm)MovRegImm64(int64, int64)MovRegImm32(int64, int64)Push(int64)Pop(int64)RetInt3Movsx8(BitMode, int64, Rm)Movsx16(BitMode, int64, Rm)Movsxd(int64, Rm)Movzx8(BitMode, int64, Rm)Movzx16(BitMode, int64, Rm)CvtSi2Sx(BitMode, SseMode, int64, Rm)CvtSx2Si(bool, SseMode, BitMode, int64, Rm)CvtSd2Ss(int64, Rm)CvtSs2Sd(int64, Rm)Ucomisd(int64, Rm)SseOpRegRm(SseMode, SseOp, int64, Rm)SseMovRegRm(SseMode, int64, Rm)SseMovRmReg(SseMode, Rm, int64)
pub enum Op
AddSubAdcSbbCmpAndOrXorMov
pub enum Cond
JbJaeJzJnzJbeJaJlJgeJleJg
pub enum SseOp
AddMulSubMinDivMax
pub enum DivMulOp
MulIMulDivIDiv
pub enum ShiftOp
RolRorRclRcrShlShrSar
pub enum BitMode
R8R16R32R64
pub enum SseMode
SingleDouble
pub enum Rm
Mem(int64)MemDisp8(int64, int64)MemDisp32(int64, int64)RipDisp32(str, bool)Reg(int64)
pub fn instruction_to_string(instruction: Instruction) -> str
pub fn div_mul_op_to_str(op: DivMulOp) -> str
pub fn sse_mode_to_str(sse_mode: SseMode) -> str
fn sse_op_to_str(op: SseOp) -> str
pub fn op_to_str(op: Op) -> str
fn cc_to_string(condition: Cond) -> str
pub fn shift_op_to_string(op: ShiftOp) -> str
fn rm_reg_to_str(mnemonic?: str, rm: Rm, reg: int64) -> str
fn reg_rm_to_str(mnemonic?: str, reg: int64, rm: Rm) -> str
fn rm_imm_to_str(opcode?: str, rm: Rm, imm: int64) -> str
fn rm_to_str(rm: Rm) -> str
fn reg64_to_str(reg: int64) -> str
fn reg_to_str(reg: int64) -> str
fn reg16_to_str(reg: int64) -> str
fn reg8_to_str(reg: int64) -> str
pub struct X86Relocation
offset: int64typ: X86RelocationType
enum X86RelocationType
R_NONER_64(str, int64)R_PC32(str, int64)
fn write32(value?: int64, out: BinaryOutput)
fn write64(value?: int64, out: BinaryOutput)
fn write_rex_byte(out: BinaryOutput, reg: int64)
fn write_sse_mode_prefix(sse_mode: SseMode, out: BinaryOutput)
fn write_mod_rm_byte(mod: int64, rm: int64, reg: int64, out: BinaryOutput)
fn write_mod_rm(mode: BitMode, opcode: int64, rm: Rm, reg: int64, out: BinaryOutput)
fn write_ext_opcode(mode: BitMode, opcode: int64, rm: Rm, reg: int64, out: BinaryOutput)
fn write_rm_reg(rm: Rm, reg: int64, out: BinaryOutput)
fn write_rm_imm(reg: int64, rm: Rm, imm: int64, out: BinaryOutput)
pub fn emit_instruction(instruction?: Instruction, out: BinaryOutput)
fn get_sse_opcode(op: SseOp) -> int64
fn get_opcode(mode: BitMode, op: Op) -> int64
fn get_cc_code(condition: Cond) -> int64
fn get_shift_code(op: ShiftOp) -> int64
pub fn is_pic_reloc(typ: int64) -> bool
pub fn apply_reloc(data: ByteArray, offset: int64, typ: int64, addend: int64, symbol: int64)
pub fn emit_data_item(data: DataItem, out: BinaryOutput)
module compiler.x86_gen
X86 backend
var rax: int64
var rcx: int64
var rdx: int64
var rbx: int64
var rsp: int64
var rbp: int64
var rsi: int64
var rdi: int64
var r8: int64
var r9: int64
var r10: int64
var r11: int64
var r12: int64
var r13: int64
var r14: int64
var r15: int64
var xmm0: int64
var xmm1: int64
var xmm2: int64
var xmm3: int64
var xmm4: int64
var xmm5: int64
var xmm6: int64
var xmm7: int64
var xmm8: int64
var xmm9: int64
var xmm10: int64
var xmm11: int64
var xmm12: int64
var xmm13: int64
var xmm14: int64
var xmm15: int64
pub fn gen_x86(program: Program, options: CodegenOptions)
struct X86Ctx
parameter_regs_i64: Vector[int64]parameter_regs_f64: Vector[int64]clobber_regs: Vector[int64]
pub enum VirtInst
EntryRmReg(BitMode, Op, VirtRm, Register)RegRm(BitMode, Op, Register, VirtRm)MulRegRm(Register, VirtRm)DivMul(DivMulOp, VirtRm)Mov(BitMode, Register, Register)MovImm(Register, int64)Lea(Register, VirtRm)ShiftRmReg(ShiftOp, VirtRm, Register)Push(Register)Pop(Register)CallRm(VirtRm)Movsx8(BitMode, Register, VirtRm)Movsx16(BitMode, Register, VirtRm)Movsxd(Register, VirtRm)Movzx8(BitMode, Register, VirtRm)Movzx16(BitMode, Register, VirtRm)CvtSi2Sx(BitMode, SseMode, Register, VirtRm)CvtSx2Si(bool, SseMode, BitMode, Register, VirtRm)CvtSs2Sd(Register, VirtRm)CvtSd2Ss(Register, VirtRm)Ucomisd(Register, VirtRm)SseMov(SseMode, Register, Register)SseOpRegRm(SseMode, SseOp, Register, VirtRm)SseMovRegRm(SseMode, Register, VirtRm)SseMovRmReg(SseMode, VirtRm, Register)Actual(Instruction)Exit
pub enum VirtRm
Reg(Register)StackSlot(int64)RegDisp(Register, int64)Global(str)GotGlobal(str)
fn vinst_to_str(vi?: VirtInst) -> str
fn vrm_to_str(vrm?: VirtRm) -> str
fn enter_function(ctx: X86Ctx, context: SelectionContext[VirtInst], function: Function)
fn gen_prologue(frame: Frame, out: BinaryOutput)
fn gen_epilogue(frame: Frame, out: BinaryOutput)
fn stack_round_up16(value?: int64, taken: int64) -> int64
Given the fact that we already took 'taken' bytes, round value to a multiple of 16 bytes.
fn select_instruction(ctx: X86Ctx, context: SelectionContext[VirtInst], instruction: Instruction)
Select machine instruction based on sil operator
fn get_int_mode(ty?: Type) -> BitMode
fn get_float_mode(ty?: Type) -> SseMode
fn add_rm_uses(minst?: Instruction[VirtInst], rm: VirtRm)
Add use information for RM mode
fn move(context: SelectionContext[VirtInst], mode: BitMode, dst: Register, src: Register)
fn sse_move(context: SelectionContext[VirtInst], mode: SseMode, dst: Register, src: Register)
fn load_addr(context: SelectionContext[VirtInst], address: Address) -> VirtRm
fn materialize(context: SelectionContext[VirtInst], minst: Instruction[VirtInst], out: BinaryOutput)
Apply selected registers, and emit selected instruction to output stream.
fn emit(instruction?: Instruction, out: BinaryOutput)
fn mat_reg(reg: Register) -> int64
fn mat_rm(rm: VirtRm) -> Rm
Materialize a Rm
module compiler.basepass
pub class IdGen
var counter: int64
pub fn new_id() -> int64
module compiler.bc
pub struct Program
extern_functions: Vector[ExternFunction]globals: Vector[Global]structs: Vector[Struct]functions: Vector[Function]
pub struct Global
name: strty: Typevalue: Option
pub struct Struct
libname: Optionname: strfields: List[TypedName]
pub struct TypedName
ty: Typename: str
pub struct Local
ty: Typename: strwritable: bool
pub struct ExternFunction
libname: Optionname: strparameters: Vector[TypedName]return_types: Vector[Type]no_return: bool
pub struct Function
is_pub: boolname: strparameters: Vector[TypedName]return_types: Vector[Type]no_return: boollocals: Vector[Local]instructions: Vector[Instruction]
pub enum Type
Int(bool, int64)Float(int64)BoolStrCharPtrStructRef(int64)Array(Type)Function(List[Type], Vector[Type])
pub fn get_element_type_from_type(ty?: Type) -> Type
pub enum Instruction
NopDupSwapLiteral(LiteralValue)NotNegBinop(BinaryOperator, Type)Bitop(BitOperator, Type)IntCast(bool, int64)FloatCast(int64)IntToFloat(int64)FloatToInt(bool, int64)ToOpaque(Type)FromOpaque(Type)Jump(uint32)JumpIf(ComparisonOperator, uint32, uint32)Call(int64)CallIndirect(Vector[TypedName], Vector[Type])Return(int64)DecRef(int64)UnreachableLocalGet(int64)LocalSet(int64)ParameterGet(int64)ParameterSet(int64)GetAttr(int64)SetAttr(int64)GetIndexSetIndexGlobalGet(int64)GlobalSet(int64)LoadFunc(int64)StructLiteral(int64)ArrayLiteral(Type)
pub fn get_target_labels(instructions: Vector[Instruction]) -> Set[uint32]
Get a set of labels to which is being jumped
pub enum LiteralValue
Int(int64)Str(str)Float(float64)Bool(bool)Char(char)Null
pub enum BinaryOperator
AddSubDivideModuloMultiply
pub enum ComparisonOperator
LessLessEqualsGreaterGreaterEqualsEqualsNotEquals
pub enum BitOperator
ShrShlXorAndOr
pub fn literal_to_string(literal?: LiteralValue) -> str
pub fn instruction_to_string(instruction?: Instruction) -> str
fn binop_to_string(op: BinaryOperator) -> str
fn comparison_to_string(op: ComparisonOperator) -> str
fn bitop_to_string(op: BitOperator) -> str
pub fn print_bc_program_to_file(program: Program, filename: Option)
pub fn print_bc_program(program: Program)
pub fn print_bc_instructions(instructions: Vector[Instruction])
class Printer
pub var m_out: TextGenerator
pub fn write_program(program: Program)
pub fn write_instructions(instructions: Vector[Instruction])
fn indent()
fn dedent()
fn emit(text?: str)
pub fn type_to_string(ty?: Type) -> str
module compiler.builtins
pub fn get_rt_module(strtab: StringTable, typectx: TypeContext) -> ModuleDef
module compiler.dbginfo
pub class DbgInfo
pub var sources: List[Source]
var sources_by_filename: HashMap[str,Source]
pub var functions: Vector[Function]
var functions_by_name: HashMap[str,Function]
pub fn add_source(filename: Path, code: str)
fn get_source(filename: Path) -> Source
pub fn add_function(name: str, filename: Path, location: int64)
pub fn has_function(name: str) -> bool
pub fn get_function_by_name(name: str) -> Function
pub struct Source
filename: Pathcode: str
pub struct Function
name: strlocation: int64source: Sourcestart_label: strend_label: str
module compiler.driver
Main compilation driver.
pub struct CompilationOptions
dump_ast: boolbackend: Backendadd_imports: List[Path]output_filename: Optiongen_export: Optionverbosity: int64optimization_level: int64check_unused_symbols: boolrun_code: booltime_trace: boolreport: booldebug: bool
pub enum Backend
BytecodeCC2PythonSlangWebAssembly(bool)NullSilRiscvX86Html
pub fn default_compile_options() -> CompilationOptions
pub fn compile(sources: List[Path], options: CompilationOptions) except CompilationError
Batch compile
fn new_builder(options: CompilationOptions) -> Builder
class Builder
pub var options: CompilationOptions
pub var m_profiler: Profiler
pub var m_id_gen: IdGen
pub var m_modules: List[ModuleDef]
pub var m_typectx: TypeContext
var m_rt_module: ModuleDef
pub var strtab: StringTable
pub var m_debug: Option
pub fn add_module(module_def: ModuleDef)
pub fn parse_module(path: Path) except ParseError
pub fn parse_sources(sources: List[Path]) except CompilationError
pub fn do_binding() except CompilationError
pub fn do_export()
pub fn do_transform() except CompilationError
Perform type checking and transformation on the added modules
pub fn get_bc_program() -> Program
pub fn get_sil_program(bits: int64) -> Program
module compiler.errors
pub struct CompilationError
errors: List[SingleCompilationError]
enum Severity
ErrorWarning
pub struct SingleCompilationError
filename: Optionseverity: Severitylocation: int64message: str
pub class ErrorCollector
var m_messages: List[SingleCompilationError]
var m_filename: Option
pub fn enter_file(filename: Option)
pub fn leave_file()
pub fn make_error(location: int64, message: str) -> SingleCompilationError
pub fn add_error(location: int64, message: str)
pub fn add_warning(location: int64, message: str)
pub fn append(error?: SingleCompilationError)
pub fn render_or_raise() except CompilationError
pub fn new_error(filename: Option, location: int64, message: str) -> SingleCompilationError
pub fn new_warning(filename: Option, location: int64, message: str) -> SingleCompilationError
pub fn new_single_error(filename: Option, location: int64, message: str) -> CompilationError
pub fn new_error_with_filename(filename: Path, location: int64, message: str) -> CompilationError
pub fn new_errors(errors: List[SingleCompilationError]) -> CompilationError
pub fn display_error(error: CompilationError)
pub fn print_errors(errors: List[SingleCompilationError])
fn render_message(message: SingleCompilationError)
fn print_error(label: str, filename: Path, message: SingleCompilationError)
fn count_leading_tabs(text: str) -> int64
module compiler.escape_analysis
Analyze variables, and mark variables that escape
pub fn escape(module_defs: List[ModuleDef])
struct Escaper
a: int64
fn escape_on_definition(filler: Escaper, definition: Definition, phase: VisitPhase)
fn escape_on_type(escaper: Escaper, ty: Type, phase: VisitPhase)
fn escape_on_statement(escaper: Escaper, statement: Statement, phase: VisitPhase)
fn escape_on_expression(escaper: Escaper, expression: Expression, phase: VisitPhase)
fn escape_on_node(escaper: Escaper, node: VisitNode, phase: VisitPhase)
fn mark_escaping_vars(value?: Expression)
This expression escapes
module compiler.namebinding
pub fn bind_names(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext, check_unused: bool) except CompilationError
fn fill_scopes(binder: NameBinder, module_defs: List[ModuleDef]) except CompilationError
fn import_symbols(binder: NameBinder, module_defs: List[ModuleDef]) except CompilationError
fn resolve_symbols(binder: NameBinder, typectx: TypeContext, module_defs: List[ModuleDef]) except CompilationError
fn check_unused_symbols(binder: NameBinder, module_defs: List[ModuleDef]) except CompilationError
fn new_bind_visitor(binder: NameBinder) -> Visitor
pub fn bind_names_expression(strtab: StringTable, expression: Expression) except CompilationError
fn get_scope(definition: Definition) -> Option
fn filler_on_definition(filler: NameBinder, definition: Definition, phase: VisitPhase)
fn filler_on_type(filler: NameBinder, ty: Type, phase: VisitPhase)
fn filler_on_statement(filler: NameBinder, statement: Statement, phase: VisitPhase)
fn filler_on_expression(filler: NameBinder, expression: Expression, phase: VisitPhase)
fn filler_on_node(filler: NameBinder, node: VisitNode, phase: VisitPhase)
fn binder_on_definition(binder: NameBinder, definition: Definition, phase: VisitPhase)
fn binder_on_type(binder: NameBinder, ty: Type, phase: VisitPhase)
fn binder_on_statement(binder: NameBinder, statement: Statement, phase: VisitPhase)
fn symbol_to_kind(symbol: Symbol) -> ExpressionKind
fn binder_on_expression(binder: NameBinder, expression: Expression, phase: VisitPhase)
fn binder_on_node(binder: NameBinder, node: VisitNode, phase: VisitPhase)
fn base_scope(strtab: StringTable, typectx: TypeContext) -> Scope
fn enter_namespace(namespace: NamespaceDef, path: List[uint32]) -> Option
Follow a path to a namespace
class NameBinder
Helper class to fill scopes, and resolve names from scopes.
var scopes: Vector[Scope]
var root_namespace: NamespaceDef
pub var tycon_map: HashMap[NodeId,TyCon]
pub var strtab: StringTable
var was_class_scope: bool
pub var errors: ErrorCollector
pub fn fill_imports(module_def: ModuleDef)
fn import_mod(start: List[uint32], imp: Import) except SingleCompilationError
fn find_module(root_namespace: NamespaceDef, start: List[uint32], location: int64, path: List[uint32]) -> NamespaceDef except SingleCompilationError
Try to look up a module in the namespace
pub fn add_tycon(id: NodeId, tycon: TyCon)
pub fn define_variable(is_pub: bool, variable: Variable)
pub fn define_type_parameter(type_parameter: TypeParameter)
pub fn define_parameter(parameter_def: ParameterDef)
pub fn register_module_into_namespace(module_def: ModuleDef)
Register module into the namespace hierarchy
pub fn define(is_pub: bool, name: uint32, kind: SymbolKind, location: int64)
pub fn lookup_expression_kind(name: uint32, location: int64) -> ExpressionKind except SingleCompilationError
fn lookup_expression(name: uint32, location: int64) -> Expression except SingleCompilationError
pub fn resolve_type_kind(name: QualName) -> TypeKind except SingleCompilationError
Resolve qualified name to a type
pub fn resolve_tycon(name: QualName) -> TyCon except SingleCompilationError
Resolve qualified name to a type constructor
fn resolve_qual_name(name: QualName) -> Symbol except SingleCompilationError
Resolve a qualified name to a symbol
pub fn resolve_attribute(namespace: NamespaceDef, attr: uint32, location: int64) -> Symbol except SingleCompilationError
Try to load an attribute from a module.
fn lookup_base_name(name: uint32, location: int64) -> Symbol except SingleCompilationError
pub fn enter_scope(scope: Scope)
pub fn leave_scope()
fn make_error(location: int64, message: str) -> SingleCompilationError
pub fn add_error(location: int64, message: str)
pub fn add_warning(location: int64, message: str)
pub fn render_or_raise() except CompilationError
module compiler.parsing.lexer
Turn source text into a sequence of tokens
enum LexerMode
NormalString
pub class Lexer
var pending: Queue[Token]
var indent_stack: Vector[uint32]
var at_bol: bool
var at_end: bool
var spaces: uint32
var source: str
var source_length: int64
var m_keywords: HashMap[uint32,TokenKind]
var strtab: StringTable
var m_mode: LexerMode
var m_keep_comments: bool
var tok_begin: int64
var fstring_begin: int64
var offset: int64
pub fn init(source: str)
pub fn keep_comments()
pub fn next_token() -> Token
fn work_some()
fn on_newline(tok: Token)
fn emit(tok: Token)
fn emit_token(kind: TokenKind, location: int64)
fn next_token2() -> Token
fn parse_normal_token() -> TokenKind
fn parse_string_token() -> TokenKind
fn parse_escape_sequence() -> TokenKind
fn parse_line_comment() -> TokenKind
fn parse_identifier() -> TokenKind
fn parse_char() -> TokenKind
Char literal
fn parse_string() -> TokenKind
fn parse_doc_string() -> TokenKind
Parse a doc string, like this one :)
fn parse_number(c: char) -> TokenKind
fn parse_binary_number() -> TokenKind
fn parse_hex_number() -> TokenKind
fn parse_float(base: int64) -> TokenKind
fn parse_hex_float(base: int64) -> TokenKind
fn parse_exponent(base: int64, exponent: int64, is_hex: bool) -> TokenKind
Parse the exponent notation after the 'e'
fn create_float(base: int64, exponent: int64) -> TokenKind
fn create_hex_float(base: int64, exponent: int64) -> TokenKind
fn peek() -> char
fn peek_n(n: int64) -> char
fn next_char() -> char
fn match(txt?: char) -> bool
fn get_lexeme() -> str
fn fill_keyword_dictionary()
fn add_keyword(key: str, value: TokenKind)
fn is_id(c: char) -> bool
fn is_id_or_digit(c: char) -> bool
module compiler.location
pub struct Location2
begin: int64end: int64
typedef-Location$6363:Int64
pub fn new_location(begin: int64, end: int64) -> int64
pub fn location_default() -> int64
pub fn get_begin(x?: int64) -> int64
pub fn get_end(x?: int64) -> int64
pub fn merge_locations(begin: int64, end: int64) -> int64
pub fn location_at(offset: int64) -> int64
pub struct Position
row: int64column: int64
pub fn offset_to_position(offset: int64, code: str) -> Position
Calculate row and column from offset in string.
module compiler.parsing.parsing
Recursive descent slang-lang parser.
pub fn parse_source(path: Path, id_gen: IdGen, typectx: TypeContext, strtab: StringTable, debug: Option) -> ModuleDef except ParseError
pub fn parse_module_from_text(source: str, filename: Path, id_gen: IdGen, typectx: TypeContext, strtab: StringTable, debug: Option) -> ModuleDef except ParseError
pub fn parse_statement_from_text(source: str, id_gen: IdGen, typectx: TypeContext, strtab: StringTable) -> Statement except ParseError
Invoke parsing, purely on statement.
pub fn parse_expr_from_text(source: str, id_gen: IdGen, typectx: TypeContext, strtab: StringTable) -> Expression except ParseError
Invoke parsing, purely on expression.
pub struct ParseError
location: int64message: str
class Parser
An attempt at a recursive descent parser.
var typectx: TypeContext
var lex: Lexer
var m_peek: Token
var m_peek2: Token
var id_gen: IdGen
var strtab: StringTable
pub fn feed(source: str)
pub fn parse_module(filename: Path) -> ModuleDef except ParseError
fn parse_import(location: int64) -> Import except ParseError
fn parse_from_import() -> Import except ParseError
fn parse_names() -> List[NameAtLocation] except ParseError
list of names until newline:
fn parse_macro_def() -> MacroDef except ParseError
fn parse_enum_def(is_pub: bool) -> EnumDef except ParseError
fn parse_type_parameters() -> List[TypeParameter] except ParseError
fn parse_struct_def(is_pub: bool) -> StructDef except ParseError
fn parse_class_def(is_pub: bool) -> ClassDef except ParseError
Parse a class definition.
fn parse_interface_def(is_pub: bool) -> InterfaceDef except ParseError
Parse an interface definition.
fn parse_impl_def(location: int64) -> ImplDef except ParseError
fn parse_type_def(is_pub: bool, location: int64) -> TypeDef except ParseError
fn parse_func_def(is_pub: bool, this_parameter: Option) -> FunctionDef except ParseError
fn parse_extern_func_def(libname: str) -> FunctionDef except ParseError
fn parse_func_decl_def(this_parameter: Option) -> FunctionDef except ParseError
fn parse_parameters() -> List[ParameterDef] except ParseError
fn parse_function_info() -> FunctionInfo except ParseError
fn parse_optional_return_type() -> Type except ParseError
fn parse_optional_except_type() -> Type except ParseError
fn parse_parameter_def() -> ParameterDef except ParseError
fn parse_optional_docstring() -> Option except ParseError
fn has_parsed_question() -> bool
fn parse_var_def(is_pub: bool, writable: bool) -> VariableDef except ParseError
fn parse_type() -> Type except ParseError
fn parse_qual_name() -> QualName except ParseError
fn parse_qual_name_suffix(name: uint32, location: int64) -> QualName except ParseError
fn parse_type_application(name: QualName) -> Type except ParseError
Parse type application
fn parse_function_type() -> Type except ParseError
Parse function signature.
fn parse_array_type() -> Type except ParseError
Parse array type
fn parse_block() -> Statement except ParseError
parse block of statements.
pub fn parse_statement() -> Statement except ParseError
fn parse_expression_statement() -> Statement except ParseError
fn parse_assignement_expression(target: Expression, op: Option, location: int64) -> Statement except ParseError
fn parse_let_statement(writable: bool) -> Statement except ParseError
fn parse_big_expression() -> Expression except ParseError
A potentially big multi-line expression occurring at the end of the line.
fn parse_obj_init(obj_ty: Expression, location: int64) -> Expression except ParseError
fn parse_labeled_expression() -> LabeledExpression except ParseError
fn parse_if_statement() -> Statement except ParseError
fn parse_while_statement() -> Statement except ParseError
fn parse_for_statement() -> Statement except ParseError
fn parse_try_statement() -> Statement except ParseError
fn parse_case_statement() -> Statement except ParseError
fn parse_case_arm(name: uint32, location: int64) -> CaseArm except ParseError
fn parse_switch_statement() -> Statement except ParseError
fn parse_return_statement() -> Statement except ParseError
fn parse_raise_statement() -> Statement except ParseError
pub fn parse_expression() -> Expression except ParseError
fn parse_if_expression(true_value: Expression, location: int64) -> Expression except ParseError
fn parse_expression2(min_prec: int64) -> Expression except ParseError
fn parse_unary() -> Expression except ParseError
fn parse_atom() -> Expression except ParseError
fn parse_raw_string() -> str except ParseError
Parse string without interpolation
fn parse_string(location: int64) -> Expression except ParseError
Parse possibly interpolated string.
fn parse_index_suffix(base: Expression) -> Expression except ParseError
fn parse_call_suffix(callee: Expression) -> Expression except ParseError
fn parse_array_literal(location: int64) -> Expression except ParseError
fn parse_array_literal2(size: Expression, location: int64) -> Expression except ParseError
fn parse_name() -> NameAtLocation except ParseError
fn parse_parenthesis_open() except ParseError
fn parse_parenthesis_close() except ParseError
fn parse_newline() except ParseError
fn parse_indent() except ParseError
fn parse_dedent() except ParseError
fn try_parse_dedent() -> bool
fn parse_kw_else() except ParseError
fn parse_kw_for() except ParseError
fn parse_colon() except ParseError
fn parse_comma() except ParseError
fn parse_equals() except ParseError
fn move_token()
fn get_token() -> Token
fn new_id() -> int64
fn unexpected_token(tok: Token, expected: str) -> ParseError
module compiler.parsing.token
pub fn default_token() -> Token
pub struct Token
location: int64kind: TokenKind
pub enum TokenKind
Identifier(uint32)KwAndKwBreakKwCaseKwClassKwContinueKwElseKwElifKwEnumKwExceptKwExternKwFnKwForKwFromKwIfKwImportKwImplKwInKwInterfaceKwLetKwLoopKwMacroKwModuleKwNotKwOrKwPassKwPubKwRaiseKwReturnKwStructKwSwitchKwTryKwTypeKwVarKwWhileKwUnreachableKwBoxKwUnboxKwNullFloat(float64, str)Integer(int64, str)Char(char)EscapedChar(char, CharEscapeMode, str)Bool(bool)StringStartStringContent(str)StringEndDocString(List[str])ColonCommaDotArrowQuestionParenthesisOpenParenthesisCloseBracketOpenBracketCloseBraceOpenBraceCloseEqualsBraceClose(str)PlusMinusSlashPercentAsterixLessGreaterLessEqualsGreaterEqualsEqualsEqualsEqualsShiftRightShiftLeftBitOrBitAndBitXorNotEqualsPlusEqualsMinusEqualsAsterixEqualsSlashEqualsSpace(uint32)Tab(uint32)NewLineComment(str)TabbedComment(uint32, str)IndentDedentEofNoneError(str)
pub enum CharEscapeMode
SimpleOctalHex
pub fn token_to_string(strtab: StringTable, tok: Token) -> str
Convert token to txt
module compiler.pass3
This pass runs after names have been resolved, and before types can be checked.
pub fn resolve_newops(strtab: StringTable, module_defs: List[ModuleDef], id_gen: IdGen) except CompilationError
fn newop_on_definition(newop: NewOp, definition: Definition, phase: VisitPhase)
fn newop_on_type(newop: NewOp, ty: Type, phase: VisitPhase)
fn newop_on_statement(newop: NewOp, statement: Statement, phase: VisitPhase)
fn newop_on_expression(newop: NewOp, expression: Expression, phase: VisitPhase)
fn newop_on_node(newop: NewOp, node: VisitNode, phase: VisitPhase)
class NewOp
pub var errors: ErrorCollector
pub var strtab: StringTable
var id_gen: IdGen
fn try_as_type(expression: Expression) -> Option
pub fn add_error(location: int64, message: str)
pub fn turn_tycon_to_type(tycon: TyCon) -> Type
pub fn new_type_arguments(type_parameters: List[TypeParameter]) -> Vector[Type]
fn new_id() -> int64
module compiler.string_table
pub class StringTable
String table used for string interning
var m_table: Vector[str]
var m_map: HashMap[str,uint32]
pub fn intern(name?: str) -> uint32
Perform string interning on identifier
pub fn get(index?: uint32) -> str
module compiler.transforms
Available transformations:
- Turn for-loops into while-loops
- Turn classes into structs with functions
- Turn enums into tagged unions
- Turn switch-statement into chain of if-statements

Ideas for transformations:
- Transform try/except into something else
pub struct TransformOptions
keep_switch: bool
pub fn transform(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext, id_gen: IdGen, rt_module: ModuleDef, options: TransformOptions) except CompilationError
fn remove_union_defs(module_defs: List[ModuleDef])
struct Transformer
class_rewriter: ClassRewritermodname: stroptions: TransformOptions
fn transformer_on_definition0(transformer: Transformer, definition: Definition, phase: VisitPhase)
fn transformer_on_definition1(transformer: Transformer, definition: Definition, phase: VisitPhase)
fn transformer_on_definition7b(transformer: Transformer, definition: Definition, phase: VisitPhase)
fn transformer_on_type0(transformer: Transformer, ty: Type, phase: VisitPhase)
fn transformer_on_type5(transformer: Transformer, ty: Type, phase: VisitPhase)
fn transformer_on_type7(transformer: Transformer, ty: Type, phase: VisitPhase)
fn transformer_on_statement0(transformer: Transformer, statement: Statement, phase: VisitPhase)
fn transformer_on_statement1(transformer: Transformer, statement: Statement, phase: VisitPhase)
fn transformer_on_statement3(transformer: Transformer, statement: Statement, phase: VisitPhase)
fn transformer_on_statement5(transformer: Transformer, statement: Statement, phase: VisitPhase)
fn transformer_on_statement7(transformer: Transformer, statement: Statement, phase: VisitPhase)
fn transformer_on_expression0(transformer: Transformer, expression: Expression, phase: VisitPhase)
fn transformer_on_expression1(transformer: Transformer, expression: Expression, phase: VisitPhase)
fn transformer_on_expression2(transformer: Transformer, expression: Expression, phase: VisitPhase)
fn transformer_on_expression3(transformer: Transformer, expression: Expression, phase: VisitPhase)
fn transformer_on_expression7(transformer: Transformer, expression: Expression, phase: VisitPhase)
fn upcast_type(expression: Expression)
fn transformer_on_node0(transformer: Transformer, node: VisitNode, phase: VisitPhase)
fn transformer_on_node7(transformer: Transformer, node: VisitNode, phase: VisitPhase)
fn transformer_on_node7b(transformer: Transformer, node: VisitNode, phase: VisitPhase)
fn transformer_on_type9(transformer: Transformer, ty: Type, phase: VisitPhase)
fn transformer_on_expression9(transformer: Transformer, expression: Expression, phase: VisitPhase)
enum EnumImpl
IntNullableStruct(StructDef)
class InterfaceImpl2
Interface implementation details
pub var struct_def: StructDef
var vtable_map: HashMap[str,Variable]
var invoker_map: HashMap[uint32,FunctionDef]
pub fn get_impl_vtable(strtab: StringTable, ty: Type) -> Variable
Get vtable for given type.
pub fn set_impl_vtable(strtab: StringTable, ty: Type, vtable: Variable)
pub fn set_invoker(name: uint32, invoker: FunctionDef)
pub fn get_invoker(name: uint32) -> FunctionDef
class ClassRewriter
var ctor_map: HashMap[NodeId,FunctionDef]
pub var class_struct_map: HashMap[NodeId,StructDef]
pub var enum_impl_map: HashMap[NodeId,EnumImpl]
pub var interface_impl2_map: HashMap[NodeId,InterfaceImpl2]
pub var new_definitions: Vector[Definition]
pub var strtab: StringTable
pub var typectx: TypeContext
var id_gen: IdGen
var rt_module: ModuleDef
pub fn rewrite_class_def(class_def: ClassDef)
fn lift_method(method: FunctionDef, class_def: ClassDef, struct_def: StructDef)
fn create_constructor(class_def: ClassDef, struct_def: StructDef)
pub fn rewrite_class_literal(ty: Type, arguments: List[LabeledExpression], location: int64) -> Expression
pub fn prefix_name(prefix: str, name: uint32) -> uint32
fn get_unique_id() -> int64
fn new_variable(name: str, ty: Type, location: int64) -> Variable
fn get_enum_impl(id: NodeId) -> EnumImpl
pub fn load_std_function(name: str, location: int64) -> Expression
fn load_rt_symbol(name: str) -> Symbol
pub fn rewrite_interface_def(interface_def: InterfaceDef)
fn create_invoker_helper(this_ty: Type, function_def: FunctionDef) -> FunctionDef
Create a function that takes a vtable/data pair, which calls the proper function.
pub fn rewrite_impl_def(impl_def: ImplDef)
Create a global variable initialized with a vtable.

Move implementing function to toplevel
fn create_impl_wrapper_func(method: FunctionDef) -> FunctionDef
pub fn rewrite_cast_to_interface(value: Expression, ty: Type) -> Expression
Turn cast to interface into struct literal with data + vtable
pub fn transform_for_loop(for_statement: ForStatement, location: int64) -> Statement
Turn for loop into iterator and while loop
fn transform_for_loop_over_iterator(for_statement: ForStatement, location: int64) -> Statement
fn transform_for_loop_over_sequence(for_statement: ForStatement, location: int64) -> Statement
fn transform_for_loop_over_array(for_statement: ForStatement, location: int64) -> Statement
fn transform_for_loop_over_str(for_statement: ForStatement, location: int64) -> Statement
pub fn transform_switch(switch_statement: SwitchStatement, location: int64) -> StatementKind
pub fn rewrite_enum_def(enum_def: EnumDef)
pub fn transform_case(case_statement: CaseStatement) -> Statement
Transform case statement into switch case over tag values.
pub fn rewrite_enum_literal(enum_ty: Type, variant: EnumVariant, values: List[Expression], location: int64) -> Expression
pub fn erase_type(ft: Type, value: Expression, assign: bool)
fn create_bridge_function(function_def: FunctionDef, parameter_types: Vector[Type], return_type: Type) -> FunctionDef
fn needs_opaque_cast(ty?: Type) -> bool
fn uplift_this_parameter(function_def: FunctionDef)
module compiler.typechecking
Type checking logic.
pub fn type_check(module_defs: List[ModuleDef], strtab: StringTable, typectx: TypeContext, display_warnings: bool) except CompilationError
fn type_check_module(module_def: ModuleDef, strtab: StringTable, typectx: TypeContext, display_warnings: bool) except CompilationError
fn new_type_check_visitor(checker: TypeChecker) -> Visitor
pub fn type_check_expression(strtab: StringTable, typectx: TypeContext, expression: Expression) except CompilationError
fn checker_on_definition(checker: TypeChecker, definition: Definition, phase: VisitPhase)
fn checker_on_type(checker: TypeChecker, ty: Type, phase: VisitPhase)
fn assign_types(variables: List[Variable], types: Vector[Type])
fn checker_on_statement(checker: TypeChecker, statement: Statement, phase: VisitPhase)
fn checker_on_expression(checker: TypeChecker, expression: Expression, phase: VisitPhase)
fn checker_on_node(checker: TypeChecker, node: VisitNode, phase: VisitPhase)
class TypeChecker
pub var errors: ErrorCollector
pub var was_errors: bool
pub var current_function: Option
pub var loops: int64
pub var exception_handlers: List[Type]
var strtab: StringTable
var m_typectx: TypeContext
pub fn check_function_def(function_def: FunctionDef)
pub fn check_statement_mid(statement: Statement)
pub fn check_statement(statement: Statement)
pub fn check_expression(expression: Expression)
fn check_arguments(location: int64, parameter_types: Vector[Type], arguments: List[Expression])
fn check_may_raise_exception(ty: Type, location: int64)
fn assert_void(statement: Statement)
fn assert_statement_type(statement: Statement, ty: Type)
fn merge_paths(statement: Statement, ty: Type) -> Type
fn coerce(ty: Type, value: Expression)
Fit an expression to a type.
fn check_type(given_ty: Type, expected_ty: Type, location: int64)
fn unify(ty1: Type, ty2: Type) -> bool
fn unify_many(typs1: Vector[Type], typs2: Vector[Type]) -> bool
fn add_error(location: int64, message: str)
fn add_warning(location: int64, message: str)
module compiler.typedb
Functions to serialize type definitions to JSON.
pub fn store_symbol_table(strtab: StringTable, module_defs: List[ModuleDef], filename: Path)
class SymbolSaver
var m_ser: JsonBuilder
var strtab: StringTable
var m_libname: str
pub fn save_modules(module_defs: List[ModuleDef]) -> JsonValue
fn save_module(module_def: ModuleDef)
fn save_import(imp: Import)
fn save_definition(definition: Definition)
fn save_macro_def(macro_def: MacroDef)
fn save_var_def(variable_def: VariableDef)
fn save_type_def(type_def: TypeDef)
fn save_enum_def(enum_def: EnumDef)
fn save_class_def(class_def: ClassDef)
fn save_function_def(function_def: FunctionDef)
fn save_function_info(info: FunctionInfo)
fn save_struct_def(struct_def: StructDef)
fn save_interface_def(interface_def: InterfaceDef)
fn save_impl_def(impl_def: ImplDef)
fn save_doc_string(docstring: Option)
fn save_type_parameters(type_parameters: List[TypeParameter])
fn save_types(attr: str, types: Vector[Type])
fn save_type_if_non_void(attr: str, ty: Type)
fn save_type(attr: str, ty: Type)
fn save_tycon(tycon: TyCon)
fn save_id(id: NodeId)
fn save_name_list(attr: str, values?: List[uint32])
fn save_string_list(attr: str, values?: List[str])
pub fn load_symbol_table(filename: Path, strtab: StringTable, typectx: TypeContext) -> List[ModuleDef]
class SymbolLoader
var strtab: StringTable
var typectx: TypeContext
var m_des: JsonBrowser
var m_type_parameter_map: HashMap[NodeId,TypeParameter]
var m_this_type: Option
var m_libname: str
pub fn push_json(value: JsonValue)
pub fn load_modules() -> List[ModuleDef]
fn load_module(libname: Option) -> ModuleDef
fn load_import() -> Import
fn load_definition() -> Definition
fn load_variable_def(def_name: uint32, def_id: int64) -> VariableDef
fn load_function(def_name: uint32, def_id: int64) -> FunctionDef
fn load_function_info() -> FunctionInfo
fn load_parameters() -> List[ParameterDef]
fn load_parameter() -> ParameterDef
fn load_struct_def(def_name: uint32, def_id: int64) -> StructDef
fn load_type_def(def_name: uint32, def_id: int64) -> TypeDef
fn load_enum_def(def_name: uint32, def_id: int64) -> EnumDef
fn load_class_def(def_name: uint32, def_id: int64) -> ClassDef
fn load_definitions(attr: str) -> Vector[Definition]
fn load_interface_def() -> InterfaceDef
fn load_impl_def() -> ImplDef
fn load_docstring() -> Option
Load optional docstring
fn load_type_parameters() -> List[TypeParameter]
fn load_types(attr: str) -> Vector[Type]
fn load_type_or_void(attr: str) -> Type
Load type from attribute, or void, if attribute is absent
fn load_type(attr: str) -> Type
fn load_id() -> NodeId
fn load_name_list(attr: str) -> List[uint32]
fn load_string_list(attr: str) -> List[str]
module compiler.vm
Virtual machine for bytecode.
pub enum Value
Int64(int64)Int32(int32)Int16(int16)Int8(int8)Uint64(uint64)Uint32(uint32)Uint16(uint16)Uint8(uint8)Str(str)Char(char)Float(float64)Bool(bool)List(ListValue)NullUndefined
enum FunctionRef
ByteCode(Function)Native(ExternFunctionImpl)
struct ListValue
values: List[Value]
pub fn value_to_string(value?: Value) -> str
fn bool_from_value(value?: Value) -> bool
fn str_from_value(value?: Value) -> str
fn int64_from_value(value?: Value) -> int64
fn int32_from_value(value?: Value) -> int32
fn uint64_from_value(value?: Value) -> uint64
fn uint32_from_value(value?: Value) -> uint32
fn char_from_value(value?: Value) -> char
fn float_from_value(value?: Value) -> float64
fn list_from_value(value?: Value) -> ListValue
struct ExternFunctionImpl
f: fn (List[Value]) -> Optionn: int64
fn efi_std_ord(arguments: List[Value]) -> Option
fn efi_std_chr(arguments: List[Value]) -> Option
fn efi_std_float_to_str(arguments: List[Value]) -> Option
fn efi_std_float_to_str2(arguments: List[Value]) -> Option
fn efi_std_str_len(arguments: List[Value]) -> Option
fn efi_std_str_get(arguments: List[Value]) -> Option
fn efi_std_str_slice(arguments: List[Value]) -> Option
fn efi_std_print(arguments: List[Value]) -> Option
fn efi_std_read_line(arguments: List[Value]) -> Option
fn efi_default(arguments: List[Value]) -> Option
fn efi_rt_int_to_str(arguments: List[Value]) -> Option
fn efi_rt_char_to_str(arguments: List[Value]) -> Option
fn efi_rt_str_concat(arguments: List[Value]) -> Option
fn efi_rt_str_compare(arguments: List[Value]) -> Option
fn get_efi_db() -> HashMap[str,ExternFunctionImpl]
pub fn prepare_vm(vm: VirtualMachine, program: Program)
pub fn run_bytecode(program: Program, entry_function: str)
pub fn eval_code(vm: VirtualMachine, code: Vector[Instruction]) -> Value
Evaluate a bytecode expression
fn frame_from_function(function: Function, arguments: List[Value]) -> Frame
class Frame
pub var arguments: Vector[Value]
pub var locals: Vector[Value]
pub var stack: List[Value]
pub var pc: int64
var code: Vector[Instruction]
pub fn fetch() -> Instruction
pub class VirtualMachine
pub var frames: List[Frame]
pub var globals: Vector[Value]
pub var m_functions: Vector[FunctionRef]
pub var structs: Vector[Struct]
pub fn step()
fn fetch() -> Instruction
fn execute(instruction: Instruction)
fn push_empty_list(count: int64)
fn push(value?: Value)
fn pop() -> Value
fn pop_n(count: int64) -> List[Value]
fn jump(pc?: uint32)
fn get_local(index: int64) -> Value
fn set_local(index: int64, value: Value)
fn get_parameter(index: int64) -> Value
fn set_parameter(index: int64, value: Value)
fn get_global(index: int64) -> Value
fn set_global(index: int64, value: Value)
pub fn pop_frame() -> Frame
pub fn push_frame(frame: Frame)
fn eval_binop_int64(op: BinaryOperator, lhs: int64, rhs: int64) -> int64
fn eval_binop_int32(op: BinaryOperator, lhs: int32, rhs: int32) -> int32
fn eval_binop_uint64(op: BinaryOperator, lhs: uint64, rhs: uint64) -> uint64
fn eval_binop_uint32(op: BinaryOperator, lhs: uint32, rhs: uint32) -> uint32
fn eval_comparison_int64(op: ComparisonOperator, lhs: int64, rhs: int64) -> bool
fn eval_comparison_int32(op: ComparisonOperator, lhs: int32, rhs: int32) -> bool
fn eval_comparison_uint64(op: ComparisonOperator, lhs: uint64, rhs: uint64) -> bool
fn eval_comparison_uint32(op: ComparisonOperator, lhs: uint32, rhs: uint32) -> bool
fn eval_binop_float(op: BinaryOperator, lhs: float64, rhs: float64) -> float64
fn eval_comparison_float(op: ComparisonOperator, lhs: float64, rhs: float64) -> bool
fn eval_bitop_int64(op: BitOperator, lhs: int64, rhs: int64) -> int64
fn eval_bitop_int32(op: BitOperator, lhs: int32, rhs: int32) -> int32
fn eval_bitop_uint64(op: BitOperator, lhs: uint64, rhs: uint64) -> uint64
fn eval_bitop_uint32(op: BitOperator, lhs: uint32, rhs: uint32) -> uint32
fn eval_comparison(op: ComparisonOperator, lhs: Value, rhs: Value) -> bool
module compiler.webassembly
WebAssembly
===========

WebAssembly support.
pub struct Module
types: List[CompType]imports: List[Import]tags: List[Tag]globals: List[Global]functions: List[Function]exports: List[Export]datas: List[Data]
pub enum NumType
i32i64f32f64
pub struct BlockType
params: List[ValueType]results: List[ValueType]
pub fn one_result_block_type(result_type?: ValueType) -> BlockType
pub fn empty_block_type() -> BlockType
pub enum ValueType
Num(NumType)Ref(RefType)
pub fn nullable_ref_type(heap_type?: HeapType) -> RefType
pub fn ref_type(heap_type?: HeapType) -> RefType
pub fn ref_extern_type() -> RefType
pub struct RefType
nullable: boolheap_type: HeapType
pub enum HeapType
Anyi31FuncExternTypeIdx(int64)
pub enum CompType
Struct(List[FieldType])Array(FieldType)Func(List[ValueType], List[ValueType])
pub struct FieldType
mutable: boolty: StorageType
pub enum StorageType
Value(ValueType)Packed(PackType)
pub enum PackType
i8i16
fn value_type_to_string(ty?: ValueType) -> str
fn num_type_to_string(ty?: NumType) -> str
fn ref_type_to_string(ty?: RefType) -> str
fn heap_type_to_string(heap_type?: HeapType) -> str
fn fuu(label: str, items: List[ValueType], parts2: List[str])
pub fn comp_type_to_string(comp_type?: CompType) -> str
fn field_type_to_string(field_type: FieldType) -> str
fn packed_type_to_string(ty?: PackType) -> str
pub struct Tag
typeidx: int64
pub struct Import
modname: strname: strkind: ExternType
pub enum ExternType
Func(int64)Global(ValueType, bool)Tag(int64)
pub struct Global
mutable: boolty: ValueTypevalue: List[Instruction]
pub struct Function
typeidx: int64locals: List[ValueType]code: List[Instruction]
pub struct Export
name: strkind: ExportKind
pub enum ExportKind
Func(int64)Global(int64)Tag(int64)Memory(int64)Table(int64)
pub struct Data
data: Bytes
pub enum CatchItem
Catch(int64, int64)
pub enum Instruction
ctrl_unreachablectrl_nopdropctrl_block(BlockType)ctrl_loop(BlockType)ctrl_if(BlockType)ctrl_elsectrl_endctrl_br(int64)ctrl_br_if(int64)ctrl_br_tablectrl_returnctrl_call(int64)ctrl_call_ref(int64)ctrl_call_indirect(int64)ctrl_throw(int64)ctrl_try_table(BlockType, List[CatchItem])local_get(int64)local_set(int64)local_tee(int64)global_get(int64)global_set(int64)i32_load(int64, int64)i64_load(int64, int64)f32_load(int64, int64)f64_load(int64, int64)i32_store(int64, int64)i64_store(int64, int64)f32_store(int64, int64)f64_store(int64, int64)i32_const(int64)i64_const(int64)f32_const(float32)f64_const(float64)i32_eqzi32_eqi32_nei32_lt_si32_lt_ui32_gt_si32_gt_ui32_le_si32_le_ui32_ge_si32_ge_ui64_eqzi64_eqi64_nei64_lt_si64_lt_ui64_gt_si64_gt_ui64_le_si64_le_ui64_ge_si64_ge_uf32_eqf32_nef32_ltf32_gtf32_lef32_gef64_eqf64_nef64_ltf64_gtf64_lef64_gei32_clzi32_ctzi32_popcnti32_addi32_subi32_muli32_div_si32_div_ui32_rem_si32_rem_ui32_andi32_ori32_xori32_shli32_shr_si32_shr_ui32_rotli32_rotri64_clzi64_ctzi64_popcnti64_addi64_subi64_muli64_div_si64_div_ui64_rem_si64_rem_ui64_andi64_ori64_xori64_shli64_shr_si64_shr_ui64_rotli64_rotrf32_absf32_negf32_ceilf32_floorf32_truncf32_nearestf32_sqrtf32_addf32_subf32_mulf32_divf32_minf32_maxf32_copysignf64_absf64_negf64_ceilf64_floorf64_truncf64_nearestf64_sqrtf64_addf64_subf64_mulf64_divf64_minf64_maxf64_copysigni32_wrap_i64i32_trunc_f32_si32_trunc_f32_ui32_trunc_f64_si32_trunc_f64_ui64_extend_i32_si64_extend_i32_ui64_trunc_f32_si64_trunc_f32_ui64_trunc_f64_si64_trunc_f64_uf32_convert_i32_sf32_convert_i32_uf32_convert_i64_sf32_convert_i64_uf32_demote_f64f64_convert_i32_sf64_convert_i32_uf64_convert_i64_sf64_convert_i64_uf64_promote_f32i32_reinterpret_f32i64_reinterpret_f64f32_reinterpret_i32f64_reinterpret_i64i32_extend8_si32_extend16_si64_extend8_si64_extend16_si64_extend32_sref_func(int64)ref_null(HeapType)ref_is_nullref_as_non_nullref_eqref_cast(RefType)struct_new(int64)struct_get(int64, int64)struct_set(int64, int64)array_new_fixed(int64, int64)array_new_data(int64, int64)array_new_elem(int64, int64)array_new_default(int64)array_get(int64)array_set(int64)ref_i31i31_get(bool)extern_convert_anyany_convert_extern
class Writer
var m_buffer: ByteArray
pub fn write_u32(value?: int64)
pub fn write_s32(value?: int64)
pub fn write_f32(value?: float32)
pub fn write_f64(value?: float64)
pub fn write_byte(b?: int64)
pub fn write_data(data?: Bytes)
pub fn pack_memarg(align: int64, offset: int64)
pub fn get_bytes() -> Bytes
pub fn pack_block_type(writer: Writer, block_type: BlockType)
pub fn encode(writer: Writer, instruction: Instruction)
fn pack_value_type(writer: Writer, ty?: ValueType)
fn pack_heap_type(writer: Writer, ty?: HeapType)
fn pack_field_type(writer: Writer, field?: FieldType)
fn pack_str(writer: Writer, text?: str)
fn write_header(writer: Writer)
fn write_section(writer: Writer, id: int64, data: Bytes)
Write a section with given ID and data.
fn create_type_section(wasm_module: Module) -> Bytes
Create data for the type section
fn create_import_section(wasm_module: Module) -> Bytes
fn create_func_section(wasm_module: Module) -> Bytes
fn create_global_section(wasm_module: Module) -> Bytes
fn write_export_section(wasm_module: Module) -> Bytes
fn write_code_section(wasm_module: Module) -> Bytes
fn write_code(function: Function) -> Bytes
fn write_data_section(wasm_module: Module) -> Bytes
fn write_data_count_section(wasm_module: Module) -> Bytes
fn write_tag_section(wasm_module: Module) -> Bytes
pub fn to_wasm(wasm_module: Module) -> Bytes
Create binary representation of wasm module.
fn block_type_to_string(block_type: BlockType) -> str
fn catch_to_string(catch: CatchItem) -> str
fn to_string(instruction: Instruction) -> str
pub fn to_wat(wasm_module: Module, out: TextGenerator)
Write webassembly module in text format (WAT)
fn escape_binary(data?: Bytes) -> str