67 lines
1.1 KiB
Go
67 lines
1.1 KiB
Go
package main
|
|
|
|
import "strings"
|
|
|
|
type Code struct {
|
|
Instructions []string
|
|
}
|
|
|
|
func (code *Code) add(instructions ...string) {
|
|
code.Instructions = append(code.Instructions, instructions...)
|
|
}
|
|
|
|
func (code *Code) addAll(other Code) {
|
|
code.Instructions = append(code.Instructions, other.Instructions...)
|
|
}
|
|
|
|
func ofInstruction(instructions ...string) Code {
|
|
return Code{Instructions: instructions}
|
|
}
|
|
|
|
func emptyCode() Code {
|
|
return Code{Instructions: []string{}}
|
|
}
|
|
|
|
func clone(code Code) Code {
|
|
newInstrs := make([]string, len(code.Instructions))
|
|
copy(newInstrs, code.Instructions)
|
|
return Code{Instructions: newInstrs}
|
|
}
|
|
|
|
func concat(code Code, other ...Code) Code {
|
|
newCode := clone(code)
|
|
|
|
for _, o := range other {
|
|
newCode.addAll(o)
|
|
}
|
|
|
|
return newCode
|
|
}
|
|
|
|
func (code Code) clone() Code {
|
|
return clone(code)
|
|
}
|
|
|
|
func (code *Code) isEmpty() bool {
|
|
return len(code.Instructions) == 0
|
|
}
|
|
|
|
func (code *Code) toString() string {
|
|
text := ""
|
|
|
|
indent := 1
|
|
for _, instr := range code.Instructions {
|
|
if instr == "end" {
|
|
indent--
|
|
}
|
|
|
|
text += strings.Repeat("\t", indent) + instr + "\n"
|
|
|
|
if instr == "block" || instr == "loop" {
|
|
indent++
|
|
}
|
|
}
|
|
|
|
return text
|
|
}
|