q/src/build/Build.go

114 lines
2.2 KiB
Go

package build
import (
"bufio"
"os"
"path/filepath"
"strings"
"git.akyoto.dev/cli/q/src/asm"
"git.akyoto.dev/cli/q/src/asm/x64"
"git.akyoto.dev/cli/q/src/directory"
"git.akyoto.dev/cli/q/src/elf"
"git.akyoto.dev/cli/q/src/errors"
"git.akyoto.dev/cli/q/src/log"
"git.akyoto.dev/cli/q/src/register"
"git.akyoto.dev/cli/q/src/syscall"
)
// Build describes a compiler build.
type Build struct {
Name string
Directory string
WriteExecutable bool
}
// New creates a new build.
func New(directory string) *Build {
return &Build{
Name: filepath.Base(directory),
Directory: directory,
WriteExecutable: true,
}
}
// Run parses the input files and generates an executable file.
func (build *Build) Run() error {
err := build.Compile()
if err != nil {
return err
}
if !build.WriteExecutable {
return nil
}
final := asm.Assembler{}
code := &final.Code
data := &final.Data
x64.MoveRegNum32(code, register.Syscall0, syscall.Write)
x64.MoveRegNum32(code, register.Syscall1, 1)
x64.MoveRegNum32(code, register.Syscall2, 0x4000a2)
x64.MoveRegNum32(code, register.Syscall3, 6)
x64.Syscall(code)
x64.MoveRegNum32(code, register.Syscall0, syscall.Exit)
x64.MoveRegNum32(code, register.Syscall1, 0)
x64.Syscall(code)
data.WriteString("Hello\n")
return writeToDisk(build.Executable(), code.Bytes(), data.Bytes())
}
// Compile compiles all the functions.
func (build *Build) Compile() error {
stat, err := os.Stat(build.Directory)
if err != nil {
return err
}
if !stat.IsDir() {
return &errors.InvalidDirectory{Path: build.Directory}
}
directory.Walk(build.Directory, func(file string) {
if !strings.HasSuffix(file, ".q") {
return
}
log.Info.Println(file)
})
return nil
}
// Executable returns the path to the executable.
func (build *Build) Executable() string {
return filepath.Join(build.Directory, build.Name)
}
// writeToDisk writes the executable file to disk.
func writeToDisk(filePath string, code []byte, data []byte) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
buffer := bufio.NewWriter(file)
executable := elf.New(code, data)
executable.Write(buffer)
buffer.Flush()
err = file.Close()
if err != nil {
return err
}
return os.Chmod(filePath, 0755)
}