summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v2/StreamEngine.java
blob: 39bbc0db26ee770b5a239d1e7afff174af49f182 (plain)
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
package bjc.dicelang.v2;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;
import bjc.utils.esodata.SingleTape;
import bjc.utils.esodata.Tape;

public class StreamEngine {
	private DiceLangEngine eng;

	private Tape<IList<String>> streams;
	private IList<String>       currStream;

	public StreamEngine(DiceLangEngine engine) {
		eng = engine;
	}

	private void init() {
		streams = new SingleTape<>();

		currStream = new FunctionalList<>();
		streams.insertBefore(currStream);
	}

	public boolean doStreams(String[] toks, IList<String> dest) {
		init();

		for(String tk : toks) {
			if(tk.startsWith("{@S")) {
				if(!processCommand(tk)) return false;
			} else {
				currStream.add(tk);
			}
		}

		for(String tk : currStream) {
			dest.add(tk);
		}

		return true;
	}

	private boolean processCommand(String tk) {
		char[] comms = null;

		if(tk.length() > 5) {
			comms = tk.substring(3, tk.length() - 1).toCharArray();
		} else {
			comms = new char[1];
			comms[0] = tk.charAt(3);
		}

		for(char comm : comms) {
			switch(comm) {
				case '+':
					streams.insertAfter(new FunctionalList<>());
					break;
				case '>':
					if(!streams.right()) {
						System.out.println("\tERROR: Attempted to switch to non-existent stream");
						return false;
					}

					currStream = streams.item();
					break;
				case '<':
					if(!streams.left()) {
						System.out.println("\tERROR: Attempted to switch to non-existent stream");
						return false;
					}

					currStream = streams.item();
					break;
				case '-':
					if(streams.size() == 1) {
						System.out.println("\tERROR: Cannot delete last stream");
						return false;
					} else {
						streams.remove();
						currStream = streams.item();
					}
					break;
				default:
					System.out.println("\tERROR: Unknown stream control command: " + tk);
					return false;
			}
		}

		return true;
	}
}