??如题,照着语法写了这个编译器。
??代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <utility>
#include <windows.h>
using namespace std;
typedef pair<int, int> pii;
const int MAXN = 1e6 + 5;
pii pos[MAXN];
int stk[MAXN], cp[MAXN], top;
int val[MAXN] = {};
char code[MAXN], buf[MAXN];
void RE( const int cur )
{
printf( "Runtime Error on: Line %d, Character %d.\n", pos[cur].first, pos[cur].second );
printf( "Error: Out of Memory.\n" );
exit( 0 );
}
void CE( const int cur, bool type )
{
printf( "Compilation Error on: Line %d, Character %d.\n", pos[cur].first, pos[cur].second );
printf( "Mismatched %s Bracket.\n", type ? "Right" : "Left" );
exit( 0 );
}
int main()
{
puts( "Please Input File Name:" );
fgets( buf, MAXN, stdin );
buf[strlen( buf ) - 1] = ‘\0‘;
FILE *source = fopen( buf, "r" );
int len = 0, cnt = 0;
while( ~ fscanf( source, "%s", buf + 1 ) )
{
cnt ++;
for( int i = 1 ; buf[i] && buf[i] != ‘\r‘ && buf[i] != ‘\n‘ ; i ++ )
code[++ len] = buf[i], pos[len] = pii( cnt, i );
}
system( "cls" );
puts( "Processing." );
for( int i = 1 ; i <= len ; i ++ )
{
if( code[i] == ‘[‘ ) stk[++ top] = i;
if( code[i] == ‘]‘ )
{
cp[i] = stk[top], cp[stk[top --]] = i;
if( top < 0 ) CE( i, 1 );
}
if( i == len / 3 )
{
system( "cls" );
puts( "Processing.." );
}
if( i == len / 3 * 2 )
{
system( "cls" );
puts( "Processing..." );
}
}
system( "cls" );
puts( "Done!" );
puts( "Running..." );
Sleep( 500 );
system( "cls" );
if( top ) CE( stk[1], 0 );
int ptr = 0;
for( int i = 1 ; i <= len ; i ++ )
{
if( code[i] == ‘>‘ ) { ptr ++; if( ptr == MAXN ) RE( i ); }
if( code[i] == ‘<‘ ) { ptr --; if( ptr < 0 ) RE( i ); }
if( code[i] == ‘+‘ ) val[ptr] ++;
if( code[i] == ‘-‘ ) val[ptr] --;
if( code[i] == ‘.‘ ) putchar( val[ptr] );
if( code[i] == ‘,‘ ) val[ptr] = getchar();
if( code[i] == ‘[‘ ) { if( val[ptr] == 0 ) i = cp[i]; }
if( code[i] == ‘]‘ ) { if( val[ptr] ) i = cp[i]; }
}
return 0;
}
原文:https://www.cnblogs.com/crashed/p/13039551.html