Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- #include <sstream>
- #include <stdio.h>
- #include <cctype>
- // Simple SISA RISC Assembler (SASM)
- // NOTA: NO compila las instrucciones LD, LDB, ST y STB (por ahora)
- const std::string instructions[3][8] =
- {
- { "AND", "OR", "XOR", "NOT", "ADD", "SUB", "SHA", "SHL" },
- { "CMPLT", "CMPLE", "-", "CMPEQ", "CMPLTU", "CMPLEU", "-", "-" },
- { "ADDI", "-", "-", "-", "-", "-", "-", "-" }
- };
- std::vector<std::string> splitString(const std::string& str, char delimiter)
- {
- std::vector<std::string> split;
- std::stringstream ss(str);
- std::string item;
- while (getline(ss, item, delimiter)) split.push_back(item);
- return split;
- }
- void findAndReplaceAll(std::string& data, std::string toSearch, std::string replaceStr)
- {
- size_t pos = data.find(toSearch);
- while( pos != std::string::npos)
- {
- data.replace(pos, toSearch.size(), replaceStr);
- pos = data.find(toSearch, pos + toSearch.size());
- }
- }
- inline int getN(const std::string& reg) { return (reg[1] - '0'); }
- int processString(const std::string& str)
- {
- std::vector<std::string> tokens = splitString(str, ' ');
- int instr = 0x0000;
- int foundLine = -1;
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 8; j++)
- {
- if(tokens[0] == instructions[i][j])
- {
- foundLine = i;
- instr |= (i << 12);
- instr |= j;
- break;
- }
- }
- }
- if(foundLine == -1)
- {
- if(tokens[0] == "JALR")
- {
- // JALR Rd, Ra
- instr |= ((0b0111) << 12);
- instr |= (getN(tokens[2]) << 9);
- instr |= (getN(tokens[1]) << 6);
- }
- else
- {
- std::string list[] = { "LD", "ST", "LDB", "STB", "JALR", "BNZ", "BZ", "MOVHI", "MOVI", "OUT", "IN" };
- for(int i = 0; i < 11; i++)
- {
- if(tokens[0] == list[i])
- {
- if(i > 4)
- {
- instr |= ((0b1000 + (i - 5) / 2) << 12);
- if(tokens[0] != "OUT")
- {
- instr |= (getN(tokens[1]) << 9);
- instr |= std::stoi(tokens[2]) & 0xFF;
- }
- else
- {
- instr |= (getN(tokens[2]) << 9);
- instr |= std::stoi(tokens[1]) & 0xFF;
- }
- if(i % 2 == 1) instr |= (1 << 8);
- }
- else
- {
- instr |= ((0b0011 + i) << 12);
- // LD, ST, LDB, STB
- }
- }
- }
- }
- }
- else if(foundLine > 1)
- {
- instr |= (getN(tokens[2]) << 9);
- instr |= (getN(tokens[1]) << 6);
- instr |= std::stoi(tokens[3]) & 0x3F;
- }
- else
- {
- instr |= (getN(tokens[2]) << 9);
- instr |= (getN(tokens[3]) << 6);
- instr |= (getN(tokens[1]) << 3);
- }
- return instr;
- }
- void strupr(char* str)
- {
- while(*str != '\0')
- {
- *str = toupper(*str);
- ++str;
- }
- }
- int main()
- {
- char line[256];
- while(std::cin.getline(line, 256, '\n'))
- {
- strupr(line);
- std::string instr(line);
- std::replace(instr.begin(), instr.end(), ',', ' ');
- std::replace(instr.begin(), instr.end(), '\t', ' ');
- findAndReplaceAll(instr, " ", " ");
- printf("0x%04X\n", processString(instr));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement