-
Notifications
You must be signed in to change notification settings - Fork 0
/
iag.c
129 lines (111 loc) · 2.24 KB
/
iag.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define STACKSIZE 256
#define PROGSIZE 65000
void error( char *complaint )
{
fprintf( stderr, "%s\n", complaint );
exit( 1 );
}
void system_call( int nr, int mp, int mem[] )
{
int c;
switch( nr ) {
case 2:
fputc( mem[mp], stdout );
break;
case 3:
c = fgetc( stdin );
if ( c == EOF ) c = 0;
mem[mp] = c;
break;
case 4:
mem[mp] = time( NULL );
break;
case 5:
exit( 0 );
break; /* Not needed */
}
}
void dump_debug( int acc, int mp, int mem[], int memsize )
{
int i;
printf( "\nDebug: [%d] ", acc );
for( i = 0; i < memsize; ++i )
printf( "%c%d", ( mp == i ? '*' : ' ' ), mem[i] );
putchar( '\n' );
}
void stack_debug( int sp, char *stack[] )
{
int i;
for( i = sp; i >= 0; --i ) {
char *f = stack[i];
printf ( "\ns[%d]: %c%c%c%c%c%c%c", i,
f[0], f[1], f[2], f[3], f[4], f[5], f[6] );
}
putchar( '\n' );
}
int execute( char *ip, char *end )
{
char *stack[STACKSIZE];
int *mem = malloc( sizeof(int) );
int memsize = 1;
int sp = 0, mp = 0, acc = 0;
mem[0] = 0;
while ( ip < end ) {
switch ( *ip ) {
case '<':
if ( --mp < 0 ) error( "Memory underflow" );
break;
case '=':
mem[mp] = acc = acc - mem[mp];
if ( ++mp >= memsize ) {
int nmemsize = memsize * 2 + 10;
mem = realloc( mem, sizeof(int) * nmemsize );
while ( memsize < nmemsize )
mem[memsize++] = 0;
}
break;
case '|':
if ( acc > 0 ) system_call( acc, mp, mem );
else if ( acc == 0 ) {
stack[sp++] = ip;
if ( !mem[mp] )
while ( ++ip < end )
if ( *ip == '|' ) break;
acc = 1;
} else {
sp += acc;
if ( sp < 0 ) error( "Stack underflow" );
ip = stack[sp] - 1;
acc = 0;
}
break;
case 'd':
dump_debug( acc, mp, mem, memsize );
break;
case 's':
stack[sp] = ip;
stack_debug( sp, stack );
break;
case 'x':
return 0;
}
++ip;
}
return 0;
}
int main( int ac, char* av[] )
{
char prog[PROGSIZE] = { 0 };
int c;
char *progp = prog;
FILE *pfile;
if ( ac < 2 ) error( "Please give program file as argument" );
pfile = fopen( av[1], "r" );
if ( !pfile ) error( "Not a valid file" );
while ( ( c = fgetc( pfile )) != EOF ) *progp++ = c;
return execute( prog, progp );
}