#!/usr/bin/env ruby

# ----------------------------------------------------------------------
# Project: JCPU, a portable 8-bit RISC CPU written in VHDL
# This file: A small assembler for the JCPU

# Copyright (C) 2007 J. Ahrensfeld

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

# For questions and ideas, please contact the author at jens@jayfield.org

# ---------------------------------------------------------------------

arg = $*
MAX_SIZE_ROM = 1024
PROJECT_NAME = arg.to_s.gsub(/\..*/, "")
ENTITY_NAME = "rom"
ENTITY_DATA_TYPE = "inst_t"
ENTITY_ADDR_TYPE = "inst_addr_t"
OPC_LIST_NAME = "/cygdrive/w/vhdl/lib/CPUs/JCpu/tools/opc.list"

# --------------------------------------------------------
# Open file
# --------------------------------------------------------
filename = arg.to_s
if !File.exists?(filename)
	STDERR.puts "#{filename} does not exist"
	exit 1
end

# --------------------------------------------------------
# Pass 1
# --------------------------------------------------------
lc = 0	# Line counter
pc = 0	# Program counter
chip_dc = [0,0,0,0]	# chip data counter
xmem_dc = 0	# xmem data counter
curr_segment = "UNDEF";
page = 0

label_list=[[],[]]
instr_list=[nil]
file = File.open(filename, "r")
file.each do |raw_line|
	lc += 1

	# Make all upper case
	iline = "#{raw_line}".strip.upcase
	
	# Remove comments
	iline = iline.gsub(/;.*/, "")
	
	# Split instruction at spaces
	iline_member = iline.split(" ")

	if iline_member[0] == nil
		next
	end	
	
	mc = 0;
	label = nil
	clean_line = nil
	if (iline_member[0] =~ /\w+:/)
		mc += 1
		label = iline_member[0].delete(":")
		if label_list.rindex(label) != nil
			STDERR.puts format("Error in line %d: Duplicate label \"%s\" found", lc, label)
			exit 1
		end
	end
	
	case iline_member[mc]
	when nil
		value = format("0x%3.3X",pc)
	when "EQU"
		if 0 == (iline_member[mc+1] =~ /\d+/)
			value = format("0x%2.2X",eval(iline_member[mc+1..iline_member.nitems].to_s))
		else 	
			value = iline_member[mc+1]
		end 	
	when "ORG", "CODE"
		pc = eval(iline_member[mc+1..iline_member.nitems].to_s)
		value = format("0x%3.3X",pc)
	when "CDATA", "CMEM"
		if iline_member[mc+1] == nil
			STDERR.puts format("Error in line %d: CDATA needs argument!", lc)
			exit 1
		end 	
		curr_segment = "CMEM";
		page = iline_member[mc+1].to_i(16)
	when "XDATA", "XMEM"
		curr_segment = "XMEM";
	when "DC"
		len = 0;
		iline.split("DC")[1].delete("0x").scan(/[0-9A-Fa-f]+/).each do |byte| 
			len += 1
		end	
		if curr_segment == "CMEM"
			STDERR.puts format("Error in line %d: CDATA cannot be initialized!", lc)
			exit 1
		else
			value = format("0x%2.2X",xmem_dc)
			puts format("Found DC defining %d bytes at 0x%4.4X in %s", len, xmem_dc, curr_segment);
			xmem_dc += len
		end	
	when "DB"
		len = iline_member[mc+1].to_i
		if curr_segment == "CMEM"
			value = format("0x%2.2X",chip_dc[page])
			puts format("Found DB reserving %d bytes at 0x%4.4X in %s(%d)", len, chip_dc[page], curr_segment, page);
			chip_dc[page] += len
		else
			value = format("0x%2.2X",xmem_dc)
			puts format("Found DB reserving %d bytes at 0x%4.4X in %s", len, xmem_dc, curr_segment);
			xmem_dc += len
		end	
	else
		op_line = iline_member[mc+1..iline_member.nitems].to_s
		value = format("0x%3.3X",pc)
		opc = iline_member[mc]
		if iline_member[mc+1] != nil
			op1 = op_line.gsub(/,+.*$/, "")
		end	
		if iline_member[mc+2] != nil
			op2 = op_line.scan(/,.+$/).to_s.delete(", ")
		end	
		if instr_list[pc] == nil
			instr_list[pc] = [lc, pc, opc , op1 , op2]
			pc += 1
		else
			STDERR.puts format("Error in line %d: Overlapping sections at %3.3X", lc, pc)
			exit 1
		end
	end;	

	# Push labels
	if label	
		label_list = label_list + [label, value]
	end
