-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAssemblerInterpreterPartII2.java
356 lines (297 loc) · 8.84 KB
/
AssemblerInterpreterPartII2.java
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <pre>
* This solution is a multi-pass assembler.
*
* This is my verbose solution, which is faster because of less switches.
* I didn't submit this solution because it's too verbose for codewars.
* Instead, I submitted AssemblerInterpreterPartII.java.
* </pre>
*
* @author Jonathan Bradley Whited
* @see https://www.codewars.com/kata/assembler-interpreter-part-ii/java
* @see https://en.wikipedia.org/wiki/Assembly_language
* @see https://en.wikipedia.org/wiki/Assembly_language#Number_of_passes
* @rank 2 kyu
*/
public class AssemblerInterpreterPartII2 {
protected int currInstIndex = 0;
protected Map<String,FuncInst> funcs = new HashMap<>();
protected int gotoIndex = -1;
protected Deque<Integer> gotoIndexStack = new LinkedList<>();
protected boolean hasEnd = false;
protected List<Inst> insts; // Defined in constructor
protected StringBuilder out = new StringBuilder();
protected int prevCmp = 0;
protected Map<String,Integer> regs = new HashMap<>();
public static void main(String[] args) {
// "(5+1)/2 = 3"
// "5! = 120"
// "Term 8 of Fibonacci series is: 21"
// "mod(11, 3) = 2"
// "gcd(81, 153) = 9"
// null
// "2^10 = 1024"
Charset charset = StandardCharsets.UTF_8; // Charset.forName("UTF-8");
String dirname = "data";
String filename = "asm_interp_partii.asm"; // Party?
Path[] paths = new Path[]{Paths.get("..",dirname,filename),Paths.get(dirname,filename)};
for(Path path: paths) {
if(Files.exists(path)) {
try(BufferedReader fin = Files.newBufferedReader(path,charset)) {
String line = null;
StringBuilder prog = new StringBuilder();
while((line = fin.readLine()) != null) {
if(line.equals("---")) {
System.out.println(interpret(prog.toString()));
prog.setLength(0); // Clear/reset
}
else {
prog.append(line).append('\n');
}
}
if(prog.length() > 0) {
System.out.println(interpret(prog.toString()));
}
}
catch(IOException e) {
e.printStackTrace();
}
break;
}
}
}
public static String interpret(final String input) {
return (new AssemblerInterpreterPartII2(input)).run();
}
public AssemblerInterpreterPartII2(final String input) {
String[] lines = input.split("\n+");
insts = new ArrayList<>(lines.length);
for(String line: lines) {
Inst inst = newInst(line);
if(inst != null) { insts.add(inst); }
}
}
public String run() {
for(currInstIndex = 0; currInstIndex < insts.size(); ++currInstIndex) {
Inst inst = insts.get(currInstIndex);
inst.exec();
if(hasEnd) { break; }
if(gotoIndex != -1) {
currInstIndex = gotoIndex;
gotoIndex = -1;
}
}
return hasEnd ? out.toString() : null;
}
public Inst newInst(String line) {
Inst inst = null;
// Blank line or comment?
if((line = line.trim()).isEmpty() || line.charAt(0) == ';') {
return inst;
}
// <instruction> | <single quoted string> | <comma> | <comment>
Matcher matcher = Pattern.compile("[^\\s',;]+|'[^']*'|,|;.*").matcher(line);
List<String> args = new ArrayList<String>(2); // Usually 2
while(matcher.find()) {
String group = matcher.group();
char firstChar = group.charAt(0);
if(firstChar == ';') { break; } // Comment?
if(firstChar == ',') { continue; } // Ignore commas
args.add(group);
}
if(!args.isEmpty()) {
String instName = args.get(0);
if(args.size() == 1 && instName.charAt(instName.length() - 1) == ':') {
inst = new FuncInst();
}
else {
switch(instName) {
case "add": inst = new AddInst(); break;
case "call": inst = new CallInst(); break;
case "cmp": inst = new CmpInst(); break;
case "dec": inst = new DecInst(); break;
case "div": inst = new DivInst(); break;
case "end": inst = new EndInst(); break;
case "inc": inst = new IncInst(); break;
case "je": inst = new JeInst(); break;
case "jg": inst = new JgInst(); break;
case "jge": inst = new JgeInst(); break;
case "jl": inst = new JlInst(); break;
case "jle": inst = new JleInst(); break;
case "jmp": inst = new JmpInst(); break;
case "jne": inst = new JneInst(); break;
case "mov": inst = new MovInst(); break;
case "msg": inst = new MsgInst(); break;
case "mul": inst = new MulInst(); break;
case "ret": inst = new RetInst(); break;
case "sub": inst = new SubInst(); break;
}
}
if(inst != null) {
inst.args = args;
inst.index = currInstIndex++;
inst.init();
}
else {
throw new RuntimeException("Invalid instruction: " + instName);
}
}
return inst;
}
public abstract class Inst {
protected List<String> args;
protected int index;
public abstract void exec();
public void init() {
args.remove(0); // Remove instruction name
}
}
public abstract class NumInst extends Inst {
protected int[] nums;
protected String[] vars;
public void exec() {
for(int i = 0; i < args.size(); ++i) {
String arg = args.get(i);
if(arg.matches("\\d+")) {
nums[i] = Integer.parseInt(arg);
}
else {
nums[i] = regs.getOrDefault(arg,0);
vars[i] = arg;
}
}
}
public void init() {
super.init();
nums = new int[args.size()];
vars = new String[args.size()];
}
public void setVar(int index,int num) {
regs.put(vars[index],nums[index] = num);
}
}
public class AddInst extends NumInst {
public void exec() {
super.exec();
setVar(0,nums[0] + nums[1]);
}
}
public class CallInst extends JmpInst {
public void exec() {
super.exec();
if(isJmp()) { gotoIndexStack.push(currInstIndex); }
}
}
public class CmpInst extends NumInst {
public void exec() {
super.exec();
prevCmp = nums[0] - nums[1];
}
}
public class DecInst extends NumInst {
public void exec() {
super.exec();
setVar(0,--nums[0]);
}
}
public class DivInst extends NumInst {
public void exec() {
super.exec();
setVar(0,nums[0] / nums[1]);
}
}
public class EndInst extends Inst {
public void exec() {
hasEnd = true;
}
}
public class FuncInst extends Inst {
public void init() {
String name = args.get(0);
name = name.substring(0,name.length() - 1);
args.set(0,name);
funcs.put(name,this);
}
public void exec() {}
}
public class IncInst extends NumInst {
public void exec() {
super.exec();
setVar(0,++nums[0]);
}
}
public class JeInst extends JmpInst {
public boolean isJmp() { return prevCmp == 0; }
}
public class JgInst extends JmpInst {
public boolean isJmp() { return prevCmp > 0; }
}
public class JgeInst extends JmpInst {
public boolean isJmp() { return prevCmp >= 0; }
}
public class JlInst extends JmpInst {
public boolean isJmp() { return prevCmp < 0; }
}
public class JleInst extends JmpInst {
public boolean isJmp() { return prevCmp <= 0; }
}
public class JmpInst extends Inst {
public void exec() {
if(isJmp()) {
FuncInst funcInst = funcs.get(args.get(0));
gotoIndex = funcInst.index;
}
}
public boolean isJmp() { return true; }
}
public class JneInst extends JmpInst {
public boolean isJmp() { return prevCmp != 0; }
}
public class MovInst extends NumInst {
public void exec() {
super.exec();
setVar(0,nums[1]);
}
}
public class MsgInst extends Inst {
public void exec() {
for(String arg: args) {
out.append(arg.charAt(0) == '\'' ? arg.substring(1,arg.length() - 1) : regs.get(arg));
}
}
}
public class MulInst extends NumInst {
public void exec() {
super.exec();
setVar(0,nums[0] * nums[1]);
}
}
public class RetInst extends Inst {
public void exec() {
if(!gotoIndexStack.isEmpty()) {
gotoIndex = gotoIndexStack.pop();
}
}
}
public class SubInst extends NumInst {
public void exec() {
super.exec();
setVar(0,nums[0] - nums[1]);
}
}
}