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

Updated examples #7

Merged
merged 11 commits into from
Jun 14, 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/result/
/tmp/
/.direnv/

Expand Down
44 changes: 22 additions & 22 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 7 additions & 10 deletions crates/benda/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use bend::imp;
use num_traits::ToPrimitive;
use parser::Parser;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyFunction, PyString, PyTuple};
use rustpython_parser::{parse, Mode};
use types::extract_type;
use types::tree::{Leaf, Node, Tree};
use types::u24::u24;
use types::u24;
mod benda_ffi;
mod parser;
mod types;
Expand Down Expand Up @@ -68,15 +66,14 @@ impl PyBjit {
arg_list.push(arg.to_string());
}

let mut parsed_types: Vec<(String, imp::Expr)> = vec![];
let mut parsed_types: Vec<(String, Bound<PyAny>)> = vec![];

for (index, arg) in
args.downcast::<PyTuple>().unwrap().iter().enumerate()
{
parsed_types.push((
arg_list.get(index).unwrap().to_string(),
extract_type(arg).unwrap(),
));
let var_name = arg_list.get(index).unwrap().to_string();

parsed_types.push((var_name.clone(), arg));
}

let code = std::fs::read_to_string(filename.to_string()).unwrap();
Expand All @@ -97,7 +94,7 @@ impl PyBjit {
parsed_types.clone(),
);
let return_val =
parser.parse(fun_def.name.as_ref(), &[]);
parser.parse(name.to_string().as_ref(), &[]);
val = Some(PyString::new_bound(
py,
return_val.as_str(),
Expand All @@ -118,7 +115,7 @@ impl PyBjit {
fn benda(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(switch, m)?)?;
m.add_class::<PyBjit>()?;
m.add_class::<u24>()?;
m.add_class::<u24::u24>()?;
m.add_class::<Tree>()?;
m.add_class::<Node>()?;
m.add_class::<Leaf>()?;
Expand Down
1 change: 1 addition & 0 deletions crates/benda/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use pyo3::prelude::*;
use rustpython_parser::{parse, Mode};

mod benda_ffi;
mod types;

fn main() -> PyResult<()> {
let filename = String::from("main.py");
Expand Down
126 changes: 50 additions & 76 deletions crates/benda/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ use bend::fun::{self, Adt, Book, CtrField, Name, Op, Rule, STRINGS};
use bend::imp::{self, Expr, MatchArm, Stmt};
use indexmap::IndexMap;
use num_traits::cast::ToPrimitive;
use pyo3::{Bound, PyAny};
use rustpython_parser::ast::{
located, CmpOp as rCmpOp, Expr as rExpr, ExprAttribute, ExprBinOp,
Operator as rOperator, Pattern as rPattern, Stmt as rStmt, StmtAssign,
StmtClassDef, StmtExpr, StmtFunctionDef, StmtIf, StmtMatch,
};

use crate::benda_ffi::run;
use crate::types::{extract_type, extract_type_expr};

#[derive(Clone, Debug)]
enum FromExpr {
Expand Down Expand Up @@ -57,20 +59,20 @@ struct Context {
subs: Vec<String>,
}

pub struct Parser {
pub struct Parser<'py> {
statements: Vec<rStmt>,
book: Book,
definitions: Vec<imp::Definition>,
ctx: Option<Context>,
index: usize,
fun_args: Vec<(String, imp::Expr)>,
fun_args: Vec<(String, Bound<'py, PyAny>)>,
}

impl Parser {
impl<'py> Parser<'py> {
pub fn new(
statements: Vec<rStmt>,
index: usize,
fun_args: Vec<(String, imp::Expr)>,
fun_args: Vec<(String, Bound<'py, PyAny>)>,
) -> Self {
Self {
statements,
Expand Down Expand Up @@ -192,11 +194,15 @@ impl Parser {
}

rExpr::Call(c) => {
let fun = c.func;
let fun = c.clone().func;

let expr = self.parse_expr_type(*fun);

if let Some(FromExpr::Expr(Expr::Var { ref nam })) = expr {
if let Some(var) = extract_type_expr(c.clone()) {
return Some(FromExpr::Expr(var));
}

let mut args: Vec<Expr> = vec![];

for arg in c.args {
Expand Down Expand Up @@ -692,8 +698,8 @@ impl Parser {
}

// Creates a Bend Definition for each argument for the annotaded function.
fn parse_fun_args(&mut self) {
for (name, expr) in &self.fun_args {
fn parse_fun_args(&mut self, parsed_types: &Vec<(String, imp::Expr)>) {
for (name, expr) in parsed_types {
let u_type = expr.clone().to_fun();

let nam = Name::new(name.to_string());
Expand Down Expand Up @@ -724,76 +730,44 @@ impl Parser {
subs: vec![fun_name.to_string()],
});

self.parse_fun_args();
let mut parsed_types: Vec<(String, imp::Expr)> = vec![];

for (index, stmt) in
self.statements.clone().iter().skip(self.index).enumerate()
{
if let rStmt::Assign(assi) = stmt {
if let rExpr::Name(target) = assi.targets.first().unwrap() {
if py_args.contains(target.id.as_ref()) {
let body =
self.parse_vec(&self.statements.clone(), index);

if let Some(FromExpr::Statement(st)) = body {
return Some(imp::Definition {
name: Name::new("main"),
params: vec![],
body: st,
});
}
}
}
for arg in self.fun_args.iter() {
parsed_types.push((
arg.0.clone(),
extract_type(arg.1.clone(), &self.book).unwrap(),
));
}

if let rExpr::Call(call) = *assi.clone().value {
if let rExpr::Name(func) = *call.func {
if fun_name == func.id.to_string() {
if call.args.is_empty() {
panic!("The function must have arguments for Bend can run it.");
} else {
let new_body = self
.parse_vec(&self.statements.clone(), index);

if let Some(FromExpr::Statement(st)) = new_body
{
return Some(imp::Definition {
name: Name::new("main"),
params: vec![],
body: st,
});
}

let mut new_args: Vec<Expr> = vec![];

for arg in self.fun_args.clone() {
new_args.push(Expr::Var {
nam: Name::new(arg.0),
})
}

let first = Stmt::Return {
term: Box::new(Expr::Call {
fun: Box::new(imp::Expr::Var {
nam: Name::new(
fun_name.to_string(),
),
}),
args: new_args,
kwargs: vec![],
}),
};
return Some(imp::Definition {
name: Name::new("main"),
params: vec![],
body: first,
});
}
}
}
}
self.parse_fun_args(&parsed_types);

let mut new_args: Vec<Expr> = vec![];

for arg in parsed_types.clone() {
match arg.1 {
imp::Expr::Var { nam } => {}
_ => new_args.push(Expr::Var {
nam: Name::new(arg.0),
}),
}
}

let first = Stmt::Return {
term: Box::new(Expr::Call {
fun: Box::new(imp::Expr::Var {
nam: Name::new(fun_name.to_string()),
}),
args: new_args,
kwargs: vec![],
}),
};

return Some(imp::Definition {
name: Name::new("main"),
params: vec![],
body: first,
});

None
}

Expand Down Expand Up @@ -895,9 +869,9 @@ impl Parser {
}
}

if !is_bjit {
return;
}
//if !is_bjit {
//return;
//}

let args = *fun_def.args.clone();
let mut names: Vec<Name> = vec![];
Expand Down Expand Up @@ -946,7 +920,7 @@ impl Parser {

self.book.entrypoint = None;

println!("BEND:\n {}", self.book.display_pretty());
//println!("BEND:\n {}", self.book.display_pretty());

let return_val = run(&self.book);

Expand Down
Loading