Example #1
0
func newLoC(input string, sourceIndex int) *LoC {
	input = translation.TrimBlanks(translation.TrimComment(input))
	loc := new(LoC)
	loc.input = input
	loc.isLabel = strings.HasPrefix(input, "(") && strings.HasSuffix(input, ")")
	loc.isAInstruction = strings.HasPrefix(input, "@")
	loc.isCInstruction = !loc.isLabel && !loc.isAInstruction && input != ""
	loc.isRedundant = !loc.isLabel && !loc.isAInstruction && !loc.isCInstruction
	loc.sourceIndex = sourceIndex
	if loc.isAInstruction || loc.isCInstruction {
		loc.targetIndex = instructionCount
		instructionCount++
	} else {
		loc.targetIndex = -1
	}
	return loc
}
Example #2
0
func translateSingleFile(input string) (output string) {
	lines := strings.Split(input, "\n")
	for _, line := range lines {
		trimmedLine := translation.TrimComment(line)
		if trimmedLine == "" {
			continue
		} else {
			tokens := tokenize(trimmedLine)
			switch tokens[0] {
			case "push":
				output += "//push\n"
				output += push(tokens[1], tokens[2])
			case "pop":
				output += "//pop\n"
				output += pop(tokens[1], tokens[2])
			case "neg":
				output += "//neg\n"
				output += unaryComputation("-")
			case "not":
				output += "//not\n"
				output += unaryComputation("!")
			case "add":
				output += "//add\n"
				output += generateBinaryComputation("+")
			case "sub":
				output += "//sub\n"
				output += generateBinaryComputation("-")
			case "and":
				output += "//and\n"
				output += generateBinaryComputation("&")
			case "or":
				output += "//or\n"
				output += generateBinaryComputation("|")
			case "eq":
				output += "//eq\n"
				output += comparison("JEQ")
			case "lt":
				output += "//lt\n"
				output += comparison("JLT")
			case "gt":
				output += "//gt\n"
				output += comparison("JGT")
			case "label":
				output += label(tokens[1])
			case "goto":
				output += "//goto\n"
				output += unconditionalGoto(tokens[1])
			case "if-goto":
				output += "//if-goto\n"
				output += ifGoto(tokens[1])
			case "call":
				output += "//call\n"
				output += call(tokens[1], tokens[2])
			case "return":
				output += "//return\n"
				output += returnStatment()
			case "function":
				output += "//function\n"
				output += function(tokens[1], tokens[2])
			default:
				panic("unknown operation: " + tokens[0])
			}
		}
	}
	output += "(END)\n"
	output += "@END\n"
	output += "D;JMP\n"
	return
}