Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for lambda funcs and function types #15

Merged
merged 4 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ This is an incredibly simple example of calculating the `n`'th Fibonacci sequenc
Currently the only way to observe output is via the return code of the program.

```
function fib(n: int32) -> int32
fun fib(n: int32) -> int32
if n == 0 then
return 0;
else if n == 1 then
Expand Down
2 changes: 1 addition & 1 deletion samples/add.ras
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function add(a: int64, b: int64) -> int64
fun add(a: int64, b: int64) -> int64
return a + b;
end

Expand Down
8 changes: 4 additions & 4 deletions samples/call.ras
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
function baz(x: int32, y: int32, z: int32) -> int32
let w = x + y + z;
fun foo(x: int32, y: int64) -> int32
let z = x;
let w = y;
end

program passing1
let x: int32 = 431;
let test = baz(x, x, x);
foo(12i32, 22i64);
end
2 changes: 1 addition & 1 deletion samples/fib.ras
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function fib(n: int32) -> int32
fun fib(n: int32) -> int32
if n == 0 then
return 0;
else if n == 1 then
Expand Down
2 changes: 1 addition & 1 deletion samples/float.ras
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function foo(x: float32) -> float32
fun foo(x: float32) -> float32
return 2.0 * x;
end

Expand Down
4 changes: 2 additions & 2 deletions samples/funcdef.ras
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
function foo(x: int32) -> int32
fun foo(x: int32) -> int32
return x + 4;
end

program test_program

function baz(x: int32, y: int32, z: int32) -> int32
fun baz(x: int32, y: int32, z: int32) -> int32
let w = x + y + z;
return w;
end
Expand Down
15 changes: 15 additions & 0 deletions samples/lambda.ras
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
fun foo(x: int32) -> int32
return x + 5;
end

program test_funcs
let f: (int32) -> int32 = foo;
let res = f(3);

let g = fun (x: int32) -> (1i32);

let h = fun (x: int32) begin
return 23;
end;
return h(2);
end
2 changes: 1 addition & 1 deletion samples/working.ras
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
let x = 3 * (4 + 5);

function baz(x: int32, y: int32) -> int32
fun baz(x: int32, y: int32) -> int32
let z = 4 * (4 / 5);
let y = 3;
return y;
Expand Down
11 changes: 9 additions & 2 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub enum Expr {
Not(Box<Expr>),
Neg(Box<Expr>),
Call(Symbol, Box<Args>),
LambdaFunc(LambdaFunc),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -121,13 +122,19 @@ pub struct Param {

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Func {
pub ret_t: types::Type,
pub return_t: types::Type,
pub params: Params,
pub with: With,
pub ident: String,
pub block: Block,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LambdaFunc {
pub return_t: types::Type,
pub params: Params,
pub block: Block,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Num {
Int32(i32),
Expand Down
88 changes: 68 additions & 20 deletions src/backends/c.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::codegen::{CodeGen, CodeGenContext, CodeGenError};
use crate::ir::{self, FuncDef, IRNode};
use crate::types::Type;
use crate::types::{self, Type};
use anyhow::Result;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::process::Command;
Expand All @@ -15,21 +16,6 @@ macro_rules! matches_variant {
};
}

pub fn translate_type(type_t: Type) -> String {
match type_t {
Type::Int32 => "int32_t",
Type::Int64 => "int64_t",
Type::UInt32 => "uint32_t",
Type::UInt64 => "uint64_t",
Type::Float32 => "float",
Type::Float64 => "double",
Type::Bool => "int32_t",
Type::String => "char*",
other => panic!("unknown type: {:?}", other),
}
.into()
}

pub fn translate_value(value: ir::Value) -> String {
match value {
ir::Value::Int32(num) => format!("INT32_C({})", num),
Expand Down Expand Up @@ -77,6 +63,9 @@ pub struct CGenContext {
outfile: String,
skip_validation: bool,
code_buffer: Vec<String>,
global_idx: usize,
type_counter: usize,
type_map: HashMap<types::Type, String>,
}

impl From<CodeGenContext> for CGenContext {
Expand All @@ -86,13 +75,17 @@ impl From<CodeGenContext> for CGenContext {
outfile: ctx.outfile,
skip_validation: ctx.skip_validation,
code_buffer: vec![],
global_idx: 0,
type_counter: 0,
type_map: HashMap::new(),
}
}
}

impl CodeGen for CGenContext {
fn gen(&mut self) -> Result<(), CodeGenError> {
self.gen_includes();
self.save_global_idx();
let start = self.gen_globals();
self.gen_program(start);

Expand Down Expand Up @@ -127,6 +120,56 @@ impl CGenContext {
self.code_buffer.push(code.into());
}

fn add_global_code(&mut self, code: &str) {
self.code_buffer.insert(self.global_idx, code.into());
self.global_idx += 1;
}

fn save_global_idx(&mut self) {
self.global_idx = self.code_buffer.len();
}

fn get_new_type_id(&mut self) -> usize {
let new_type = self.type_counter;
self.type_counter += 1;
new_type
}

fn translate_type(&mut self, type_t: Type) -> String {
match type_t.clone() {
Type::Int32 => "int32_t".into(),
Type::Int64 => "int64_t".into(),
Type::UInt32 => "uint32_t".into(),
Type::UInt64 => "uint64_t".into(),
Type::Float32 => "float".into(),
Type::Float64 => "double".into(),
Type::Bool => "int32_t".into(),
Type::String => "char*".into(),
Type::Function(func) => match self.type_map.get(&type_t.clone()) {
Some(val) => val.to_string(),
None => {
let typedef_name = format!("_func_type_{}", self.get_new_type_id());
self.type_map.insert(type_t.clone(), typedef_name.clone());
let param_types: Vec<String> = func
.params_t
.iter()
.map(|t| self.translate_type(t.clone()))
.collect();
let return_type: String = self.translate_type(*func.return_t.clone());
let joined_params = param_types.join(",");
self.add_global_code(&format!(
"typedef {} (*{})({});",
return_type,
typedef_name.clone(),
joined_params
));
typedef_name
}
},
other => panic!("unknown type: {:?}", other),
}
}

fn gen_includes(&mut self) -> Result<(), CodeGenError> {
self.add_code("#include \"stdint.h\"\n");
Ok(())
Expand Down Expand Up @@ -206,8 +249,11 @@ impl CGenContext {
}

fn gen_assign(&mut self, idx: usize, assign: ir::Assign) -> Result<usize, CodeGenError> {
if !matches_variant!(assign.type_t, Type::Function) {
self.add_code(&translate_type(assign.type_t));
if !(matches_variant!(assign.type_t, Type::Function)
&& matches_variant!(self.build_stack.get(idx - 1).unwrap(), IRNode::EndFuncDef))
{
let assignment_type = &self.translate_type(assign.type_t);
self.add_code(assignment_type);
self.add_code(&assign.symbol.ident.clone());
self.add_code("=");
self.gen_expr(idx - 1);
Expand Down Expand Up @@ -340,12 +386,14 @@ impl CGenContext {
}

fn gen_func_def(&mut self, idx: usize, def: FuncDef) -> Result<usize, CodeGenError> {
self.add_code(&translate_type(def.return_t));
let return_type = &self.translate_type(def.return_t);
self.add_code(return_type);
self.add_code(&def.symbol.ident);
self.add_code("(");
let num_params = def.params_t.clone().len();
for (n, param) in def.params_t.into_iter().enumerate() {
self.add_code(&translate_type(param.1));
let param_type = &self.translate_type(param.1);
self.add_code(param_type);
self.add_code(&param.0);
if n != num_params - 1 {
self.add_code(",");
Expand Down
31 changes: 13 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,7 @@ struct Args {
backend: BackendArgs,

// Emit: options will be any or both of ir, or C for dumping intermediate reps to file
#[arg(
short = 'e',
long = "emit",
value_parser,
value_delimiter = ',',
)]
#[arg(short = 'e', long = "emit", value_parser, value_delimiter = ',')]
emit: Option<Vec<EmitArgs>>,
}

Expand All @@ -59,7 +54,7 @@ enum EmitArgs {
C,
}

lalrpop_mod!(pub rascal_grammar);
lalrpop_mod!(pub rascal);

fn main() {
let args = Args::parse();
Expand All @@ -72,7 +67,7 @@ fn main() {
(save_c, save_ir) = (false, false);
}
let src_file = fs::read_to_string(args.infile).expect("ERROR: couldn't find source file");
let root = rascal_grammar::RootParser::new().parse(&src_file).unwrap();
let root = rascal::RootParser::new().parse(&src_file).unwrap();
// Perform semantic checks and type checking
let mut state = semantic::new_state(root);
state.build().unwrap();
Expand Down Expand Up @@ -103,7 +98,7 @@ fn root_parser_passing1() {
let y = 10;
end
"#;
assert!(rascal_grammar::ProgramParser::new().parse(source).is_ok());
assert!(rascal::ProgramParser::new().parse(source).is_ok());
}

#[test]
Expand All @@ -113,7 +108,7 @@ fn root_parser_failing1() {
1 + 2;
end
"#;
assert!(rascal_grammar::ProgramParser::new().parse(source).is_err());
assert!(rascal::ProgramParser::new().parse(source).is_err());
}

#[test]
Expand All @@ -123,7 +118,7 @@ fn type_checking_passing1() {
let x: int32 = 431;
end
"#;
let root = rascal_grammar::RootParser::new().parse(source).unwrap();
let root = rascal::RootParser::new().parse(source).unwrap();
let mut state = semantic::new_state(root);
// Perform semantic checks and type checking
let build_res = state.build();
Expand All @@ -134,12 +129,12 @@ fn type_checking_passing1() {
#[test]
fn type_checking_passing2() {
let source = r#"
function foo(a: float32, b: float32) -> float32
fun foo(a: float32, b: float32) -> float32
let c = a;
c *= b;
end

function baz(x: int32, y: int32, z: int32) -> int32
fun baz(x: int32, y: int32, z: int32) -> int32
let w = x + y + z;
end

Expand All @@ -148,7 +143,7 @@ fn type_checking_passing2() {
let test = baz(x, x, x);
end
"#;
let root = rascal_grammar::RootParser::new().parse(source).unwrap();
let root = rascal::RootParser::new().parse(source).unwrap();
let mut state = semantic::new_state(root);
// Perform semantic checks and type checking
let build_res = state.build();
Expand All @@ -159,7 +154,7 @@ fn type_checking_passing2() {
#[should_panic]
fn type_checking_func_failing1() {
let source = r#"
function foo(a: int32, b: float32) -> float32
fun foo(a: int32, b: float32) -> float32
let c = a;
let d = b;
end
Expand All @@ -169,7 +164,7 @@ fn type_checking_func_failing1() {
let test = foo(x, x);
end
"#;
let root = rascal_grammar::RootParser::new().parse(source).unwrap();
let root = rascal::RootParser::new().parse(source).unwrap();
let mut state = semantic::new_state(root);
// Perform semantic checks and type checking
let build_res = state.build();
Expand All @@ -186,7 +181,7 @@ fn type_checking_ifs_passing1() {
end
end
"#;
let root = rascal_grammar::RootParser::new().parse(source).unwrap();
let root = rascal::RootParser::new().parse(source).unwrap();
let mut state = semantic::new_state(root);
// Perform semantic checks and type checking
let build_res = state.build();
Expand All @@ -212,7 +207,7 @@ fn type_checking_ifs_passing2() {
end
end
"#;
let root = rascal_grammar::RootParser::new().parse(source).unwrap();
let root = rascal::RootParser::new().parse(source).unwrap();
let mut state = semantic::new_state(root);
// Perform semantic checks and type checking
let build_res = state.build();
Expand Down
Loading