Website Summary Files Commits Branches @commit @diff @stats
path: root / homework / 81319 / bfinterpreter / bf / tokenizer.go
blob: 10a0342ca3c3ba36a31360815388e261cc681ffc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package bf

import (
	"bytes"
	"io"
)

type token int

const (
	unkwn token = iota
	movR
	movL
	incD
	decD
	outD
	inD
	loopS
	loopE
)

func tokenize(symbol string) token {
	switch symbol {
	case ">":
		return movR
	case "<":
		return movL
	case ".":
		return outD
	case ",":
		return inD
	case "+":
		return incD
	case "-":
		return decD
	case "[":
		return loopS
	case "]":
		return loopE
	}

	return 0
}

type tokenizingStream struct {
	reader io.Reader
}

func (s *tokenizingStream) Read(p []byte) (int, error) {
	buffer := make([]byte, len(p))

	count, err := s.reader.Read(buffer)
	if err != nil {
		return 0, err
	}

	for i := 0; i < count; i++ {
		p[i] = byte(tokenize(string(buffer[i])))
	}

	return count, nil
}

func tokenizeInput(input string) []instruction {
	byteBuff := []byte(input)
	reader := bytes.NewReader(byteBuff)
	tokenizingReader := tokenizingStream{
		reader: reader,
	}

	bytesRead := make([]byte, 1)
	instructions := make([]instruction, 0)

	for {
		_, ok := tokenizingReader.Read(bytesRead)
		if ok == io.EOF {
			break
		}
		if ok == nil {
			inst := instruction{
				instructionType: token(bytesRead[0]),
			}

			instructions = append(instructions, inst)
		}
	}

	return instructions
}

func parseInput(instructions []instruction) []instruction {
	stack := make([]instruction, 0)

	for idx, inst := range instructions {
		instructions[idx].idx = uint(idx)

		if inst.instructionType != loopS && inst.instructionType != loopE {
			continue
		}

		if inst.instructionType == loopS {
			inst.idx = uint(idx)
			stack = append(stack, inst)

			continue
		}

		if len(stack) < 1 {
			panic("input data invalid!")
		}

		prevInst := stack[len(stack)-1]
		prevInst.matchingBracketIdx = uint(idx)
		instructions[prevInst.idx] = prevInst

		inst.idx = uint(idx)
		inst.matchingBracketIdx = prevInst.idx
		instructions[idx] = inst

		stack = stack[:len(stack)-1]
	}

	return instructions
}