컴공 일기229
게시글 주소: https://dev.orbi.kr/00062045045
요새는 운동을 하러 가는 것 이외엔, 공학과 수학에 집중하고 있습니다. 나도 모르게, 몰입이 되고 있다는 느낌을 많이 받고 있어요. 다만, 결과는 과정의 수려함들을 집어삼켜 먹는 습성이 있는 걸 잘 알아서, 큰 욕심은 내지 않고 있습니다.
과정에 주목하는 삶을 살고 있달까요. 뭐, 무엇인가를 크게 이뤄나가는 일상은 아닙니다만, 개인적으론 참 만족스럽습니다.
저번 일기에서 그려보았듯, Assembler를 제작하고 있어요. 재미있는 여정입니다.
Parser 모듈 : 입력 코드에 대한 접근을 캡슐화(Capsulation)합니다. 어셈블리 명령을 읽어 들여 구문을 분석하고, 명령 세부요소(필드/기호)에 편리하게 접근하도록 합니다. 추가적으로 모든 공백과 주석문을 제거합니다.
Parser.h
#pragma once
#ifndef HACK_ASSEMBLER_PARSER_H
#define HACK_ASSEMBLER_PARSER_H
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
class Parser
{
public:
Parser(string& filename);
//File is closed implicitly.
bool hasMoreCommands();
//Returns true if the file contains commands that still need to be parsed,
//Return flase otherwise.
void advance(unsigned long& lineNr);
char commandType(unsigned long& lineNr);
string symbol();
//Returns the symbol or decimal value of the current command.
//Should only be called if commandType() returns 'A' or 'L'.
string destM();
// Returns the destination mnemonic of the current command.
string compM();
string jumpM();
private:
ifstream fin;
string currentCommand;
map <char, char> commandTable;
};
#endif
-Parser.cpp
#include "Parser.h"
using namespace std;
Parser::Parser(string& fileName)
{
fin.open(fileName);
if (fin.fail())
{
cout << fileName << "not found." << endl;
exit(1);
}
//Populate the command map table.
commandTable['@'] = 'A';
commandTable['A'] = 'C';
commandTable['D'] = 'C';
commandTable['M'] = 'C';
commandTable['0'] = 'C';
commandTable['1'] = 'C';
commandTable['-'] = 'C';
commandTable['!'] = 'C';
commandTable['('] = 'L';
}
bool Parser::hasMoreCommands()
{
return !fin.eof();
}
void Parser::advance(unsigned long& lineNr)
{
string currentLine;
unsigned long commentPos;
bool commandFound;
commandFound = false;
while (!commandFound && getline(fin, currentLine))
{
lineNr++;
//Remove whitespace.
currentLine.erase(remove_if(currentLine.begin(), currentLine.end(), ::isspace), currentLine.end());
//Remove comments.
commentPos = currentLine.find("//");
//if comments were found
if (commentPos != string::npos)
{
currentLine.erase(commentPos, currentLine.length() - commentPos);
}
commandFound = !currentLine.empty();
}
currentCommand = currentLine;
}
char Parser::commandType(unsigned long& lineNr)
{
if (commandTable.find(currentCommand[0]) != commandTable.end())
{
return commandTable[currentCommand[0]];
}
cout << "Invalid syntax at line: " << lineNr << endl;
}
string Parser::symbol()
{
unsigned long openBracketPos, closeBracketPos;
openBracketPos = currentCommand.find('(');
closeBracketPos = currentCommand.find(')');
//A-instruction: return everything after the '@' character
if (currentCommand[0] == '@')
{
return currentCommand.substr(1, currentCommand.length() - 1);
}
else if (openBracketPos != string::npos && closeBracketPos != string::npos) {
return currentCommand.substr(openBracketPos + 1, closeBracketPos - openBracketPos - 1);
}
// If the function was called in error, return a blank string.
return "";
}
string Parser::destM()
{
unsigned long equalSignPos;
//Return everything before the '=' character.
if (equalSignPos != string::npos)
{
return currentCommand.substr(0, equalSignPos);
}
//If no destination was specified, return a blank string.
return "";
}
string Parser::compM()
{
unsigned long equalSignPos, semiColonPos;
equalSignPos = currentCommand.find('=');
semiColonPos = currentCommand.find(';');
// Return the computation mnemonic based on three cases.
if (equalSignPos != string::npos)
{
//Case 1: dest = comp ; jump
if (semiColonPos != string::npos)
{
return currentCommand.substr(equalSignPos + 1, semiColonPos - equalSignPos - 1);
}
//Case 2: dest = comp
return currentCommand.substr(equalSignPos + 1, currentCommand.length() - equalSignPos - 1);
}
else if (semiColonPos != string::npos)
{
//Case 3: comp ; jump
return currentCommand.substr(0, semiColonPos);
}
return "";
}
string Parser::jumpM()
{
unsigned long semiColonPos;
//Return everything after the ';' character.
if (semiColonPos != string::npos)
{
return currentCommand.substr(semiColonPos + 1, currentCommand.length() - semiColonPos - 1);
}
//If a jump was not specified, return a blank string.
}
CodeTranslator 모듈 : 어셈블리 언어의 연상기호를 2진 코드로 변환합니다.
-CodeTranslator.h
#pragma once
#ifndef HACK_ASSEMBLER_CODE_H
#define HACK_ASSEMBLER_CODE_H
#include <iostream>
#include <map>
using namespace std;
class CodeTranslator
{
public:
CodeTranslator();
//Populates the code translation map tables
// with the language specification.
string dest(string destMenmonic, unsigned long& lineNr);
//Returns the binary code of the destination mnemonic
//as a string containing 3 bits.
//Line number is passed for use in an error message.
string comp(string compMnemonic, unsigned long& lineNr);
//Returns the binary code of the computation mnemonic
//as a string containing 3 bits.
//Line number is passed for use in an error message.
string jump(string jumpMnemonic, unsigned long& lineNr);
//Returns the binary code of the jump mnemonic
//as a string containing 3 bits.
//Line number is passed for use in an error meassage.
private:
map<string, string> destTable;
map<string, string> compTable;
map<string, string> jumpTable;
};
#endif
-CodeTranslator.cpp
| #include "CodeTranslator.h" | |
| using namespace std; | |
| CodeTranslator::CodeTranslator() { | |
| // Populate the translation map tables. | |
| destTable[""] = "000"; | |
| destTable["M"] = "001"; | |
| destTable["D"] = "010"; | |
| destTable["MD"] = "011"; | |
| destTable["A"] = "100"; | |
| destTable["AM"] = "101"; | |
| destTable["AD"] = "110"; | |
| destTable["AMD"] = "111"; | |
| compTable["0"] = "0101010"; | |
| compTable["1"] = "0111111"; | |
| compTable["-1"] = "0111010"; | |
| compTable["D"] = "0001100"; | |
| compTable["A"] = "0110000"; | |
| compTable["!D"] = "0001101"; | |
| compTable["!A"] = "0110001"; | |
| compTable["-D"] = "0001111"; | |
| compTable["-A"] = "0110011"; | |
| compTable["D+1"] = "0011111"; | |
| compTable["A+1"] = "0110111"; | |
| compTable["D-1"] = "0001110"; | |
| compTable["A-1"] = "0110010"; | |
| compTable["D+A"] = "0000010"; | |
| compTable["D-A"] = "0010011"; | |
| compTable["A-D"] = "0000111"; | |
| compTable["D&A"] = "0000000"; | |
| compTable["D|A"] = "0010101"; | |
| compTable["M"] = "1110000"; | |
| compTable["!M"] = "1110001"; | |
| compTable["-M"] = "1110011"; | |
| compTable["M+1"] = "1110111"; | |
| compTable["M-1"] = "1110010"; | |
| compTable["D+M"] = "1000010"; | |
| compTable["D-M"] = "1010011"; | |
| compTable["M-D"] = "1000111"; | |
| compTable["D&M"] = "1000000"; | |
| compTable["D|M"] = "1010101"; | |
| jumpTable[""] = "000"; | |
| jumpTable["JGT"] = "001"; | |
| jumpTable["JEQ"] = "010"; | |
| jumpTable["JGE"] = "011"; | |
| jumpTable["JLT"] = "100"; | |
| jumpTable["JNE"] = "101"; | |
| jumpTable["JLE"] = "110"; | |
| jumpTable["JMP"] = "111"; | |
| } | |
| string CodeTranslator::dest(string destMnemonic, unsigned long& lineNr) { | |
| if (destTable.find(destMnemonic) != destTable.end()) { | |
| return destTable[destMnemonic]; | |
| } | |
| // If none of the mnemonics are found, output an error message, | |
| // and provide the line number in the original source where the error occurred. | |
| cout << "Invalid syntax in destination statement at line: " << lineNr << endl; | |
| exit(1); | |
| } | |
| string CodeTranslator::comp(string compMnemonic, unsigned long& lineNr) { | |
| if (compTable.find(compMnemonic) != compTable.end()) { | |
| return compTable[compMnemonic]; | |
| } | |
| // If none of the mnemonics are found, output an error message, | |
| // and provide the line number in the original source where the error occurred. | |
| cout << "Invalid syntax in computation statement at line: " << lineNr << endl; | |
| exit(1); | |
| } | |
| string CodeTranslator::jump(string jumpMnemonic, unsigned long& lineNr) { | |
| if (jumpTable.find(jumpMnemonic) != jumpTable.end()) { | |
| return jumpTable[jumpMnemonic]; | |
| } | |
| // If none of the mnemonics are found, output an error message, | |
| // and provide the line number in the original source where the error occurred. | |
| cout << "Invalid syntax in jump statement at line: " << lineNr << endl; | |
| exit(1); | |
| } |
0 XDK (+0)
유익한 글을 읽었다면 작성자에게 XDK를 선물하세요.
-
초 가구야 공주 보셈요 4 0
진짜 꿀잼 고트 애니
-
그냥 술자리 싫음 청년 7 3
그 뒤지게 시끄러운 곳에서 말도 제대로 안들리는데 처음 보는 사람하고 어색하게...
-
근데 더프 수학선택 범위 좁은건 3모대비라하면 이해되는데 4 3
투과목 << 얘넨 3모에도 안나오는데 전범위로 하면 될걸 왜 꾸득꾸득 초반부만 넣는거임
-
알림창 개폭력적이네 9 6
-
개강 3주차...아직 후배 얼굴도 본적없음
-
시발 뭘 할 수가 없네 9 1
친구 없어도 그래도 고대 왔으니 합응까진 갈까 했는데 허리 이 시발롬 좆도 안낫고 더 아파짐 아오
-
음주체스숙취수학 1 0
왜효고ㅓ좋냐
-
옾붕이들은 영어듣기 잘하나요 9 0
듣기 살면서 한번도 안툴린 사람 많으려나영듣칼럼 쓰려 하는데 수요 있으려나...
-
와 시벌 이게 얼마만인지 모르겟다 한달만에 같이 밥먹는거같은데 두달인가?
-
본인은 메인 두 번 가봄 3 1
한 번은 평가원 피셜 확정 등급컷 (영어) 네이버 블로그 감성 글로 가봤고 한 번은...
-
역시 약대생 3 1
난 시간 꽉꽉 채워 풀어서 88점인데
-
3덮 미적 풀어봤다 15 2
이렇다 전 글에서 맞춘사람 5000덕 보내줄게 생각보다 잘나왔네 22 30은 걍...
-
3모 ㅈ된거같으면 개추. 3 3
ㄱㄱ
-
어스름 내린 언덕 너머로 푸른 융단이 조용히 깔리면 4 1
수줍게 눈을 뜨는 작은 별들 사이로 깊고 아득한 밤이 피어납니다.
-
JMS 유튜버 댓글 근황 1 2
빨리 JMS에서 탈출하길 빕니다
-
대학간 오르비언 특 8 3
2월 말 ~ 3월 첫째주까진 재밌다~~ 하면서 안들어오더니 3월 둘째주부턴 외롭다...
-
나 분명 학기중엔 0 0
새르비를 안할줄알았는데ㅔㅔㅔ 옯창이 맞는것인가?
-
체언 수식 부사
-
새르비ing 0 0
손 ㄱㄱ
-
지방대 궁금한점 질문받음 9 0
옯인원들에겐 관심없을수있지만 25수능때 66584로 지방대 빵노리고 붙었음...
-
독서 제대로 이해한 지문이 없었음... 심지어 마킹 안 하고 1분 초과됨 3모 5일...
-
아빠 잔다 2 1
잔디wwwwww
-
재작년에 수능봐서 백분위 97 받고 대학 다니다가 올해 다시 수능 준비 중인데 생명...
-
3연강으로맞고 0 0
8:30~17:30당하니까죽겠다
-
여기다전화해줘 0 1
119 너 때문에 내 심장이 멎었어
-
행복해요 8 0
-
현역이때 생윤 말아먹어서 재수때 정법하서 3나왔어요 다시 생윤으로 돌아갓?...
-
글리젠 진짜 없네 2 0
내가아는 오르비가맞냐
-
ㅇㅇ
-
그것이 문제로다
-
오르비 굿나잇 ~ 7 1
피곤해뒤지겟다 오답은 내일 할게
-
얘네가 진선여고 숙명여고에 있었으면 내신 몇 뜰까요? 7 0
옛동네인 영등포에 사는 초등동창인 여사친들인데 한 아이는 영등포 공학 좆반고에서...
-
N제 먼저?? 0 0
수1 스블 다 들었고 수2,확통 실점개념 반정도 들었는데 수2,확통까지 실전개념 다...
-
08) 오늘의 공부인증!! 10 1
그냥 너무 심란함 모든것에 대해서 ㅠㅠ
-
ㄹㅇㅋㅋ
-
에효 못생긴 옵붕이들 ㅉ 0 1
심지어 공부도 못하는 말이야
-
새르비 최강의 남자 3 1
쌍윤왜어려움
-
3섶 화1 45 4 0
물2는...예...
-
5시긴40분뒤에일어니야더ㅣㅁ 2 2
습박
-
오늘 저녁 ㅁㅌㅊ? 4 1
돼지 되는 중 ...ing
-
새르비의라이징스타 0 0
설국문쟁취
-
한국 kf21 보라메=>뭔가 문제 있어보이고 그렇게 안 쌜거 같음 미국 f22 =>...
-
김기현쌤 아이디어 0 0
작수 4이고 이번에 확통으로 바꿨습니더 확통은 시발점 듣고있는데 수1 수2를 어느...
-
조해공 과잠 봤을 때였음 조선해양공학과 <- 개틀딱같음 Naval...
-
이거 개쩌는 공부법인듯 2 1
1주마다 문제집 제끼고 오르비에 인증하기 앉아있는 시간은 같지만 공부량 ㅈㄴ 늘어난게 체감이 됨
-
윤사 코드원 샀음 1 2
윤사 개박살 났으니까 그래도 김종익 플러스 해서 코드원까지 하려고..
-
전화하고싶다 3 0
누구든좋으니까
-
작년에 2 0
2월부터 수능까지 새르비에 항상 있었던 사람이 있음
-
소아과 의사 누구였지 6 0
오르비언 ㅇㅅㅇ
-
한 달 뒤 새르비 상황 1 3
제목:진짜 다 뒤1졌냐? 2분전 조회수 8 작성자 수능 ㅈ된 설의적표현 내용:

저 컴공인데 엄청 어려워 보이네요...
어.. 어셈블러를 직접 구현하는 과정이 컴공에 없기는 하죠 ㅠㅠ 개인적으로 그게 아쉬워서 방학을 기회로 해보고 있답니다!
와...컴공 가고 싶었는데 뭔가 엄청 어려워보인다
원리를 알면 생각보다 간단한 코드예요. 번역을 하려면, 문장을 단어별로 세세히 쪼갤 필요가 있고, 그 단어의 의미를 하나하나 파악하잖아요?
그런 원리예요 ㅎㅎ 그걸 코드로 표현한다면 복잡해보이지만, 어느정도 공부를 하고 나면 한 눈에 보이는 정도입니다.
ㅠㅠ 컴공 지망생이긴 한데 혹시 가서 고등학고 때 배웠던 과목 중 쓰이는 과목이 있나요..?
수능 국어요! 코딩도 결국 글쓰기예요. 그러니까, '글'을 읽는 원리라든가, 쓰는 원리에 익숙하면 굉장히 유리한 점을 지니고 있습니다. 수학도 많이 쓰이고요. 근데, 고등학교 수학에서 배웠던 것들이 '기반'이 되기는 하는데, 그것이 '중심'이 되는 것은 물론 아닙니다.