From 2d45cf240b451f6239925b55a25e341aa15202e6 Mon Sep 17 00:00:00 2001 From: Natapat Samutpong Date: Fri, 18 Mar 2022 06:57:52 +0700 Subject: [PATCH] emit intrinsic --- crates/codegen/src/ts.rs | 3 ++- crates/hir/src/lib.rs | 16 ++++++++++++---- example/emit.hz | 3 +++ 3 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 example/emit.hz diff --git a/crates/codegen/src/ts.rs b/crates/codegen/src/ts.rs index 52817ae..e8dc141 100644 --- a/crates/codegen/src/ts.rs +++ b/crates/codegen/src/ts.rs @@ -59,7 +59,8 @@ impl Codegen { match name.as_str() { "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" => { todo!() }, + "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 ca2cecd..c6758e1 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; 3] = [ +const INTRINSICS: [&str; 4] = [ "write", "read", "write_file", + "emit", ]; #[derive(Debug, Clone)] @@ -204,13 +205,20 @@ pub fn expr_to_ir(expr: &Expr) -> (Option, Option) { } _ => return (None, Some(LoweringError { span: name.1.clone(), message: "Expected identifier".to_string(), note: None })) }; + let mut largs = Vec::new(); for arg in &args.0 { - let arg = expr_to_ir(&arg.0); - if_err_return!(arg.1); + let larg = expr_to_ir(&arg.0); + if_err_return!(larg.1); - largs.push(arg.0.unwrap()); + // Check if the args is string + if let IRKind::Value{ .. } = larg.0.clone().unwrap() { + largs.push(larg.0.clone().unwrap()); + } else { + return (None, Some(LoweringError { span: arg.1.clone(), message: "Expected string".to_string(), note: None })) + } } + let ir_kind = IRKind::Intrinsic { name, args: largs }; return (Some(ir_kind), None); }, diff --git a/example/emit.hz b/example/emit.hz new file mode 100644 index 0000000..e4d9090 --- /dev/null +++ b/example/emit.hz @@ -0,0 +1,3 @@ +fun main: void = do + @emit("console.log('Hello, World!')"); +end; \ No newline at end of file