From a88c502529b6649e25ffc832f0fdc25b6dba41f6 Mon Sep 17 00:00:00 2001 From: sfja Date: Fri, 13 Dec 2024 20:29:06 +0100 Subject: [PATCH] add readchar --- compiler/arch.ts | 7 ++++--- examples/std.slg | 1 + runtime/arch.hpp | 7 ++++--- runtime/vm.cpp | 13 +++++++++++++ 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/compiler/arch.ts b/compiler/arch.ts index e8f9aee..4942416 100644 --- a/compiler/arch.ts +++ b/compiler/arch.ts @@ -55,9 +55,10 @@ export const Builtins = { FileOpen: 0x41, FileClose: 0x42, FileWriteString: 0x43, - FileReadToString: 0x44, - FileFlush: 0x45, - FileEof: 0x46, + FileReadChar: 0x44, + FileReadToString: 0x45, + FileFlush: 0x46, + FileEof: 0x47, } as const; export function opToString(op: number): string { diff --git a/examples/std.slg b/examples/std.slg index 24bf7e9..0175802 100644 --- a/examples/std.slg +++ b/examples/std.slg @@ -15,6 +15,7 @@ fn array_at_string(array: [string], index: int) -> string #[builtin(ArrayAt)] {} fn file_open(filename: string, mode: string) -> int #[builtin(FileOpen)] {} fn file_close(file: int) #[builtin(FileClose)] {} fn file_write_string(file: int, content: string) -> int #[builtin(FileWriteString)] {} +fn file_read_char(file: int) -> int #[builtin(FileReadChar)] {} fn file_read_to_string(file: int) -> string #[builtin(FileReadToString)] {} fn file_flush(file: int) #[builtin(FileFlush)] {} fn file_eof(file: int) -> bool #[builtin(FileEof)] {} diff --git a/runtime/arch.hpp b/runtime/arch.hpp index 115f2f3..472b2fb 100644 --- a/runtime/arch.hpp +++ b/runtime/arch.hpp @@ -56,9 +56,10 @@ enum class Builtin : uint32_t { FileOpen = 0x41, FileClose = 0x42, FileWriteString = 0x43, - FileReadToString = 0x44, - FileFlush = 0x45, - FileEof = 0x46, + FileReadChar = 0x44, + FileReadToString = 0x45, + FileFlush = 0x46, + FileEof = 0x47, }; } diff --git a/runtime/vm.cpp b/runtime/vm.cpp index 7e7fe48..97e2759 100644 --- a/runtime/vm.cpp +++ b/runtime/vm.cpp @@ -322,6 +322,7 @@ void VM::run_builtin(Builtin builtin_id) case Builtin::FileOpen: case Builtin::FileClose: case Builtin::FileWriteString: + case Builtin::FileReadChar: case Builtin::FileReadToString: case Builtin::FileFlush: case Builtin::FileEof: @@ -488,6 +489,18 @@ void VM::run_file_builtin(Builtin builtin_id) stack_push(Int(0)); break; } + case Builtin::FileReadChar: { + assert_stack_has(1); + auto file_id = stack_pop().as_int().value; + auto fp = this->open_files.find(file_id); + if (fp == this->open_files.end()) { + std::cerr << std::format("error: no open file {}\n", file_id); + std::exit(1); + } + int value = std::fgetc(fp->second); + stack_push(Int(value)); + break; + } case Builtin::FileReadToString: { assert_stack_has(1); auto file_id = stack_pop().as_int().value;