/* parses(source) -> boolean */ int DuckParses(int argument_count, void* data) { L_TOKEN* lexing; char* buffer; int error = 0; VALUE argument = GetRecord("source", gCurrentContext); gLastExpression.type = VAL_PRIMITIVE; gLastExpression.data.primitive = 0; if (argument.type == VAL_STRING) { lexing = LexSourceBuffer(argument.data.string, &buffer, CONTEXT_FREE_GRAMMAR); if (lexing == NULL) { gLastExpression.data.primitive = -1; FreeLexing(lexing, buffer); //return 1; return 0; } gLastExpression.data.primitive = ParseSucceeds(lexing, PARSE_TABLE, CONTEXT_FREE_GRAMMAR); if (gLastExpression.data.primitive == 0) { FreeLexing(lexing, buffer); return 0; } /* free lexing */ FreeLexing(lexing, buffer); } return error; }
/* lex a source file for a program */ L_TOKEN* LexSource(const char* file, char** stripped, GRAMMAR_TABLE table) { FILE* input; char* buffer; int size; int read; L_TOKEN* result; // read source file input = fopen(file, "rb"); if (input == 0) { printf("Could not open source file.\n"); return 0; } fseek(input, 0, SEEK_END); size = ftell(input); rewind(input); buffer = (char*)malloc(size+1); read = fread(buffer, 1, size, input); buffer[size] = 0; fclose(input); if (size == 0) { printf("Unable to read source file.\n"); return 0; } // lex source file result = LexSourceBuffer(buffer, stripped, table); free(buffer); return result; }
/* eval(source) */ int DuckEval(int argument_count, void* data) { L_TOKEN* lexing; SYNTAX_TREE* ast; char* buffer; int error = 0; VALUE argument = GetRecord("source", gCurrentContext); gLastExpression.type = VAL_NIL; gLastExpression.data.primitive = 0; CLOSURE* currentContext; currentContext = gCurrentContext; int prev_line_error = line_error; SYNTAX_TREE* prev_failed_production = failed_production; // if (gCurrentContext->parent) gCurrentContext = gCurrentContext->parent; gCurrentContext = gGlobalContext; if (argument.type == VAL_STRING) { lexing = LexSourceBuffer(argument.data.string, &buffer, CONTEXT_FREE_GRAMMAR); if (lexing == NULL) { printf("Error lexing source or empty source string.\n"); FreeLexing(lexing, buffer); return 1; } ast = ParseSource(lexing, PARSE_TABLE, CONTEXT_FREE_GRAMMAR); if (ast == NULL) { printf("Error parsing source.\n"); FreeLexing(lexing, buffer); return 1; } /* ReduceProgramAST(&ast); */ error = InterpretNode(ast); if (error) { printf("%s\n", ErrorMessage(error)); PrintStackTrace(); FreeLexing(lexing, buffer); FreeParseTree(ast); ClearCallStack(&gStackTrace); line_error = prev_line_error; failed_production = prev_failed_production; return 1; } /* sanitize last expression for use in program */ //gLastExpression = ReallocStrings(gLastExpression); /* free lexing and parse tree */ //FreeLexing(lexing, buffer); //FreeParseTree(ast); GCAddLexing(lexing, buffer); GCAddParseTree(ast); } gCurrentContext = currentContext; return error; }