egg

Multi-architecture emulator.
Log | Files | Refs | README | LICENSE

assembler.go (6504B)


      1 // Package assembler implements a library for creating assemblers for the EGG
      2 // emulator.
      3 package assembler
      4 
      5 import (
      6 	"bufio"
      7 	"fmt"
      8 	"os"
      9 
     10 	"github.com/gboncoffee/intergo"
     11 )
     12 
     13 const (
     14 	TOKEN_LABEL = iota
     15 	TOKEN_INSTRUCTION
     16 	TOKEN_ARG
     17 	TOKEN_LITERAL
     18 )
     19 
     20 // This variable is a workaround between circular imports: ideally, we would
     21 // just use InterCtx, but we cannot import machine here as machine
     22 // already imports us. The main function will point this to the machine one.
     23 // Please don't touch.
     24 var InterCtx *intergo.InterContext
     25 
     26 // Can be a label, an instruction, an argument or a literal. All directives are
     27 // resolved in the tokenizer stage.
     28 type Token struct {
     29 	File  *string
     30 	Value []byte
     31 	Line  int
     32 	Type  int
     33 }
     34 
     35 // This token is specifically an instruction. An array of these is passed to the
     36 // debugger.
     37 type DebuggerToken struct {
     38 	Instruction string
     39 	Label       string
     40 	File        *string
     41 	Args        []string
     42 	Address     uint64
     43 	Line        int
     44 }
     45 
     46 // This kind of token can be only instructions and literals (only instructions
     47 // have arguments). Labels and arguments are already "resolved". The Reserved
     48 // field is reserved for architecture-specific use (example: storing information
     49 // regarding the addressing mode in 6502).
     50 type ResolvedToken struct {
     51 	File     *string
     52 	Args     []uint64
     53 	Value    []byte
     54 	Address  uint64
     55 	Line     int
     56 	Type     int
     57 	Reserved uintptr
     58 }
     59 
     60 // For intermediate reasons.
     61 type Instruction struct {
     62 	Mnemonic string
     63 	File     *string
     64 	Args     []string
     65 	Size     uint64
     66 	Line     int
     67 	Reserved uintptr
     68 }
     69 
     70 // If the token is not a label, uses the provided function to translate it.
     71 func TranslateArgument(arg string, labels map[string]uint64, translateArg func(string) (uint64, error)) (uint64, error) {
     72 	value, hasLabel := labels[arg]
     73 	if !hasLabel {
     74 		var err error
     75 		value, err = translateArg(arg)
     76 		if err != nil {
     77 			return 0, err
     78 		}
     79 	}
     80 
     81 	return value, nil
     82 }
     83 
     84 // "Resolve" tokens. The process callback can be used for basically anything,
     85 // but it MUST set the Size field. For example, it may remove parenthesis from
     86 // an argument when the architecture accepts them, and set something with the
     87 // Reserved field informing that the addressing mode of the instruction is XYZ.
     88 //
     89 // translateArg is passed directly to TranslateArgument.
     90 func ResolveTokens(tokens []Token, process func(*Instruction) error, translateArg func(string) (uint64, error)) ([]ResolvedToken, []DebuggerToken, error) {
     91 	resolvedTokens := []ResolvedToken{}
     92 	labels := make(map[string]uint64)
     93 	reverseLabels := make(map[uint64]string)
     94 	address := uint64(0)
     95 
     96 	// We use this so we can process everything and only after translate
     97 	// the arguments.
     98 	arguments := make(map[uint64][]string)
     99 
    100 	for i := 0; i < len(tokens); i++ {
    101 		token := &tokens[i]
    102 		switch token.Type {
    103 		// Token before instruction.
    104 		case TOKEN_ARG:
    105 			panic(InterCtx.Get("If you're reading this, there's a bug in the emulator. Please fill an issue at https://github.com/gboncoffee/egg reporting the bug with the Assembly you're trying to run and command line arguments you used to run EGG."))
    106 		case TOKEN_LABEL:
    107 			labels[string(token.Value)] = address
    108 			reverseLabels[address] = string(token.Value)
    109 		case TOKEN_LITERAL:
    110 			resolvedTokens = append(resolvedTokens, ResolvedToken{
    111 				Line:    token.Line,
    112 				File:    token.File,
    113 				Type:    TOKEN_LITERAL,
    114 				Address: address,
    115 				Value:   token.Value,
    116 			})
    117 			address += uint64(len(token.Value))
    118 		case TOKEN_INSTRUCTION:
    119 			instruction := Instruction{
    120 				Line:     token.Line,
    121 				File:     token.File,
    122 				Mnemonic: string(token.Value),
    123 				Args:     []string{},
    124 			}
    125 
    126 			// Squeeze all arguments into the Intruction variable.
    127 			i++
    128 			for i < len(tokens) && tokens[i].Type == TOKEN_ARG {
    129 				instruction.Args = append(instruction.Args, string(tokens[i].Value))
    130 				i++
    131 			}
    132 			i--
    133 
    134 			if err := process(&instruction); err != nil {
    135 				return nil, nil, err
    136 			}
    137 
    138 			// Finally create a proper token and append it. The arguments are
    139 			// going to be treated only after we finish with all labels, of
    140 			// course.
    141 			resolvedTokens = append(resolvedTokens, ResolvedToken{
    142 				Line:     instruction.Line,
    143 				File:     instruction.File,
    144 				Type:     TOKEN_INSTRUCTION,
    145 				Value:    []byte(instruction.Mnemonic),
    146 				Address:  address,
    147 				Reserved: instruction.Reserved,
    148 			})
    149 
    150 			arguments[address] = instruction.Args
    151 			address += instruction.Size
    152 		}
    153 	}
    154 
    155 	// Now that we have all labels, we can treat the arguments. We also create
    156 	// the debugger tokens.
    157 	debuggerTokens := []DebuggerToken{}
    158 	for i := 0; i < len(resolvedTokens); i++ {
    159 		token := &resolvedTokens[i]
    160 		if token.Type == TOKEN_INSTRUCTION {
    161 			args, ok := arguments[token.Address]
    162 			if !ok {
    163 				panic(InterCtx.Get("If you're reading this, there's a bug in the emulator. Please fill an issue at https://github.com/gboncoffee/egg reporting the bug with the Assembly you're trying to run and command line arguments you used to run EGG."))
    164 			}
    165 
    166 			debuggerTokens = append(debuggerTokens, DebuggerToken{
    167 				Line:        token.Line,
    168 				File:        token.File,
    169 				Instruction: string(token.Value),
    170 				Args:        args,
    171 				Address:     token.Address,
    172 				Label:       reverseLabels[token.Address],
    173 			})
    174 
    175 			for _, arg := range args {
    176 				result, err := TranslateArgument(arg, labels, translateArg)
    177 				if err != nil {
    178 					return nil, nil, fmt.Errorf(InterCtx.Get("%v:%v: Error on argument translation: %v"), *token.File, token.Line, err)
    179 				}
    180 				token.Args = append(token.Args, result)
    181 			}
    182 		}
    183 	}
    184 
    185 	return resolvedTokens, debuggerTokens, nil
    186 }
    187 
    188 // Tokenize recursively (as of .include directives) creates a Token array from
    189 // file names. I.e., it opens and reads the passed file, opening and reading
    190 // other files when reaching a .include.
    191 func Tokenize(fileName string, tokens *[]Token) error {
    192 	// Private functions used here are defined in tokenizer.go for the sake
    193 	// of organization.
    194 
    195 	file, err := os.Open(fileName)
    196 	if err != nil {
    197 		return fmt.Errorf(InterCtx.Get("couldn't open file: %v"), err)
    198 	}
    199 	defer func(){
    200 		_ = file.Close()
    201 	}()
    202 
    203 	scanner := bufio.NewScanner(file)
    204 
    205 	// This reads line by line. The i is necessary so we actually knows where
    206 	// we're in the file.
    207 	i := 1
    208 	for scanner.Scan() {
    209 		line := scanner.Text()
    210 		if err := scanner.Err(); err != nil {
    211 			return fmt.Errorf(InterCtx.Get("error reading file %v: %v"), fileName, err)
    212 		}
    213 
    214 		err = parseLine(&fileName, &line, i, tokens)
    215 		if err != nil {
    216 			return err
    217 		}
    218 
    219 		i++
    220 	}
    221 
    222 	return nil
    223 }