egg

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

tokenizer.go (5778B)


      1 package assembler
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"strconv"
      7 	"strings"
      8 )
      9 
     10 // Adds some specific bytes. Like a literal but easier with numbers. The size
     11 // argument shall be 1, 2, 4 or 8.
     12 func bitsDirective(fileName *string, lineNum int, args *string, size int, tokens *[]Token) error {
     13 	*args = strings.TrimSpace(*args)
     14 	if len(*args) == 0 {
     15 		return fmt.Errorf(InterCtx.Get("%v:%v: Expected literal bytes after bits directive"), *fileName, lineNum)
     16 	}
     17 
     18 	bitsize := size * 8
     19 
     20 	argsSlice := strings.Split(*args, " ")
     21 	literal := make([]byte, size*len(argsSlice))
     22 	for i, arg := range argsSlice {
     23 		n, err := strconv.ParseUint(arg, 0, bitsize)
     24 		if err != nil {
     25 			return fmt.Errorf(InterCtx.Get("%v:%v: Cannot convert %v to a %v bits number"), *fileName, lineNum, arg, bitsize)
     26 		}
     27 
     28 		for j := 0; j < size; j++ {
     29 			literal[i*size+j] = byte(n)
     30 			n = n >> 8
     31 		}
     32 	}
     33 
     34 	*tokens = append(*tokens, Token{
     35 		Line:  lineNum,
     36 		File:  fileName,
     37 		Type:  TOKEN_LITERAL,
     38 		Value: literal,
     39 	})
     40 
     41 	return nil
     42 }
     43 
     44 // Creates an empty literal with the number in *args as the size (in bytes).
     45 func spaceDirective(fileName *string, lineNum int, args *string, tokens *[]Token) error {
     46 	if len(*args) == 0 {
     47 		return fmt.Errorf(InterCtx.Get("%v:%v: Expected a number of bytes after space directive"), *fileName, lineNum)
     48 	}
     49 	n, err := strconv.ParseUint(*args, 0, 64)
     50 	if err != nil {
     51 		return fmt.Errorf(InterCtx.Get("%v:%v: Cannot create space: Cannot parse %v to number: %v"), *fileName, lineNum, *args, err)
     52 	}
     53 	*tokens = append(*tokens, Token{
     54 		Line:  lineNum,
     55 		File:  fileName,
     56 		Type:  TOKEN_LITERAL,
     57 		Value: make([]byte, n),
     58 	})
     59 
     60 	return nil
     61 }
     62 
     63 func getHexNumber(r rune) (uint8, error) {
     64 	if 0x30 <= r && r <= 0x39 {
     65 		return uint8(r - 0x30), nil
     66 	} else if 0x41 <= r && r <= 0x46 {
     67 		return uint8(r - 0x37), nil
     68 	} else if 0x61 <= r && r <= 0x66 {
     69 		return uint8(r - 0x57), nil
     70 	} else {
     71 		return 0, errors.New("malformed hex number")
     72 	}
     73 }
     74 
     75 // Line shall already be trimmed so the function works both with .literal and #.
     76 // Parses everything cleanly excepts that any % followed by a two-digit hex
     77 // number (e.g., %FA) in substituted by it's own value. Use %% for a literal %.
     78 // Trailing % are also inserted.
     79 func parseLiteral(fileName *string, line *string, lineNum int, tokens *[]Token) {
     80 	var b strings.Builder
     81 	lit := *line
     82 	i := 0
     83 	for i < len(lit) {
     84 		if lit[i] == '%' {
     85 			if i+1 < len(lit) && lit[i+1] == '%' {
     86 				b.WriteRune('%')
     87 				i += 2
     88 			} else if i+2 < len(lit) {
     89 				b2, err := getHexNumber(rune(lit[i+1]))
     90 				if err != nil {
     91 					b.WriteRune('%')
     92 					i++
     93 					continue
     94 				}
     95 				b1, err := getHexNumber(rune(lit[i+2]))
     96 				if err != nil {
     97 					b.WriteRune('%')
     98 					i++
     99 					continue
    100 				}
    101 				b.WriteRune(rune(b1 | (b2 << 4)))
    102 				i += 3
    103 			} else {
    104 				b.WriteRune('%')
    105 				i++
    106 			}
    107 		} else {
    108 			b.WriteRune(rune(lit[i]))
    109 			i++
    110 		}
    111 	}
    112 
    113 	*tokens = append(*tokens, Token{
    114 		File:  fileName,
    115 		Line:  lineNum,
    116 		Type:  TOKEN_LITERAL,
    117 		Value: []byte(b.String()),
    118 	})
    119 }
    120 
    121 // Line shall already be trimmed.
    122 func parseDirective(fileName *string, line *string, lineNum int, tokens *[]Token) error {
    123 	if len(*line) == 0 {
    124 		return fmt.Errorf(InterCtx.Get("%v:%v: Expected a directive name"), *fileName, lineNum)
    125 	}
    126 
    127 	name, arg, _ := strings.Cut(*line, " ")
    128 	switch name {
    129 	case "include":
    130 		file := strings.TrimSpace(arg)
    131 		if len(file) == 0 {
    132 			return fmt.Errorf(InterCtx.Get("%v:%v: Expected file name to include"), *fileName, lineNum)
    133 		}
    134 		return Tokenize(file, tokens)
    135 	case "literal":
    136 		lit := strings.TrimSpace(arg)
    137 		if len(lit) == 0 {
    138 			return fmt.Errorf(InterCtx.Get("%v:%v: Expected literal content"), *fileName, lineNum)
    139 		}
    140 		parseLiteral(fileName, &lit, lineNum, tokens)
    141 		return nil
    142 	case "bits8":
    143 		return bitsDirective(fileName, lineNum, &arg, 1, tokens)
    144 	case "bits16":
    145 		return bitsDirective(fileName, lineNum, &arg, 2, tokens)
    146 	case "bits32":
    147 		return bitsDirective(fileName, lineNum, &arg, 4, tokens)
    148 	case "bits64":
    149 		return bitsDirective(fileName, lineNum, &arg, 8, tokens)
    150 	case "space":
    151 		return spaceDirective(fileName, lineNum, &arg, tokens)
    152 	}
    153 
    154 	return fmt.Errorf(InterCtx.Get("%v:%v: Unknown directive %v"), *fileName, lineNum, name)
    155 }
    156 
    157 func parseInstruction(fileName *string, line *string, lineNum int, tokens *[]Token) {
    158 	*line = strings.TrimSpace(*line)
    159 	mnemonic, args, hasMne := strings.Cut(*line, " ")
    160 	*tokens = append(*tokens, Token{
    161 		Line:  lineNum,
    162 		File:  fileName,
    163 		Type:  TOKEN_INSTRUCTION,
    164 		Value: []byte(mnemonic),
    165 	})
    166 
    167 	if hasMne {
    168 		for _, arg := range strings.Split(args, ",") {
    169 			arg = strings.TrimSpace(arg)
    170 			*tokens = append(*tokens, Token{
    171 				Line:  lineNum,
    172 				File:  fileName,
    173 				Type:  TOKEN_ARG,
    174 				Value: []byte(arg),
    175 			})
    176 		}
    177 	}
    178 }
    179 
    180 func parseLine(fileName *string, line *string, lineNum int, tokens *[]Token) error {
    181 	// This uncomments and trims the line.
    182 	*line, _, _ = strings.Cut(*line, ";")
    183 	*line = strings.TrimSpace(*line)
    184 	if len(*line) == 0 {
    185 		return nil
    186 	}
    187 
    188 	// If a literal.
    189 	if (*line)[0] == '#' {
    190 		if len(*line) <= 1 {
    191 			return fmt.Errorf(InterCtx.Get("%v:%v: Expected literal content"), *fileName, lineNum)
    192 		}
    193 		*line = (*line)[1:]
    194 		parseLiteral(fileName, line, lineNum, tokens)
    195 		return nil
    196 	}
    197 	// If a directive.
    198 	if (*line)[0] == '.' {
    199 		*line = (*line)[1:]
    200 		*line = strings.TrimSpace(*line)
    201 		return parseDirective(fileName, line, lineNum, tokens)
    202 	}
    203 
    204 	// Now we check if there's a label declared there.
    205 	beg, end, hasLabel := strings.Cut(*line, ":")
    206 	if hasLabel {
    207 		*tokens = append(*tokens, Token{Line: lineNum,
    208 			File:  fileName,
    209 			Type:  TOKEN_LABEL,
    210 			Value: []byte(strings.Clone(beg)),
    211 		})
    212 		beg = end
    213 	}
    214 
    215 	beg = strings.TrimSpace(beg)
    216 	if len(beg) != 0 {
    217 		// Finally we put an instruction there.
    218 		parseInstruction(fileName, &beg, lineNum, tokens)
    219 	}
    220 
    221 	return nil
    222 }