1. 程式人生 > >迷你型彙編指令直譯器的Java實現

迷你型彙編指令直譯器的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));
	}
}