迷你型汇编指令解释器的Java实现

今天花了1个小时,写了个迷你型的汇编指令解释器,只提供了4种指令:

1. mov指令,复制内容到另一个寄存器

2. inc指令,寄存器内容增长1

3. dec指令,寄存器内容减少1

4. jnz指令,如果非0就跳转

 

程序假定,寄存器的名称都是字母,常量都是整数。

没有考虑异常情况,比如寄存器没有初始化这样的情况。

输入:字符串类型的指令数组

输出:HashMap

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SimpleAssembler {
	public static Map<String, Integer> interpret(String[] program) {
		Map<String, Integer> out = new HashMap<String, Integer>();

		for (int i = 0; i < program.length; i++) {
			String cur = program[i];
			String[] parts = cur.split(" ");
			String type = parts[0];
			String var = "";

			switch (type) {
			case "mov":
				String to = parts[1];
				String from = parts[2];
				if (out.containsKey(from)) {
					out.put(to, out.get(from));
				} else {
					out.put(to, Integer.parseInt(from));
				}
				break;
			case "inc":
				var = parts[1];
				out.put(var, out.get(var) + 1);
				break;
			case "dec":
				var = parts[1];
				out.put(var, out.get(var) - 1);
				break;
			case "jnz":
				var = parts[1];
				int offset = Integer.parseInt(parts[2]);
				Integer val = out.get(var);
				if (val == null || val != 0) {
					i += offset - 1;
				}
				break;
			}
		}
		return out;
	}

	public static void main(String[] args) {
		System.out.println("处理指令:");
		String[] src = new String[] { "mov a 5", "inc a", "dec a", "dec a", "jnz a -1", "inc a" };
		System.out.println(Arrays.toString(src));
		System.out.println("输出结果:");
		System.out.println(SimpleAssembler.interpret(src));
	}
}
点赞