Skip to content

Commit

Permalink
Dynamically Change Architecture when Compiling (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
lyledean1 committed Sep 3, 2023
1 parent d29c969 commit 01cef90
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@

A programming language I built in Rust - mainly for fun and my own learning! Uses PEG Parser in Rust for parsing and LLVM (llvm-sys) as the backend to compile to machine code binary. Very hacky and not production ready. Also will be coming back to refactor this now I have got recursion working, expect to find lots of bugs as I had a more extensive test suite.

Try the Fibonacci example in `/examples/fib.cyclo` (also make sure you have LLVM set up to run this locally)
Try the Fibonacci example in `/examples/fib.cyclo`

```
cargo run -- --file ./examples/fib.cyclo
```

*Note*: *this isn't the most efficient Fibonacci algorithm but it's just an example of using recursion in the language*
*Note*: *this isn't the most efficient Fibonacci algorithm but it's just an example of using recursion in the language, its also only been tested on an M1 Mac, so there might be bugs on other architectures*

```rust
fn fib(int n) -> int {
Expand All @@ -20,7 +16,11 @@ fn fib(int n) -> int {
print(fib(20));
```

This should output `6765`!
```
cargo run -- --file ./examples/fib.cyclo
```

This will output a binary to `./bin/main` which you can run. This should output `6765`!

## LLVM Set Up

Expand Down
10 changes: 8 additions & 2 deletions src/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::compiler::types::num::NumberType;
use crate::compiler::types::string::StringType;
use crate::compiler::types::void::VoidType;
use crate::compiler::types::TypeBase;
use std::ffi::CString;

use std::collections::HashMap;
use std::ffi::CStr;
Expand Down Expand Up @@ -88,8 +89,13 @@ fn llvm_compile_to_ir(exprs: Vec<Expression>) -> String {
ast_ctx.match_ast(expr);
}
LLVMBuildRetVoid(builder);
// write our bitcode file to arm64
LLVMSetTarget(module, c_str!("arm64"));

// get and set the architecture
let arch_str = std::env::consts::ARCH;
let c_str = CString::new(arch_str).expect("Failed to convert to CString");
let ptr: *const i8 = c_str.as_ptr() as *const i8;

LLVMSetTarget(module, ptr);
LLVMPrintModuleToFile(module, c_str!("bin/main.ll"), ptr::null_mut());
// Use Clang to output LLVM IR -> Binary
// LLVMWriteBitcodeToFile(module, c_str!("bin/main.bc"));
Expand Down

0 comments on commit 01cef90

Please sign in to comment.