Created
November 20, 2012 02:18
-
-
Save bencz/4115521 to your computer and use it in GitHub Desktop.
A HIPER basic compiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
INPUT SAMPLE: | |
VAR TESTE = 25 | |
PRINT "ALEXANDRE" | |
PRINT TESTE | |
GETCHAR | |
*/ | |
#include <stdio.h> | |
#include <string> | |
#include <vector> | |
#include <map> | |
#include <Windows.h> | |
using namespace std; | |
bool compile(FILE *fp); | |
bool CodeGen(std::vector<string> tokens); | |
void GenPrint(std::vector<string> tokens, int _pos); | |
void GenVar(std::vector<string> tokens, std::map<string, string> _varInfo, int _pos); | |
void GenGet(); | |
int main() | |
{ | |
char *filename = "test.in"; | |
FILE *fp = fopen(filename, "rb"); | |
if(!fp) | |
{ | |
return 1; | |
} | |
if(!compile(fp)) | |
{ | |
printf("ERROR...\n"); | |
} | |
fclose(fp); | |
} | |
bool compile(FILE *fp) | |
{ | |
char c; | |
string token; | |
std::vector<string> tokens; | |
bool _return = true; | |
while ((c = getc(fp)) != EOF) | |
{ | |
if(isalpha(c) || isalnum(c) || c == '"' || c == '=') | |
{ | |
token += c; | |
} | |
else if(c == ' ' || c == '\0' || c == '\n') | |
{ | |
tokens.push_back(token); | |
token = ""; | |
} | |
} | |
tokens.push_back(token); | |
if(!CodeGen(tokens)) | |
_return = false; | |
return _return; | |
} | |
bool CodeGen(std::vector<string> tokens) | |
{ | |
int i; | |
bool _return = true; | |
map<string, string> _varInfo; | |
for(i=0;i<tokens.size();i++) | |
{ | |
if(tokens[i] == "PRINT") | |
{ | |
if(tokens[i+1][0] == '"') | |
{ | |
printf("STRING\n"); | |
} | |
else | |
{ | |
printf("VARIAVEL\n"); | |
} | |
GenPrint(tokens, i); | |
} | |
else if(tokens[i] == "VAR") | |
{ | |
if(tokens[i+2] != "=") | |
{ | |
printf("Error... faltou o ="); | |
_return = false; | |
} | |
else | |
{ | |
_varInfo.insert(make_pair(tokens[i+1], tokens[i+3])); | |
} | |
GenVar(tokens, _varInfo, i); | |
} | |
else if(tokens[i] == "GETLINE") | |
{ | |
GenGet(); | |
} | |
} | |
return _return; | |
} | |
// ++++++++++++++++++++ // | |
// The code gen section // | |
// ++++++++++++++++++++ // | |
void GenPrint(std::vector<string> tokens, int _pos) | |
{ | |
printf("Console.WriteLine(%s);", tokens[_pos+1].c_str()); | |
} | |
void GenVar(std::vector<string> tokens, std::map<string, string> _varInfo, int _pos) | |
{ | |
map<string, string>::iterator it = _varInfo.find(tokens[_pos+1]); | |
if(it != _varInfo.end()) | |
{ | |
// Get the information from map | |
printf("VARIABLE INFORMATIONS\n"); | |
printf("FIRST -> %s\n", it->first.c_str()); | |
printf("SECON -> %s\n", it->second.c_str()); | |
} | |
} | |
void GenGet() | |
{ | |
printf("Console.ReadLine();"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment