From f9a88c14c581acc6cd35ed08de1062a37f3666d4 Mon Sep 17 00:00:00 2001 From: Natapat Samutpong Date: Sun, 20 Mar 2022 05:18:27 +0700 Subject: [PATCH] implements `read_fle`, std -> runtime --- crates/codegen/src/ts.rs | 5 +++-- crates/hir/src/lib.rs | 3 ++- {std => runtime}/io.ts | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) rename {std => runtime}/io.ts (52%) diff --git a/crates/codegen/src/ts.rs b/crates/codegen/src/ts.rs index 358e312..bd449ff 100644 --- a/crates/codegen/src/ts.rs +++ b/crates/codegen/src/ts.rs @@ -58,9 +58,10 @@ impl Codegen { IRKind::Intrinsic { name, args } => { match name.as_str() { - "write" => { format!("write({}){}\n", self.gen_ir(&args[0], false), semicolon!()) }, + "write" => { format!("write({}){}\n" , self.gen_ir(&args[0], false), semicolon!()) }, "write_file" => { format!("writeFile({}, {}){}\n", self.gen_ir(&args[0], false), self.gen_ir(&args[1], false), semicolon!()) }, - "read" => { todo!() }, + "read" => { format!("read({}){}\n" , self.gen_ir(&args[0], false), semicolon!()) }, + "read_file" => { format!("readFile({}){}\n" , self.gen_ir(&args[0], false), semicolon!()) } "emit" => { format!("{}", self.gen_ir(&args[0], false).trim_start_matches('"').trim_end_matches('"')) }, _ => unreachable!(format!("Unknown intrinsic: {}", name)) // Shoul be handled by lowering } diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 7c6de45..e309fe6 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1,10 +1,11 @@ use std::ops::Range; use parser::Expr; -const INTRINSICS: [&str; 4] = [ +const INTRINSICS: [&str; 5] = [ "write", "read", "write_file", + "read_file", "emit", ]; diff --git a/std/io.ts b/runtime/io.ts similarity index 52% rename from std/io.ts rename to runtime/io.ts index 4553e25..94e91b5 100644 --- a/std/io.ts +++ b/runtime/io.ts @@ -9,6 +9,16 @@ export function write(text: any): void { writeAllSync(Deno.stdout, bytes); } +/** + * Read text from the stdin stream. + * @param prompt_str The prompt string to display. + * @returns The text read from the stdin stream. + */ +export function read(prompt_str: string): string { + const input = prompt(prompt_str, ""); + return input ? input : ""; +} + /** * Writes text to the file. * @param text The text to write. Can be any type. @@ -17,4 +27,15 @@ export function write(text: any): void { export function writeFile(text: any, path: string): void { const bytes: Uint8Array = new TextEncoder().encode(text); Deno.writeFileSync(path, bytes); +} + +/** + * Read text from the file. + * @param path The path to the file. + * @returns The text read from the file. + */ +export function readFile(path: string): string { + const decoder = new TextDecoder("utf-8"); + const text = decoder.decode(Deno.readFileSync(path)); + return text; } \ No newline at end of file