#include "common.h" #include "chunk.h" #include "debug.h" #include "vm.h" #include #include static void repl( VM* vm ) { char line[512]; for ( ; ; ) { printf( "> " ); if ( !fgets( line, sizeof(line), stdin ) ) { printf( "\n" ); break; } printf( "= %s", line ); interpret( vm, line ); } } static char* readFile( const char* path ) { FILE* file = fopen( path, "rb" ); if ( file == NULL ) { fprintf( stderr, "Error opening file: \"%s\"\n", path ); exit( 74 ); } fseek( file, 0, SEEK_END ); size_t sz = ftell( file ); rewind( file ); char* src = (char*)malloc( sz + 1 ); if ( src == NULL ) { fprintf( stderr, "Error allocating memory for file: \"%s\"\n", path ); exit( 74 ); } size_t bread = fread( src, sizeof(char), sz, file ); if ( bread < sz ) { fprintf( stderr, "Error reading file: \"%s\"\n", path ); exit( 74 ); } src[bread] = '\0'; fclose( file ); return src; } static void runFile( VM* vm, const char* path ) { char* source = readFile( path ); InterpretResult res = interpret( vm, source ); free( source ); if ( res == INTERPRET_COMPILE_ERROR ) exit( 65 ); if ( res == INTERPRET_RUNTIME_ERROR ) exit( 70 ); } int main( int argc, char** argv ) { (void)argc; (void)argv; srand( time( NULL ) ); VM vm; initVM( &vm ); if ( argc == 1 ) { repl( &vm ); } else if ( argc == 2 ) { runFile( &vm, argv[1] ); } else { fprintf( stderr, "Usage: clox [path]\n" ); //exit( EXIT_FAILURE ); } freeVM( &vm ); return EXIT_SUCCESS; } //void* malloc( size_t sz ) {}