end
file.close

# --------------------------------------------------------
def instr(opcode)
	return format("\"%6.6B\" & X\"%3.3X\"",opcode ,0)
end	

def tcl_bits(pc, opcode)
	return format("%10.10B%6.6B%12.12B",pc, opcode ,0)
end

def instr_k(opcode, k)
	return format("\"%6.6B\" & X\"%3.3X\"",opcode ,k)
end	

def tcl_bits_k(pc, opcode, k)
	return format("%10.10B%6.6B%12.12B",pc, opcode ,k)
end

def instr_r(opcode, r)
	return format("\"%6.6B\" & X\"%2.2X%X\"",opcode ,0, r)
end	

def tcl_bits_r(pc, opcode, r)
	return format("%10.10B%6.6B%8.8B%4.4B",pc, opcode ,0,r)
end

def instr_kr(opcode, k, r)
	return format("\"%6.6B\" & X\"%2.2X%X\"",opcode,k, r)
end	

def tcl_bits_kr(pc, opcode, k, r)
	return format("%10.10B%6.6B%8.8B%4.4B",pc, opcode, k, r)
end

def instr_rk(opcode, r, k)
	return format("\"%6.6B\" & X\"%2.2X%X\"",opcode,k, r)
end	

def tcl_bits_rk(pc, opcode, r, k)
	return format("%10.10B%6.6B%8.8B%4.4B",pc, opcode, k, r)
end

def instr_rr(opcode, ra, rb)
	return format("\"%6.6B\" & X\"%X%X%X\"",opcode,0, rb, ra)
end	

def tcl_bits_rr(pc, opcode, ra, rb)
	return format("%10.10B%6.6B%4.4B%4.4B%4.4B",pc, opcode, 0, rb, ra)
end

# --------------------------------------------------------
# Read mnemonic set
# --------------------------------------------------------
filename = OPC_LIST_NAME
if !File.exists?(filename)
	STDERR.puts "#{filename} does not exist"
	exit 1
end

mnemo_list = []
num_opcodes = 0
file = File.open(filename, "r")
file.each do |raw_line|
	mnemo_list[num_opcodes] = raw_line.split(" ")[1]
	num_opcodes += 1
end

# --------------------------------------------------------
# Pass 2
# --------------------------------------------------------
pc = 0
opc_start = 2
num_errors = 0
vhdl_trans_list = [nil]
vhdl_comment_list = [nil]
vhdl_tcl_list = [nil]
instr_list.each do |instruct|
		
	# puts instruct
	if instruct == nil
		vhdl_trans_list[pc] = format("\"%6.6B\" & X\"%3.3X\"",0 ,0)
		vhdl_comment_list[pc] = format("0x%3.3X:", pc)
		vhdl_tcl_list[pc] = tcl_bits(pc, 0)
		pc += 1
		next
	end
		
	# determine arglen of instruction
	ilen = 0
	if instruct[opc_start+1] == nil
		arglen = 0
	elsif instruct[opc_start+2] == nil
		arglen = 1
	elsif instruct[opc_start+3] == nil
		arglen = 2
	end	
	
	# Symbol substitution
	error = false
	for i in (1..3)
		subst_pos = opc_start+i
		if instruct[subst_pos] == nil
			next
		end	
		expr_token = ""
		expr_subst = nil
		is_direct = true;
		
#		instruct[subst_pos] = instruct[subst_pos].delete(" ")

		# checks R0 .. R16, Mnemonics
		instr_str = instruct[subst_pos]
		if 0 == (instr_str =~ /\(.+\)/)
			instr_str = instr_str.delete("()")
			is_direct = false;
		end	

		expr_token = instr_str.split(/\+|\-|\*|\//)[0]
		if (0 != (expr_token =~ /R[0-9]+/)) && (0 != (expr_token =~ /\d+/))
			idx = label_list.rindex(expr_token)
			if idx != nil
				expr_subst = label_list[idx+1]
				instruct[subst_pos] = instruct[subst_pos].gsub(expr_token, expr_subst)
			else
				STDERR.puts format("Error in line %d: Symbol \"%s\" not found", instruct[0], expr_token)
				error = true
			end
		end	
		
		if expr_subst != nil
			if 0 == (expr_subst =~ /\d+/) 
				if is_direct == true
					instruct[subst_pos] = format("0x%2.2X", eval(instruct[subst_pos]))
				else
					instruct[subst_pos] = format("(0x%2.2X)", eval(instruct[subst_pos]))
				end	
			else
				if 0 != (expr_subst =~ /R[0-9]+/)
					STDERR.puts format("Error in line %d: Invalid expression \"%s\"", instruct[0], expr_subst)
					error = true
				end
			end
		end	
	end
	
	# Parse operands
	reg = [0,0]
	kk = 0
	format = instruct[opc_start]
	for i in (0..1)
		if instruct[opc_start+i+1] =~ Regexp.new("R[0-9]+")
			# Check indirect addressing
			reg[i] = instruct[opc_start+i+1].delete("R()").to_i
			format += "|R"
			if reg[i] > 15
				STDERR.puts format("Error in line %d: Invalid register \"R%d\" specified", instruct[0], reg[i])
				error = true
			end
		else
			if instruct[opc_start+i+1] =~ Regexp.new("[0-9A-F]+")
				kk = instruct[opc_start+i+1].delete("()").to_i(16)
				format += "|K"
			end
		end
		if instruct[opc_start+i+1] =~ Regexp.new("\\(.+\\)")
			format += "i";
		end
	end 
	
	# Output instruction
	opcode = mnemo_list.rindex(format).to_i
	mnemo = instruct[2];

	case format
	when "NOP", "HALT", "RET", "RETI"
		vhdl_trans_list[pc] = instr(opcode)
		vhdl_tcl_list[pc] = tcl_bits(pc, opcode)
		minstr_comment = format("0x%3.3X: %s", pc, mnemo)
	when "MOVC|R|Ri", "MOVX|R|Ri"
		vhdl_trans_list[pc] = instr_rr(opcode, reg[0], reg[1]);
		vhdl_tcl_list[pc] = tcl_bits_rr(pc, opcode, reg[0], reg[1])
		minstr_comment = format("0x%3.3X: %s R%2.2d, (R%2.2d)", pc, mnemo, reg[0], reg[1])
	when "MOV|R|R", "SUB|R|R", "ADD|R|R", "AND|R|R", "OR|R|R", "XOR|R|R", "CMP|R|R"
		vhdl_trans_list[pc] = instr_rr(opcode, reg[0], reg[1]);
		vhdl_tcl_list[pc] = tcl_bits_rr(pc, opcode, reg[0], reg[1])
		minstr_comment = format("0x%3.3X: %s R%2.2d, R%2.2d", pc, mnemo, reg[0], reg[1])
	when "MOVC|Ri|R", "MOVX|Ri|R"
		vhdl_trans_list[pc] = instr_rr(opcode, reg[1], reg[0]);
		vhdl_tcl_list[pc] = tcl_bits_rr(pc, opcode, reg[1], reg[0])
		minstr_comment = format("0x%3.3X: %s (R%2.2d), R%2.2d", pc, mnemo, reg[1], reg[0])
	when "MOVC|Ri|K", "MOVX|Ri|K", "COUT|Ri|K", "XOUT|Ri|K"
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
		minstr_comment = format("0x%3.3X: %s (R%2.2d), 0x%2.2X", pc, mnemo, reg[0], kk)
	when "MOVC|R|Ki", "MOVX|R|Ki", "CIN|R|Ki", "XIN|R|Ki"
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
		minstr_comment = format("0x%3.3X: %s R%2.2d, (0x%2.2X)", pc, mnemo, reg[0], kk)
	when "MOV|R|K", "SUB|R|K", "ADD|R|K", "AND|R|K", "OR|R|K", "XOR|R|K", "CMP|R|K"
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
		minstr_comment = format("0x%3.3X: %s R%2.2d, 0x%2.2X", pc, mnemo, reg[0], kk)
	when "MOVC|Ki|R", "MOVC|Ki|R", "MOVX|Ki|R", "MOVX|Ki|R", "COUT|Ki|R", "XOUT|Ki|R"
		vhdl_trans_list[pc] = instr_kr(opcode, kk, reg[1]);
		vhdl_tcl_list[pc] = tcl_bits_kr(pc, opcode, kk, reg[1])
		minstr_comment = format("0x%3.3X: %s (0x%2.2X), R%2.2d", pc, mnemo, kk, reg[1])
	when "CALL|K", "JMP|K", "JNZ|K", "JZ|K","JNC|K", "JC|K", "JLT|K", "JGT|K", "JLE|K", "JGE|K", "JEQ|K", "JNE|K"
		vhdl_trans_list[pc] = instr_k(opcode, kk)
		vhdl_tcl_list[pc] = tcl_bits_k(pc, opcode, kk)
		minstr_comment = format("0x%3.3X: %s 0x%3.3X", pc, mnemo, kk)
	when "PUSH|R", "POP|R", "SHR|R", "SHL|R", "ROR|R", "ROL|R", "RORC|R", "ROLC|R"
		vhdl_trans_list[pc] = instr_r(opcode, reg[0])
		vhdl_tcl_list[pc] = tcl_bits_r(pc, opcode, reg[0])
		minstr_comment = format("0x%3.3X: %s R%2.2d", pc, mnemo, reg[0])
	when "TST|R"
		kk = 0
		minstr_comment = format("0x%3.3X: %s R%2.2d", pc, mnemo, reg[0])
		opcode = mnemo_list.rindex("CMP|R|K").to_i
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
	when "INC|R"
		kk = 1
		minstr_comment = format("0x%3.3X: %s R%2.2d", pc, mnemo, reg[0])
		opcode = mnemo_list.rindex("ADD|R|K").to_i
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
	when "DEC|R"
		kk = 1
		minstr_comment = format("0x%3.3X: %s R%2.2d", pc, mnemo, reg[0])
		opcode = mnemo_list.rindex("SUB|R|K").to_i
		vhdl_trans_list[pc] = instr_rk(opcode, reg[0], kk);
		vhdl_tcl_list[pc] = tcl_bits_rk(pc, opcode, reg[0], kk)
	else
		STDERR.puts format("Error in line %d: Not yet implemented %s", instruct[0], format)
		error = true
	end

	if error
		num_errors += 1
		break
	end
	vhdl_comment_list[pc] = minstr_comment

	puts vhdl_trans_list[pc] + " -- " + minstr_comment
	
	pc += 1
end

# --------------------------------------------------------
# Output ROM file
# --------------------------------------------------------
if num_errors == 0

	filename = format("rom_%s.vhdl.snip", PROJECT_NAME)
	file = File.open(filename, "w")

	file.puts format("ENTITY %s IS\n", ENTITY_NAME)
	file.puts format("\tPort (\n")
	file.puts format("\tclk\t\t\t: in  STD_LOGIC;\n")
	file.puts format("\tce\t\t\t: in  STD_LOGIC;\n")
	file.puts format("\taddr\t\t: in  %s;\n", ENTITY_ADDR_TYPE)
	file.puts format("\tdout\t\t: out %s\n", ENTITY_DATA_TYPE)
	file.puts format("\t);\n")
	file.puts format("END %s;\n", ENTITY_NAME)
	file.puts format("\n")
	file.puts format("ARCHITECTURE %s OF %s IS \n", PROJECT_NAME, ENTITY_NAME)
	file.puts format("\n")
	file.puts format("\ttype instruction_rom_t is array (0 to %d) of %s;\n", pc-1, ENTITY_DATA_TYPE)
	file.puts format("\n")
	file.puts format("\tconstant instruction_rom : instruction_rom_t :=\n")
	file.puts format("\t(\n");
	for i in (0..pc-2)
		file.puts "\t\t" + vhdl_trans_list[i] + ", -- " + vhdl_comment_list[i] + "\n"
	end;
	file.puts "\t\t" + vhdl_trans_list[pc-1] + " -- " + vhdl_comment_list[pc-1] + "\n"
	file.puts format("\t);\n")
	file.puts format("\n")
	file.puts format("begin")
	file.puts format("\n")
	file.puts format("PROM_READ:")
	file.puts format("\tprocess(clk, ce)\n")
	file.puts format("\tbegin\n")
	file.puts format("\t\tif rising_edge(clk) and ce = '1' then\n")
	file.puts format("\t\t\tdout <= instruction_rom(to_integer(addr));\n")
	file.puts format("\t\tend if;\n")
	file.puts format("\tend process;\n")
	file.puts format("\n")
	file.puts format("end %s;\n", PROJECT_NAME)
	puts format("ROM file written to \"%s\"\n",filename)
	file.close
end
if num_errors == 0

	filename = format("preinit_%s.vhdl.snip", PROJECT_NAME)
	file = File.open(filename, "w")

	file.puts format("\tsignal instruction_rom : instruction_rom_t :=\n")
	file.puts format("\t(\n");
	for i in (0..pc-2)
		file.puts "\t\t" + vhdl_trans_list[i] + ", -- " + vhdl_comment_list[i] + "\n"
	end;
	if pc < (MAX_SIZE_ROM-1)
		file.puts "\t\t" + vhdl_trans_list[pc-1] + ", -- " + vhdl_comment_list[pc-1] + "\n"
		for i in (pc..(MAX_SIZE_ROM-2))
			file.puts "\t\t" + instr(0) + ",\n"
		end;
		file.puts "\t\t" + instr(0) + "\n"
	else
		file.puts "\t\t" + vhdl_trans_list[pc-1] + " -- " + vhdl_comment_list[pc-1] + "\n"
	end	
	file.puts format("\t);\n")
	puts format("PREINIT file written to \"%s\"\n",filename)
	file.close
end
if num_errors == 0
	filename = format("rom_%s.tcl.snip", PROJECT_NAME)
	file = File.open(filename, "w")
	for i in (0..pc-1)
		# Chipscope 8.1
#		file.puts format("jtag_shiftdr $handle -buffer \"%s\" -endstate RTI -device $devid", vhdl_tcl_list[i].reverse);

		# Chipscope 9.1
		file.puts format("\# %s", vhdl_comment_list[i]) 
		file.puts format("::chipscope::csejtag_tap shift_device_dr $handle $devid $CSEJTAG_SHIFT_READWRITE $CSEJTAG_RUN_TEST_IDLE 0 %d \"%8.8X\"\n\n", vhdl_tcl_list[i].length, vhdl_tcl_list[i].to_i(2));
	end;
	puts format("TCL snippet written to \"%s\"\n",filename)
	file.close
end

# --------------------------------------------------------
# Output final statistics
# --------------------------------------------------------
if num_errors == 0
	puts "Program uses #{pc} instruction addresses"
	puts "No errors found"
	exit 0
else
	puts "#{num_errors} errors found"
	exit 1
end	
