Improved assembler

This commit is contained in:
Eduard Urbach 2023-10-27 22:14:20 +02:00
parent ab48a86ccd
commit a5ba316319
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 22 additions and 8 deletions

4
src/asm/Address.go Normal file
View File

@ -0,0 +1,4 @@
package asm
// Address represents a memory address.
type Address = uint32

View File

@ -6,37 +6,46 @@ import (
// Assembler contains a list of instructions. // Assembler contains a list of instructions.
type Assembler struct { type Assembler struct {
Instructions []Instruction instructions []Instruction
labels map[string]int
} }
// New creates a new assembler. // New creates a new assembler.
func New() *Assembler { func New() *Assembler {
return &Assembler{ return &Assembler{
Instructions: make([]Instruction, 0, 8), instructions: make([]Instruction, 0, 8),
labels: map[string]int{},
} }
} }
// Finalize generates the final machine code. // Finalize generates the final machine code.
func (list *Assembler) Finalize() *Result { func (a *Assembler) Finalize() *Result {
final := Result{} final := Result{}
for _, instr := range list.Instructions { for _, instr := range a.instructions {
instr.Write(&final.Code) instr.Write(&final.Code)
} }
return &final return &final
} }
func (list *Assembler) MoveRegisterNumber(reg register.ID, number uint64) { // AddLabel creates a new label at the current position.
list.Instructions = append(list.Instructions, Instruction{ func (a *Assembler) AddLabel(name string) {
a.labels[name] = len(a.instructions)
}
// MoveRegisterNumber moves a number into the given register.
func (a *Assembler) MoveRegisterNumber(reg register.ID, number uint64) {
a.instructions = append(a.instructions, Instruction{
Mnemonic: MOV, Mnemonic: MOV,
Destination: reg, Destination: reg,
Number: number, Number: number,
}) })
} }
func (list *Assembler) Syscall() { // Syscall executes a kernel function.
list.Instructions = append(list.Instructions, Instruction{ func (a *Assembler) Syscall() {
a.instructions = append(a.instructions, Instruction{
Mnemonic: SYSCALL, Mnemonic: SYSCALL,
}) })
} }

View File

@ -26,6 +26,7 @@ func (x *Instruction) Write(w io.ByteWriter) {
} }
} }
// String returns the assembler representation of the instruction.
func (x *Instruction) String() string { func (x *Instruction) String() string {
switch x.Mnemonic { switch x.Mnemonic {
case MOV: case MOV: