umx_asm

UMX virtual machine assembly compiler
git clone git://bsandro.tech/umx_asm
Log | Files | Refs | README | LICENSE

commit c18c0ebee369e7eaa529ff7bb44e61a5099e9020
parent 03811c37db143d72e471ffd7dc178d1b965c1b7e
Author: bsandro <email@bsandro.tech>
Date:   Wed,  6 Jul 2022 02:09:17 +0300

Cleanup and tiny improvements:
- new DEBUG environment variable; set to 1 to enable debug data printing
- assembler code lines consisting only of whitespaces and comments are ignored
- predefined strings (file extensions and stuff) are now constants.

Diffstat:
Mmain.go | 34++++++++++++++++++++++++----------
Msample.ums | 8++++----
2 files changed, 28 insertions(+), 14 deletions(-)

diff --git a/main.go b/main.go @@ -12,13 +12,16 @@ import ( "umx_asm/asm" ) +const commentSym = ";" const allowedExt = ".ums" +const compileExt = ".um" func main() { re := regexp.MustCompile(`[a-zA-Z0-9]+`) if len(os.Args) < 2 { log.Fatal("no assembly file supplied") } + isDebug := os.Getenv("DEBUG") == "1" filename := os.Args[1] if filepath.Ext(filename) != allowedExt { log.Fatal(fmt.Sprintf("only files with %s extension are supported", allowedExt)) @@ -32,29 +35,40 @@ func main() { scanner := bufio.NewScanner(file) var bytecode []byte for scanner.Scan() { - str, _, _ := strings.Cut(scanner.Text(), ";") + str, _, _ := strings.Cut(scanner.Text(), commentSym) + str = strings.TrimSpace(str) if len(str) > 0 { ins := asm.NewInstruction(re.FindAllString(str, -1)) - fmt.Println(ins.String()) - fmt.Printf("%.32b\n", ins.Pack()) buf := make([]byte, 4) binary.BigEndian.PutUint32(buf, ins.Pack()) bytecode = append(bytecode, buf...) + + if isDebug { + fmt.Println(ins.String()) + fmt.Printf("%.32b\n", ins.Pack()) + } } } if err := scanner.Err(); err != nil { log.Fatal(err) } - fmt.Printf("code of %d bytes\n", len(bytecode)) - for i, b := range bytecode { - fmt.Printf("%.8b", b) - if (i+1)%4 == 0 { - fmt.Printf("\n") - } + fmt.Printf("compiled size: %d bytes\n", len(bytecode)) + if isDebug { + printDebugBytecode(&bytecode) } // dump into file - newfilename := strings.TrimSuffix(filename, allowedExt) + ".um" + newfilename := strings.TrimSuffix(filename, allowedExt) + compileExt if err := os.WriteFile(newfilename, bytecode, 0660); err != nil { log.Fatal(err) } + fmt.Printf("%s -> %s\n", filename, newfilename) +} + +func printDebugBytecode(bytecode *[]byte) { + for i, b := range *bytecode { + fmt.Printf("%.8b", b) + if (i+1)%4 == 0 { + fmt.Printf("\n") + } + } } diff --git a/sample.ums b/sample.ums @@ -5,10 +5,10 @@ ;arri 1 8 15 ;orth 5 493028 -orth 1 97 -orth 2 98 -orth 3 99 -orth 4 10 +orth 1 97 ; a +orth 2 98 ; b +orth 3 99 ; c +orth 4 10 ; LF outp 1 outp 2 outp 3