Created
November 25, 2009 05:28
-
-
Save minase/242503 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#import <Foundation/Foundation.h> | |
#define TAPE_MAX_WIDTH 1 | |
@interface BrainFxck : NSObject | |
{ | |
const char *code; | |
unsigned char *tape; | |
unsigned int position; | |
unsigned int tape_width; | |
NSMutableString *trace; | |
} | |
@property (readonly) NSMutableString *trace; | |
- (void)evalCode:(NSString*)code; | |
- (void)reallocTape; | |
- (NSString*)trace; | |
@end | |
@implementation BrainFxck | |
@synthesize trace; | |
- (id)init | |
{ | |
tape = calloc(TAPE_MAX_WIDTH, sizeof(unsigned char)); | |
tape_width = TAPE_MAX_WIDTH; | |
trace = [NSMutableString new]; | |
return self; | |
} | |
- (void)evalCode:(NSString*)codeString | |
{ | |
code = [codeString cStringUsingEncoding:NSUTF8StringEncoding]; | |
while(*code) | |
{ | |
switch(*code) | |
{ | |
case '+': | |
tape[position]++; | |
break; | |
case '-': | |
tape[position]--; | |
break; | |
case '>': | |
position++; | |
if(position == tape_width) [self reallocTape]; | |
break; | |
case '<': | |
position--; | |
break; | |
case '[': | |
if(tape[position] == 0) { | |
while(*code != ']') code++; | |
} | |
break; | |
case ']': | |
if(tape[position] != 0) { | |
while(*code != '[') code--; | |
} | |
break; | |
case '.': | |
printf("%c", tape[position]); | |
break; | |
default: | |
code++; | |
continue; | |
} | |
// Trace status | |
[trace appendFormat:@"%c(%03d)", *code, position]; | |
for(int n = 0; n < tape_width; n++) | |
{ | |
[trace appendFormat:@"|%03d", tape[n]]; | |
} | |
[trace appendString:@"|\n"]; | |
code++; | |
} | |
} | |
- (void)reallocTape | |
{ | |
unsigned int new_tape_width = tape_width + TAPE_MAX_WIDTH; | |
realloc(tape, sizeof(unsigned char) * new_tape_width); | |
for(int n = tape_width; n < new_tape_width; n++) | |
{ | |
tape[n] = 0; | |
} | |
tape_width += TAPE_MAX_WIDTH; | |
} | |
- (void)dealloc | |
{ | |
free(tape); | |
[trace release]; | |
[super dealloc]; | |
} | |
@end | |
int main(int argc, char **argv) | |
{ | |
NSAutoreleasePool *pool = [NSAutoreleasePool new]; | |
BrainFxck *bf = [[BrainFxck new] autorelease]; | |
[bf evalCode: | |
@"++++++ [> ++++++++++ < -] > +++++ ." | |
@"> ++++++++++ ." | |
]; | |
NSLog(@"%@", bf.trace); | |
[pool release]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment