81 Commits
Author SHA1 Message Date
selimaj-dev 010225d8d6 small changes 2024-08-03 11:42:42 +02:00
selimaj-dev 5b08de7d16 more statements 2024-07-29 04:30:00 +02:00
selimaj-dev ab840b36e4 :) 2024-07-27 09:21:34 +02:00
selimaj-dev 7f23772ec9 pointers 2024-07-27 04:40:48 +02:00
selimaj-dev 74f3d36c08 gitignore change 2024-07-27 00:55:50 +02:00
selimaj-dev 607e023ca4 enums and identifier encoder 2024-07-27 00:44:16 +02:00
selimaj-dev c48cad6817 added header wrappers and stdlib 2024-07-24 14:12:37 +02:00
selimaj-dev 1aab723c3f small features 2024-07-22 18:43:46 +02:00
Leo dev 2829b8834e Merge pull request #11 from wyst-lang/rewrite
Rewrite
2024-07-20 05:42:32 +02:00
selimaj-dev 653cf509ba . 2024-07-20 05:41:54 +02:00
selimaj-dev 4b1fbb0cc5 obfucated names and updated stdio printf 2024-07-20 05:27:25 +02:00
selimaj-dev 3a09288a52 changes 2024-07-19 21:02:27 +02:00
selimaj-dev 82bb846e09 fixed bugs 2024-07-14 20:00:00 +02:00
selimaj-dev 023ada1506 working transpiler 2024-07-14 18:13:08 +02:00
selimaj-dev 9e5079151b fixed bugs 2024-07-11 18:02:53 +02:00
selimaj-dev 84c69df276 using pest 2024-07-11 17:47:26 +02:00
selimaj-dev 573ba1f745 rd 2024-07-11 14:20:00 +02:00
selimaj-dev f4759f01c8 new compiler 2024-07-11 14:15:31 +02:00
selimaj-dev 58af9cdd95 error codes and compiler 2024-07-09 12:29:36 +02:00
Leo dev 30ed01f5a0 Update README.md 2024-07-06 14:00:45 +02:00
selimaj-dev 0137beff70 rust code 2024-07-06 13:43:49 +02:00
selimaj-dev e3ebe9d8d3 better variable manager 2024-07-03 17:17:25 +02:00
selimaj-dev 9b755b1821 better state system 2024-07-03 12:07:05 +02:00
selimaj-dev 3cb1ab90fd better errors and defs 2024-07-02 15:06:11 +02:00
selimaj-dev 41c6b99e26 functions 2024-07-01 18:24:02 +02:00
selimaj-dev 001636c799 curly 2024-07-01 18:12:06 +02:00
selimaj-dev d561682136 round brackets 2024-07-01 18:07:48 +02:00
selimaj-dev e9237eaf9a round brackets 2024-07-01 18:05:34 +02:00
selimaj-dev beff172ff4 better error checking 2024-06-29 19:48:11 +02:00
selimaj-dev 8cbe87d59c rewrite 1 2024-06-28 14:57:55 +02:00
selimaj-dev 3d694d4931 rewrite 1 2024-06-28 14:57:47 +02:00
selimaj-dev 910b638458 rewrive-rev01 2024-06-25 21:13:46 +02:00
selimaj-dev 15e0ff362c Added rust imports with header 2024-06-23 17:53:46 +02:00
selimaj-dev 9a614ef367 dll alpha_01 2024-06-21 19:01:51 +02:00
selimaj-dev 1490a367c2 dll reader_alpha 2024-06-21 11:57:53 +02:00
selimaj-dev 472ee1cb81 dll reader_alpha 2024-06-21 11:57:28 +02:00
selimaj-dev 387b247823 better module system 2024-06-20 16:10:26 +02:00
selimaj-dev 1edc714213 better module system 2024-06-20 16:10:10 +02:00
selimaj-dev ea7222255a New variable system and stage 1 error checking 2024-06-12 22:16:43 +02:00
selimaj-dev 3434b4c0bd changed variable system 2024-06-10 22:36:42 +02:00
selimaj-dev a19a864965 params fix 2024-06-09 15:23:17 +02:00
selimaj-dev c9a135f6d7 params 2024-06-09 15:01:38 +02:00
selimaj-dev d9dcce3ea3 fixed function variable bug 2024-06-08 20:06:32 +02:00
selimaj-dev ad00c78f0c added more variable detections 2024-06-08 18:59:46 +02:00
selimaj-dev e82dae5dfc few fixes 2024-06-07 14:29:27 +02:00
selimaj-dev 5fd9ab86bc small changes 2024-06-07 13:55:42 +02:00
selimaj-dev d3b252fb28 oops 2024-06-06 23:14:47 +02:00
selimaj-dev 8348c36394 Got the lsp working 2024-06-06 23:13:48 +02:00
selimaj-dev ed60ab7af4 working lsp 2024-06-06 17:42:28 +02:00
selimaj-dev 7699809a28 small change 2024-06-06 10:14:56 +02:00
selimaj-dev 5d27d5b4a9 small change 2024-06-06 10:12:41 +02:00
selimaj-dev a11ca49c35 lsp progress 2024-06-06 04:23:24 +02:00
selimaj-dev ee4b8e5891 just a small change 2024-06-05 19:50:23 +02:00
selimaj-dev 57d99b9526 attempt lsp from scratch 2024-06-05 17:43:05 +02:00
selimaj-dev c5331279da plan b 2024-06-05 15:58:17 +02:00
selimaj-dev a6a5b46a01 get_completion works but lsp doesn't 2024-06-04 22:57:57 +02:00
selimaj-dev 35653cff1f still no fix 2024-06-04 17:29:16 +02:00
selimaj-dev 5c367e6b44 var on parser 2024-06-04 14:35:34 +02:00
selimaj-dev 15ff863fbe alpha test 2024-06-03 20:10:35 +02:00
selimaj-dev 0b513c49c3 lsp server test 2024-06-03 13:25:41 +02:00
selimaj-dev e048e0e10c lsp server test 2024-06-03 13:23:20 +02:00
selimaj-dev 5fafd054b1 bug fixes 2024-05-25 13:12:09 +02:00
selimaj-dev 4cbf46da53 Impl's and pointers 2024-05-25 11:14:58 +02:00
selimaj-dev b3db964a8e better namespaces 2024-05-24 23:37:54 +02:00
selimaj-dev 0dd3410141 auto pub on namespaces 2024-05-24 23:30:01 +02:00
selimaj-dev 1da6b3db09 namespaces 2024-05-24 23:22:27 +02:00
selimaj-dev 8c32610737 for, while, if, else 2024-05-24 22:51:25 +02:00
selimaj-dev 93ba413251 small fix 2024-05-24 18:20:44 +02:00
selimaj-dev 33fc1d85dc local incl 2024-05-24 16:50:14 +02:00
selimaj-dev 5ca3722150 global incl 2024-05-24 16:47:02 +02:00
selimaj-dev ae281d70d1 added float and as 2024-05-18 17:43:39 +02:00
selimaj-dev a5e23db625 struct var defs 2024-05-16 18:07:48 +02:00
selimaj-dev 9dc8712364 structs 2024-05-15 19:57:55 +02:00
selimaj-dev e7142f6d80 oops 2024-05-12 17:16:12 +02:00
selimaj-dev 02245401b9 added json. By using HashMap 2024-05-12 17:15:38 +02:00
selimaj-dev 9d7e560feb angle brackets 2024-05-12 16:18:45 +02:00
selimaj-dev ff84b62d3b int change and smart spacing 2024-05-11 14:58:38 +02:00
selimaj-dev 86bf9778ee square and comments 2024-05-10 21:01:20 +02:00
selimaj-dev e95990b293 pointers 2024-05-10 15:07:48 +02:00
selimaj-dev 2fb2d7ef76 Merge branch 'master' of github.com:dev-orus/wyst 2024-05-10 15:06:50 +02:00
selimaj-dev 7aae829763 pointers 2024-05-10 15:06:17 +02:00
17 changed files with 1063 additions and 656 deletions
+14
View File
@@ -2,6 +2,9 @@
# will have compiled files and executables
debug/
target/
test/
.vscode/
.idea/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
@@ -22,3 +25,14 @@ Cargo.lock
#Wyst files for testing
*.wst
# Wyst build output taht contains rust files
/build
# Wyst compiled output
out
/log.txt
/lsp.log
+2 -1
View File
@@ -2,5 +2,6 @@
"rust-analyzer.linkedProjects": [
"./Cargo.toml"
],
"rust-analyzer.showUnlinkedFileNotification": false
"rust-analyzer.showUnlinkedFileNotification": false,
"cSpell.enabled": false
}
+12 -3
View File
@@ -6,6 +6,15 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
regex = "1.10.4"
once_cell = "1.19.0"
clap = { version = "4.0", features = ["derive"] }
rand = "0.8.5"
serde_json = "1.0"
serde = "1.0.203"
serde_derive = "1.0.203"
lsp-types = "0.97.0"
zip = "2.1.3"
dirs = "5.0.1"
pest = "2"
pest_derive = "2.1"
clap = "3"
hex = "0.4"
regex = "1.10.5"
+9
View File
@@ -7,5 +7,14 @@
<h3 align="center">Wyst is a programing language that has similar syntax to C and transpiles to Rust</h3>
```c
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
```
# Alpha
We are on pure alpha. if you would like to contribute please open a new issue.
+4
View File
@@ -0,0 +1,4 @@
# Wyst stdlib
## > [!NOTE]
> any changes made here should be documented before pushed to master
View File
+7
View File
@@ -0,0 +1,7 @@
#[macro_export]
macro_rules! _0x7072696e7466 {
($($arg:tt)*) => {
print!($($arg)*)
};
}
View File
+23
View File
@@ -0,0 +1,23 @@
use std::alloc::{alloc, Layout};
use std::ptr::null_mut;
// Malloc
pub fn _0x6d616c6c6f63(size: usize) -> *mut u8 {
if size == 0 {
return null_mut();
}
// Create a memory layout for the requested size
let layout = Layout::from_size_align(size, std::mem::align_of::<u8>()).unwrap();
// Allocate the memory
unsafe {
let ptr = alloc(layout);
if ptr.is_null() {
// Allocation failed
null_mut()
} else {
ptr
}
}
}
-55
View File
@@ -1,55 +0,0 @@
use std::fs;
use std::path::Path;
use std::process::Command;
use std::io::{Error, ErrorKind};
pub fn write_to_rust_file(transpiled_code: &str, file_name: &str) -> Result<(), Error> {
// Determine the file extension based on the provided file_name
let mut output_file = String::from(file_name);
if let Some(extension) = Path::new(file_name).extension() {
if let Some(ext_str) = extension.to_str() {
// Replace the existing extension with ".rs" if it's not already ".rs"
if ext_str != "rs" {
output_file.push_str(".rs");
}
}
} else {
// If no extension is provided, append ".rs" to the file_name
output_file.push_str(".rs");
}
// Write the transpiled_code to the determined output file
fs::write(&output_file, transpiled_code)?;
Ok(())
}
pub fn compile_to_executable(rust_file: &str, output_exe: &str) -> Result<(), Error> {
let output = Command::new("rustc")
.arg(rust_file)
.arg("-o")
.arg(output_exe)
.output()?;
// Check if compilation was successful
if output.status.success() {
println!("Compilation successful!");
} else {
if let Some(code) = output.status.code() {
eprintln!("Compilation failed with error code: {}", code);
}
if !output.stdout.is_empty() {
eprintln!("Compiler output:\n{}", String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
eprintln!("Compiler errors:\n{}", String::from_utf8_lossy(&output.stderr));
}
// Compilation failed, delete the temporary Rust file
if let Err(err) = fs::remove_file(rust_file) {
eprintln!("Failed to delete temporary Rust file: {}", err);
}
return Err(Error::new(ErrorKind::Other, "Compilation failed"));
}
Ok(())
}
+90
View File
@@ -0,0 +1,90 @@
use std::str;
use std::{fs, path::Path, process::Command};
use crate::{
transpiler::{State, Transpiler},
utils::{Problem, ProblemCap, ProblemType},
};
pub fn transpile_file(input_file: String, output_file: String, is_main: bool) -> u8 {
let mut ecode: u8 = 0;
let mut trsp = Transpiler {
..Default::default()
};
if let Ok(file_contents) = fs::read_to_string(input_file) {
let mut module_code = String::new();
let mut output_code = String::new();
match trsp.transpile_code(file_contents, 0) {
Ok(rcode) => output_code += rcode.as_str(),
Err(e) => {
ecode = 1;
println!("{e}")
}
}
if is_main {
for module in trsp.clone().mod_manager.modules {
module_code += "mod ";
module_code += module.rs_mod.as_str();
module_code += ";\n";
}
}
output_code = format!(
"{module_code}\n{output_code}\nfn main() {}{}{}",
"{_0x",
hex::encode("main"),
"();}"
);
if let Ok(_) = fs::write(Path::new("build").join(output_file), output_code) {
trsp.problems.append(&mut trsp.mod_manager.write());
}
} else {
trsp.problems.push(ProblemCap::Error(Problem {
problem_msg: "File not found".to_string(),
problem_type: ProblemType::FileNotFound,
state: State {
line: 0,
column: 0,
file: None,
},
}))
}
for p in trsp.problems {
match p {
ProblemCap::Error(problem) => {
ecode = 1;
if problem.state.file == None {
println!(
"\x1b[31;1m{:?}\x1b[0;1m: {}",
problem.problem_type, problem.problem_msg,
)
} else {
println!(
"\x1b[31;1mError\x1b[0;1m: {}\x1b[0m\n{}:{}: {:?}",
problem.problem_msg,
problem.state.line,
problem.state.column,
problem.problem_type,
)
}
}
}
}
ecode
}
pub fn compile_rust(exe_file: String) {
let output = Command::new("rustc")
.arg(Path::new("build").join("main.rs"))
.arg("-o")
.arg(exe_file.clone())
.output()
.expect("Error compiling rust: ");
if &output.stderr.len() == &0 {
println!("Compiled successfully: \x1b[34;4m{}", exe_file.clone());
} else {
println!(
"{}",
str::from_utf8(&output.stderr).expect("Error encoding stderr")
);
}
}
-288
View File
@@ -1,288 +0,0 @@
use regex::Regex;
use once_cell::sync::Lazy;
use std::fmt;
pub struct LexerState {
pub line: usize,
pub column: usize
}
// Define token types
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum TokenType {
Keyword,
Newline,
Whitespace,
Number,
Identifier,
Ptr,
Operator,
SecondOperator,
Semicolon,
Round,
Curly,
Square,
Include,
String,
// EOF,
}
#[derive(Clone)]
pub struct Token {
pub token_type: TokenType,
pub value: String,
pub line: usize,
pub column: usize
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(TokenType: {:?}, TokenValue: {}, Line: {}, Column {})", self.token_type, self.value.replace("\n", "\\n"), self.line, self.column)
}
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(\x1b[33mTokenType:\x1b[0m \x1b[35m{:?}\x1b[0m, \x1b[33mTokenValue:\x1b[0m \x1b[32m\"{}\"\x1b[0m, \x1b[33mLine:\x1b[0m \x1b[36m{}\x1b[0m, \x1b[33mColumn:\x1b[0m \x1b[36m{}\x1b[0m)", self.token_type, self.value.replace("\n", "\\n"), self.line, self.column)
}
}
pub struct Node {
token_type: TokenType,
token_regex: Lazy<Regex>
}
const SYNTAX: [Node; 14] = [
Node {
token_type: TokenType::Semicolon,
token_regex: Lazy::new(|| Regex::new(r"^\;").unwrap())
},
Node {
token_type: TokenType::SecondOperator,
token_regex: Lazy::new(|| Regex::new(r"^,").unwrap())
},
Node {
token_type: TokenType::String,
token_regex: Lazy::new(|| Regex::new("^\"").unwrap())
},
Node {
token_type: TokenType::Whitespace,
token_regex: Lazy::new(|| Regex::new(r"^\s+").unwrap())
},
Node {
token_type: TokenType::Keyword,
token_regex: Lazy::new(|| Regex::new(r"^mut|try|catch|return|fn\b").unwrap())
},
Node {
token_type: TokenType::Identifier,
token_regex: Lazy::new(|| Regex::new(r"^[._a-zA-Z][a-zA-Z0-9_]*(:?\s*<[._a-zA-Z][a-zA-Z0-9_<>]*>)?").unwrap())
},
Node {
token_type: TokenType::Number,
token_regex: Lazy::new(|| Regex::new(r"^(:?.)?(:?0[x|X])?\d+(:?.\d+)?\b").unwrap())
},
Node {
token_type: TokenType::Ptr,
token_regex: Lazy::new(|| Regex::new(r"^->").unwrap())
},
Node {
token_type: TokenType::Operator,
token_regex: Lazy::new(|| Regex::new(r"^[|\-|\+|\*|\=|\!]").unwrap())
},
Node {
token_type: TokenType::Round,
token_regex: Lazy::new(|| Regex::new(r"^[\(|\)]").unwrap())
},
Node {
token_type: TokenType::Curly,
token_regex: Lazy::new(|| Regex::new(r"^[\{|\}]").unwrap())
},
Node {
token_type: TokenType::Square,
token_regex: Lazy::new(|| Regex::new(r"^[\[|\]]").unwrap())
},
Node {
token_type: TokenType::Include,
token_regex: Lazy::new(|| Regex::new(r"^#include *<(.*?)>").unwrap())
},
Node {
token_type: TokenType::Include,
token_regex: Lazy::new(|| Regex::new(r#"^#include *"(.*?)""#).unwrap())
}
];
fn get_first_char(value: &str) -> String {
value.chars().next().unwrap().to_string()
}
pub fn lex(mut code: &str, use_whitespace: bool, state: LexerState) -> Result<Vec<Token>, (LexerState, Vec<Token>)> {
let mut state = state;
let mut tokens: Vec<Token> = Vec::new();
let mut brstr: String = String::new();
let mut br_state: LexerState = LexerState { line: 0, column: 0 };
let mut brtp: Vec<u8> = Vec::new();
while !code.is_empty() {
let mut is_match = false;
let fch = get_first_char(code);
let brln = brtp.len();
match fch.as_str() {
"\"" => {
brstr += "\"";
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 && brtp[brln-1] == 0 {
brtp.pop();
tokens.push(Token {
token_type: TokenType::String,
value: brstr.clone(),
column: br_state.column,
line: br_state.line
});
brstr = String::new();
} else if brln == 0 {
brtp.push(0);
br_state.line = state.line;
br_state.column = state.column;
}
}
"'" => {
brstr += "'";
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 && brtp[brln-1] == 1 {
brtp.pop();
tokens.push(Token {
token_type: TokenType::String,
value: brstr.clone(),
column: br_state.column,
line: br_state.line
});
brstr = String::new();
} else if brln == 0 {
brtp.push(1);
br_state.line = state.line;
br_state.column = state.column;
}
}
"(" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 {
brstr += fch.as_str();
} else {
br_state.line = state.line;
br_state.column = state.column;
}
brtp.push(2);
}
")" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 && brtp[brln-1] == 2 {
brtp.pop();
if brln == 1 {
tokens.push(Token {
token_type: TokenType::Round,
value: brstr.clone(),
column: br_state.column,
line: br_state.line
});
brstr = String::new();
} else {brstr += fch.as_str();}
} else {brstr += fch.as_str();}
}
"{" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 {
brstr += fch.as_str();
} else {
br_state.line = state.line;
br_state.column = state.column;
}
brtp.push(3);
}
"}" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 && brtp[brln-1] == 3 {
brtp.pop();
if brln == 1 {
tokens.push(Token {
token_type: TokenType::Curly,
value: brstr.clone(),
column: br_state.column,
line: br_state.line
});
brstr = String::new();
} else {brstr += fch.as_str();}
} else {brstr += fch.as_str();}
}
"[" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 {
brstr += fch.as_str();
} else {
br_state.line = state.line;
br_state.column = state.column;
}
brtp.push(3);
}
"]" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 && brtp[brln-1] == 3 {
brtp.pop();
if brln == 1 {
tokens.push(Token {
token_type: TokenType::Square,
value: brstr.clone(),
column: br_state.column,
line: br_state.line
});
brstr = String::new();
} else {brstr += fch.as_str();}
} else {brstr += fch.as_str();}
}
"\\" => {
brstr += "\\";
code = code.strip_prefix(fch.as_str()).expect("");
if code.len() > 0 {
let sch = get_first_char(code);
code = code.strip_prefix(sch.as_str()).expect("");
brstr += &sch;
}
}
"\n" => {
code = code.strip_prefix(fch.as_str()).expect("");
if brln > 0 {
brstr += "\n";
}
state.line += 1;
state.column = 0;
}
_ => {
if brln > 0 {
code = code.strip_prefix(fch.as_str()).expect("");
brstr += fch.as_str();
} else {
for s in &SYNTAX {
if let Some(caps) = s.token_regex.captures(code) {
is_match = true;
code = code.strip_prefix(&caps[0]).unwrap_or(code);
if (!use_whitespace && s.token_type!=TokenType::Whitespace) || use_whitespace {
tokens.push(Token {
token_type: s.token_type,
value: caps[0].to_string(),
line: state.line,
column: state.column
});
}
state.column += caps[0].len();
} else {
continue;
};
break;
}
if !is_match {
return Err((state, tokens));
}
}
}
}
}
Ok(tokens)
}
+79 -46
View File
@@ -1,55 +1,88 @@
use std::str;
use std::thread::sleep;
use std::time::Duration;
use std::{fs, io::Read, process};
mod compiler;
mod transpiler;
mod parser;
mod lexer;
mod compile;
use std::fs;
use clap::Parser;
use lexer::LexerState;
mod utils;
// Arguments for Wyst (short and long version)
#[derive(Parser)]
struct Args {
#[clap()]
file: std::path::PathBuf,
#[clap(short, long)]
rust: Option<String>,
#[clap(short, long)]
compile: Option<String>,
}
use clap::{App, Arg};
use compiler::{compile_rust, transpile_file};
use utils::match_code;
fn main() {
let args = Args::parse();
let file_content = fs::read_to_string(&args.file)
.expect("Error reading file");
let transpiled_code = transpiler::transpile(file_content, 0, LexerState { line: 1, column: 0 });
match args.rust {
Some(ref rust_file_name) => {
// Write transpiled code to Rust file
compile::write_to_rust_file(&transpiled_code, rust_file_name)
.expect("Error writing to Rust file");
println!("Transpiled code written to {}", rust_file_name);
let matches = App::new("Wyst")
.version("0.51")
.author("Orus")
.about("The wyst compiler")
.arg(
Arg::with_name("file")
.required_unless_one(&["stdio", "hex", "logo"])
.help("Sets the input file to use"),
)
.arg(
Arg::with_name("output")
.short('o')
.long("output")
.takes_value(true)
.help("Specifies the output binary file name"),
)
.arg(
Arg::with_name("build")
.short('b')
.long("build")
.help("Puts the rust files in the build directory"),
)
.arg(
Arg::with_name("stdio")
.short('s')
.long("stdio")
.help("LSP Mode"),
)
.arg(
Arg::with_name("hex")
.short('h')
.long("hex")
.takes_value(true)
.help("Turn an identifier into hex"),
)
.arg(Arg::with_name("logo").long("logo").hide(true))
.get_matches();
if matches.is_present("logo") {
println!("{}", utils::LOGO);
let mut byte = [4; 4];
std::io::stdin().read_exact(&mut byte).unwrap();
let egg = str::from_utf8(&byte).unwrap().to_string();
let mut counter: u8 = 30;
if egg == "logo" {
loop {
if counter == 35 {
counter = 30;
}
println!("\x1B[2J\x1B[{}m{}", counter, utils::LOGO);
sleep(Duration::from_millis(400));
counter += 1;
}
}
None => {
// No Rust file specified, print transpiled code
println!("{}", transpiled_code);
} else if matches.is_present("stdio") {
println!(
"{:?}",
match_code("void testme(int x) {}\ntest".to_string(), 1, 3).unwrap()
);
} else if matches.is_present("hex") {
let ident = matches.value_of("hex").unwrap().to_string();
println!("_0x{}", hex::encode(ident));
} else {
let file = matches.value_of("file").unwrap().to_string();
let output = matches.value_of("output").unwrap_or("out").to_string();
if let Ok(_) = fs::create_dir("build") {}
let ecode = transpile_file(file, "main.rs".to_string(), true);
if ecode == 0 {
compile_rust(output);
}
}
match args.compile {
Some(ref exe_name) => {
// Compile transpiled Rust code into executable
compile::write_to_rust_file(&transpiled_code, "temp.rs")
.expect("Error writing to temporary Rust file");
compile::compile_to_executable("temp.rs", exe_name)
.expect("Error compiling to executable");
fs::remove_file("temp.rs")
.expect("Error removing temporary Rust file");
println!("Compiled executable: {}", exe_name);
if !matches.is_present("build") {
fs::remove_dir_all("build").expect("Error removing build");
}
None => {}
process::exit(ecode as i32);
}
}
-120
View File
@@ -1,120 +0,0 @@
use crate::lexer::{Token, TokenType};
use std::fmt;
use regex::Regex;
use once_cell::sync::Lazy;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AstType {
FunctionDeceleration,
VoidFunctionDeceleration,
VariableDeceleration,
MutVariableDeceleration,
Include,
IncludeLocal,
CodeBlock,
Other
}
pub struct Ast {
pub tokens: Vec<Token>,
pub ast_type: AstType
}
impl fmt::Display for Ast {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\x1b[36m{:?}:\x1b[0m [\n", self.ast_type)?;
for (i, token) in self.tokens.iter().enumerate() {
if i < self.tokens.len() - 1 {
write!(f, " {},\n", token)?;
} else {
write!(f, " {}\n", token)?;
}
}
write!(f, "]")
}
}
impl fmt::Debug for Ast {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}: [\n", self.ast_type)?;
for (i, token) in self.tokens.iter().enumerate() {
if i < self.tokens.len() - 1 {
write!(f, " {:?},\n", token)?;
} else {
write!(f, " {:?}\n", token)?;
}
}
write!(f, "]")
}
}
pub struct Parser {
pub tokens: Vec<Token>,
pub index: u32,
pub include_regex: Lazy<Regex>,
pub include_regex_local: Lazy<Regex>
}
impl Parser {
pub fn new(tokens: Vec<Token>) -> Parser {
Parser {
tokens: tokens,
index: 0,
include_regex: Lazy::new(|| Regex::new(r"^(#include *)<(.*?)>").unwrap()),
include_regex_local: Lazy::new(|| Regex::new(r#"^(#include *)"(.*?)""#).unwrap())
}
}
pub fn next(&mut self) -> Ast {
let mut ast_res: Ast = Ast {tokens: vec![], ast_type: AstType::Other};
let index = self.index as usize;
if index == self.tokens.len() {panic!("Reached the end of tokens")}
let token = &self.tokens[index];
match token.token_type {
TokenType::Identifier => {
ast_res.tokens.push(self.tokens[index].clone());
if self.tokens.len()-index > 3 && self.tokens[index+1].token_type==TokenType::Identifier && self.tokens[index+2].token_type==TokenType::Round && self.tokens[index+3].token_type==TokenType::Curly {
ast_res.tokens.push(self.tokens[index+1].clone());
ast_res.tokens.push(self.tokens[index+2].clone());
ast_res.tokens.push(self.tokens[index+3].clone());
if token.value == "void" {
ast_res.ast_type = AstType::VoidFunctionDeceleration;
} else {
ast_res.ast_type = AstType::FunctionDeceleration;
}
self.index += 3;
} else if self.tokens.len()-index > 1 {
if token.value == "cb" && self.tokens[index+1].token_type == TokenType::Curly {
ast_res.tokens.push(self.tokens[index+1].clone());
ast_res.ast_type = AstType::CodeBlock;
self.index += 1;
} else if self.tokens[index+1].token_type==TokenType::Identifier {
ast_res.tokens.push(self.tokens[index+1].clone());
ast_res.ast_type = AstType::VariableDeceleration;
self.index += 1;
} else if self.tokens[index+1].value=="mut" && self.tokens[index+2].token_type==TokenType::Identifier {
ast_res.tokens.push(self.tokens[index+2].clone());
ast_res.ast_type = AstType::MutVariableDeceleration;
self.index += 2;
}
}
}
TokenType::Include => {
if let Some(caps) = self.include_regex.captures(&token.value) {
ast_res.tokens.push(Token {token_type: TokenType::String, value: caps[2].to_owned().to_string(), line: 0, column: 0});
ast_res.ast_type = AstType::Include;
} else if let Some(caps) = self.include_regex_local.captures(&token.value) {
ast_res.tokens.push(Token {token_type: TokenType::String, value: caps[2].to_owned().to_string(), line: 0, column: 0});
ast_res.ast_type = AstType::IncludeLocal;
} else {
ast_res.tokens.push(token.clone());
ast_res.ast_type = AstType::Include;
}
}
_ => {
ast_res.tokens.push(token.clone());
}
}
self.index += 1;
ast_res
}
}
+425 -139
View File
@@ -1,150 +1,436 @@
use crate::lexer::{lex, LexerState, TokenType};
use crate::parser::{Parser, AstType};
use crate::utils::{ModManager, ProblemCap};
use pest::iterators::{Pair, Pairs};
use serde::{Deserialize, Serialize};
pub fn transpile(input: String, indent: u32, state: LexerState) -> String {
let mut result = String::new();
// The Parser
use pest::{error::Error, Parser};
use pest_derive::Parser;
#[derive(Parser)]
#[grammar = "wyst.pest"]
pub struct WystParser;
if indent == 0 {
result += "type int = i32;\n";
} else {
result += " ".repeat((indent as usize) * 2).as_str();
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct State {
pub line: u32,
pub column: u32,
pub file: Option<String>,
}
let lexer_out = lex(input.as_str(), false, state);
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Transpiler {
pub problems: Vec<ProblemCap>,
pub state: State,
pub inject: Inject,
pub mod_manager: ModManager,
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Inject {
pub state: State,
pub inject: bool,
}
match lexer_out {
Ok(tokens) => {
let mut full_ast = Parser::new(tokens.clone());
while full_ast.tokens.len() > full_ast.index as usize {
let ast = full_ast.next();
println!("{ast}");
if ast.ast_type == AstType::FunctionDeceleration {
result += format!(
"fn {}({}) -> {} {}",
ast.tokens[1].value,
transpile_round(ast.tokens[2].value.clone(), LexerState {
line: ast.tokens[2].line,
column: ast.tokens[2].column
}),
ast.tokens[0].value,
transpile(
ast.tokens[3].value.clone(),
indent + 1,
LexerState {
line: ast.tokens[3].line,
column: ast.tokens[3].column
}
)
)
.as_str();
} else if ast.ast_type == AstType::VoidFunctionDeceleration {
result += format!(
"fn {}({}) {}",
ast.tokens[1].value,
transpile_round(ast.tokens[2].value.clone(), LexerState {
line: ast.tokens[2].line,
column: ast.tokens[2].column
}),
transpile(
ast.tokens[3].value.clone(),
indent + 1,
LexerState {
line: ast.tokens[3].line,
column: ast.tokens[3].column
}
)
)
.as_str();
} else if ast.ast_type == AstType::VariableDeceleration {
result += format!("let {}: {}", ast.tokens[1].value, ast.tokens[0].value).as_str();
} else if ast.ast_type == AstType::MutVariableDeceleration {
result += format!("let mut {}: {}", ast.tokens[1].value, ast.tokens[0].value).as_str();
} else if ast.tokens.len() == 1 && ast.tokens[0].token_type == TokenType::Round {
result += format!(
"({})",
transpile_round(ast.tokens[0].value.clone(), LexerState {
line: ast.tokens[0].line,
column: ast.tokens[0].column
})
)
.as_str();
} else if ast.tokens.len() == 1 && ast.tokens[0].token_type == TokenType::Curly {
if ast.tokens[0].token_type == TokenType::Newline {
result += (ast.tokens[0].value.as_str().to_owned()
+ (" ".repeat((indent as usize) * 2).as_str()))
.as_str();
} else {
result += ast.tokens[0].value.as_str();
}
} else {
if ast.tokens[0].token_type == TokenType::Newline {
result += (ast.tokens[0].value.as_str().to_owned()
+ (" ".repeat((indent as usize) * 2).as_str()))
.as_str();
} else if ast.tokens[0].token_type == TokenType::Semicolon {
result += ";\n";
result += " ".repeat((indent as usize) * 2).as_str();
} else {
result += ast.tokens[0].value.as_str();
}
}
}
result = result.trim_end().to_string();
if indent > 0 {
result += "\n";
result += " ".repeat((indent as usize - 1) * 2).as_str();
return "{\n".to_owned() + result.as_str() + "}";
} else {
return result;
}
}
Err((state, _tokens)) => {
println!("Invalid syntax at code.ws:{}:{}", state.line, state.column);
return "".to_string();
impl Default for Inject {
fn default() -> Self {
Inject {
inject: false,
state: State {
line: 0,
column: 0,
file: None,
},
}
}
}
pub fn transpile_round(input: String, state: LexerState) -> String {
let mut result = String::new();
let lexer_out = lex(input.as_str(), false, state);
match lexer_out {
Ok(tokens) => {
let mut full_ast = Parser::new(tokens.clone());
while full_ast.tokens.len() > full_ast.index as usize {
let ast = full_ast.next();
println!("{ast}");
if ast.ast_type == AstType::VariableDeceleration {
result += format!("{}: {}", ast.tokens[1].value, ast.tokens[0].value).as_str();
} else if ast.ast_type == AstType::MutVariableDeceleration {
result += format!("mut {}: {}", ast.tokens[1].value, ast.tokens[0].value).as_str();
} else if ast.tokens.len() == 1 && ast.tokens[0].token_type == TokenType::Round {
result += format!(
"({})",
transpile_round(ast.tokens[0].value.clone(), LexerState {
line: ast.tokens[0].line,
column: ast.tokens[0].column
})
)
.as_str();
} else {
result += ast.tokens[0].value.as_str()
}
}
result = result.trim_end().to_string();
result
}
Err((state, _tokens)) => {
println!("Invalid syntax at code.ws:{}:{}", state.line, state.column);
return "".to_string();
impl Default for Transpiler {
fn default() -> Self {
Transpiler {
inject: Inject::default(),
problems: Vec::new(),
mod_manager: ModManager::new(),
state: State {
line: 1,
column: 0,
file: None,
},
}
}
}
pub fn to_indexable(pairs: Pairs<Rule>) -> Vec<Pair<Rule>> {
let mut arr: Vec<Pair<Rule>> = Vec::new();
for pair in pairs {
arr.push(pair)
}
arr
}
impl Transpiler {
pub fn encode_ident(&mut self, ident: &str) -> String {
match WystParser::parse(Rule::def_identifier, ident) {
Ok(parsed) => {
let mut output = String::new();
for pair in parsed {
let tokens = to_indexable(pair.clone().into_inner());
for t in tokens {
match t.as_rule() {
Rule::identifier => {
let ident = t.as_str().trim();
let mut ident_rs = String::from("_0x");
let ident_chars: Vec<char> = ident.chars().collect();
for i in 0..ident_chars.len() {
let current = ident_chars[i];
if ident_chars.len() > i + 1 {
let next = ident_chars[i + 1];
if current == '.' {
ident_rs += "._0x";
} else if current == ':' && next == ':' {
ident_rs += "::_0x";
} else {
if current != ':' && current != '.' {
ident_rs +=
hex::encode(current.to_string()).as_str();
}
}
} else {
if current == '.' {
ident_rs += "._0x";
} else {
ident_rs += hex::encode(current.to_string()).as_str();
}
}
}
if self.mod_manager.macros.contains(&ident_rs) {
output += ident_rs.as_str();
output += "!";
} else {
output += match ident {
"void" => "()",
"int" => "i32",
"float" => "f64",
"Vec" => "Vec",
"bool" => "bool",
_ => {
if self.mod_manager.map.contains_key(ident) {
self.mod_manager.map.get(ident).unwrap()
} else {
ident_rs.as_str()
}
}
};
}
}
Rule::def_identifier => {
output += "<";
output += self.encode_ident(t.as_str()).as_str();
output += ">";
}
_ => {}
}
}
}
output
}
Err(_) => String::new(),
}
}
pub fn transpile_pairs(&mut self, pairs: Pairs<Rule>) -> String {
let mut res = String::new();
for pair in pairs {
res += self.transpile(pair).as_str();
}
res
}
pub fn transpile_vec(&mut self, pairs: Vec<Pair<Rule>>) -> String {
let mut res = String::new();
for pair in pairs {
res += self.transpile(pair).as_str();
}
res
}
pub fn transpile(&mut self, pair: Pair<Rule>) -> String {
let mut res = String::new();
let tokens = to_indexable(pair.clone().into_inner());
match pair.as_rule() {
Rule::func_def => {
res += format!(
"pub fn {}({}) -> {} {}\n",
self.transpile(tokens[1].clone()),
self.transpile_pairs(tokens[2].clone().into_inner())
.as_str()
.replace("let mut", ""),
self.transpile(tokens[0].clone()),
self.transpile(tokens[3].clone())
)
.as_str();
}
Rule::ptr_fn_def => {
res += format!(
"pub fn {}({}) -> &mut {} {}\n",
self.transpile(tokens[1].clone()),
self.transpile_pairs(tokens[2].clone().into_inner())
.as_str()
.replace("let mut", ""),
self.transpile(tokens[0].clone()),
self.transpile(tokens[3].clone())
)
.as_str();
}
Rule::var_def_ptr => {
res += format!(
"let mut {}: &mut {}",
self.transpile(tokens[1].clone()),
self.transpile(tokens[0].clone())
)
.as_str();
}
Rule::var_def => {
if tokens.len() == 1 {
res += self.transpile(tokens[0].clone()).as_str();
} else {
res += format!(
"let mut {}: {}",
self.transpile(tokens[1].clone()),
self.transpile(tokens[0].clone())
)
.as_str();
}
}
Rule::var_def_set => {
res += format!(
"{} = {}",
self.transpile(tokens[0].clone()),
self.transpile(tokens[1].clone()),
)
.as_str();
}
Rule::curly => {
res += "{";
res += &self.transpile_pairs(pair.clone().into_inner());
res += "}";
}
Rule::code_expr => {
res += &self.transpile_pairs(pair.clone().into_inner());
}
Rule::include_global => {
res += "#[allow(unused_imports)]\nuse ";
res += self
.mod_manager
.add(&mut self.clone(), tokens[0].as_str().to_string(), true)
.as_str();
res += "::*;\n";
}
Rule::include => {
res += "#[allow(unused_imports)]\nuse ";
res += self
.mod_manager
.add(&mut self.clone(), tokens[0].as_str().to_string(), false)
.as_str();
res += "::*;\n";
}
Rule::identifier | Rule::def_identifier => {
res += self.encode_ident(pair.as_str().trim()).as_str();
}
Rule::call => {
res += " ";
res += self.transpile(tokens[0].clone()).as_str();
res += self.transpile(tokens[1].clone()).as_str();
}
Rule::round => {
res += "(";
res += self.transpile_pairs(pair.into_inner()).as_str();
res += ")";
}
Rule::expr => {
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::term => {
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::struct_def => {
res += "struct ";
res += self.transpile(tokens[0].clone()).as_str();
res += "{";
res += self.transpile(tokens[1].clone()).as_str();
res += "}";
}
Rule::semicolon => {
res += ";\n";
}
Rule::string => {
res += pair.as_str();
}
Rule::map => {
self.mod_manager.map.insert(
tokens[0].as_str().to_string(),
tokens[2].as_str().to_string(),
);
}
Rule::enum_def => {
res += format!(
"enum {} {}{}{}",
self.transpile(tokens[0].clone()),
"{",
self.transpile_pairs(tokens[1].clone().into_inner()),
"}\n"
)
.as_str();
}
Rule::ecall => {
res += self.transpile(tokens[0].clone()).as_str();
if tokens.len() > 1 {
let mut params = tokens.clone();
params.remove(0);
res += "(";
res += self.transpile_vec(params).as_str();
res += ")";
}
}
Rule::comma => {
res += ",";
}
Rule::ptr_set => {
res += format!(
"*{} = {}",
self.transpile(tokens[0].clone()),
self.transpile(tokens[1].clone()),
)
.as_str();
}
Rule::int => {
res += " ";
res += pair.as_str();
res += " ";
}
Rule::refrence => {
res += "&mut ";
res += self.transpile(tokens[0].clone()).as_str();
}
Rule::return_stm => {
res += "return ";
res += self.transpile(tokens[0].clone()).as_str();
}
Rule::if_stm => {
res += "if ";
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::else_if_stm => {
res += "else if ";
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::else_stm => {
res += "else ";
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::bool => {
res += pair.as_str();
}
Rule::operator => {
res += pair.as_str();
}
Rule::if_operator => {
res += pair.as_str();
}
Rule::if_expr => {
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::namespace_def => {
res += "mod ";
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::top_code => {
res += "{";
res += self.transpile_pairs(pair.into_inner()).as_str();
res += "}";
}
Rule::top_expr => {
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::impl_def => {
res += "impl ";
res += self.transpile_pairs(pair.into_inner()).as_str();
}
Rule::match_name => {
let to_match = tokens[0].clone().as_str();
let match_id = tokens[1].clone().as_str();
res += "\n";
res += self.encode_ident(to_match).as_str();
res += "<match:";
res += match_id;
res += ">";
}
Rule::operation => {
for i in 0..tokens.len() {
let token = tokens[i].clone();
if i % 2 == 0 {
res += self.transpile(token).as_str();
} else {
res += token.as_str();
}
}
}
_ => {
println!("\x1b[33mNot Handled: {}\x1b[0m", pair);
res += " ";
res += pair.as_str();
res += " ";
}
}
res
}
pub fn transpile_code(&mut self, code: String, indent: usize) -> Result<String, Error<Rule>> {
let mut res = String::new();
match WystParser::parse(Rule::top_expr, &code) {
Ok(parsed) => {
for pair in parsed {
res += self.transpile_pairs(pair.into_inner()).as_str();
}
}
Err(e) => {
return Err(e);
}
}
if indent > 0 {
res += " ".repeat(indent * 2).as_str();
}
if indent > 0 {
res += "\n";
res += " ".repeat((indent - 1) * 2).as_str();
}
Ok(res)
}
}
+273
View File
@@ -0,0 +1,273 @@
use crate::transpiler::{Rule, State, Transpiler, WystParser};
use dirs::home_dir;
use pest::Parser;
use rand::random;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ProblemType {
VariableNotFound,
FileNotFound,
HeaderSyntaxError,
SyntaxError,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ProblemCap {
Error(Problem),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Problem {
pub problem_type: ProblemType,
pub problem_msg: String,
pub state: State,
}
#[derive(Debug, Clone)]
pub struct Module {
pub rs_mod: String,
pub file_path: String,
pub code: String,
}
#[derive(Debug, Clone)]
pub struct ModManager {
pub modules: Vec<Module>,
pub macros: Vec<String>,
pub map: HashMap<String, String>,
}
impl ModManager {
pub fn new() -> ModManager {
ModManager {
modules: Vec::new(),
macros: Vec::new(),
map: HashMap::new(),
}
}
pub fn check(&mut self, path: String) -> Option<Module> {
for module in self.modules.clone() {
if module.file_path == path {
return Some(module);
}
}
None
}
pub fn add(&mut self, root: &mut Transpiler, file_path: String, global: bool) -> String {
let mut problems: Vec<ProblemCap> = Vec::new();
let mod_name = format!("mod_{}", self.modules.len());
let home_dirpb = home_dir().unwrap();
let home_dir = home_dirpb.to_str().unwrap();
let mut file_path = file_path;
if global {
let mut tmp = Path::new(home_dir)
.join("wyst")
.join("lib")
.join(file_path.clone())
.to_str()
.unwrap()
.to_string();
if !Path::new(&tmp).exists() {
tmp = Path::new("lib")
.join(file_path)
.to_str()
.unwrap()
.to_string();
}
file_path = tmp;
}
if let Some(modl) = self.check(file_path.clone()) {
return modl.rs_mod;
}
if let Ok(code) = fs::read_to_string(file_path.clone()) {
match file_path.rsplit_once('.').unwrap_or(("", "")).1 {
"rs" => match WystParser::parse(Rule::rust_code, &code) {
Ok(parsed) => {
self.modules.push(Module {
rs_mod: mod_name.clone(),
file_path: file_path.clone(),
code: code.clone(),
});
for pair in parsed {
for p in pair.into_inner() {
if p.as_rule() == Rule::rust_macro_lint {
self.macros.push(p.into_inner().as_str().to_string());
}
}
}
}
Err(_) => {}
},
"h" => {
file_path = file_path.rsplit_once('.').unwrap_or(("", "")).0.to_string();
file_path += ".rs";
let parsed = WystParser::parse(Rule::header_expr, &code).unwrap();
for pair in parsed {
root.transpile_pairs(pair.into_inner());
}
self.map.extend(root.mod_manager.map.clone().into_iter());
if let Ok(code1) = fs::read_to_string(file_path.clone()) {
let parsed = WystParser::parse(Rule::rust_code, &code1).unwrap();
self.modules.push(Module {
rs_mod: mod_name.clone(),
file_path: file_path.clone(),
code: code1.clone(),
});
for pair in parsed {
for p in pair.into_inner() {
if p.as_rule() == Rule::rust_macro_lint {
self.macros.push(p.into_inner().as_str().to_string());
}
}
}
} else {
problems.push(ProblemCap::Error(Problem {
problem_msg: format!("Sub Header not found '{}'", file_path),
problem_type: ProblemType::FileNotFound,
state: State {
line: 0,
column: 0,
file: None,
},
}))
}
}
_ => {}
}
} else {
problems.push(ProblemCap::Error(Problem {
problem_msg: format!("File not found '{}'", file_path),
problem_type: ProblemType::FileNotFound,
state: State {
line: 0,
column: 0,
file: None,
},
}))
}
mod_name
}
pub fn write(&mut self) -> Vec<ProblemCap> {
let mut problems: Vec<ProblemCap> = Vec::new();
for module in self.modules.clone() {
let file_path = module.file_path;
match file_path.rsplit_once('.').unwrap_or(("", "")).1 {
"wst" => {
let mut trsp = Transpiler {
mod_manager: self.clone(),
..Default::default()
};
let rust_code = trsp.transpile_code(module.code, 0).expect("");
fs::write(
Path::new("build").join((module.rs_mod + ".rs").as_str()),
rust_code,
)
.expect("Error writing rust file: ");
problems.append(&mut trsp.problems);
self.modules = trsp.mod_manager.modules;
}
"rs" => fs::write(
Path::new("build").join((module.rs_mod + ".rs").as_str()),
&module.code,
)
.unwrap(),
_ => {}
}
}
problems
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct MatchError {
msg: String,
}
pub fn match_code(code: String, line: usize, column: usize) -> Result<String, MatchError> {
let re_include = Regex::new(r#"\#\s*include\s*(<|\")([a-zA-Z0-9_.-]*)$"#).unwrap();
let re_ident = Regex::new(r#"(\:\:|[_a-zA-Z])(\:\:|[_a-zA-Z0-9])*$"#).unwrap();
let mut lines: Vec<&str> = code.split("\n").collect();
if lines.len() >= line {
let result = &lines[line][..column];
if let Some(caps) = re_include.captures(&result) {
let match_id: u16 = random();
return Ok(format!("<match_file:{}:_{}>", &caps[0], match_id));
} else if let Some(caps) = re_ident.captures(&result) {
let match_id: u16 = random();
let match_line = format!("<match:{}:_{}>", &caps[0], match_id);
lines[line] = match_line.as_str();
let mut trsp = Transpiler::default();
match trsp.transpile_code(lines.join("\n"), 0) {
Ok(rs_code) => {
return Ok(rs_code);
}
Err(_) => {
return Err(MatchError {
msg: "Syntax error".to_string(),
});
}
}
}
}
Err(MatchError {
msg: "last resort empty".to_string(),
})
}
pub const LOGO: &str = r#"
@@ @@@ @
@@@@ @@@@@ @@@@
@@@@ @@@@@@@@@@@@@@@@@@@ @@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@
@@@ @@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@@@@ @@@
@@@@@@@@@@@@@@@ @@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@ @ @@@@@@@@@@@@
@@@@@@@@@@@@@@@ @@@@@@@@@@ @@
@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@
@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@ @ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@
@@@ @@@@@@@@@ @@@ @@@@ @@@@@@@@@ @@@
@@@@@@@@ @@@ @@@ @@@@@@@@
@@@@@@@@@ @@@@ @@@@ @@@@@@@@@
@@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@ @@@@@@@@@@@@@@@@@@@ @@@@
@@@@ @@@@@ @@@@
@@ @@@ @@
"#;
+121
View File
@@ -0,0 +1,121 @@
WHITESPACE = _{ ("//" ~ (!"\n" ~ ANY)*) | ("/*" ~ (!"*/" ~ ANY)*) | " " | "\t" | "\n" }
// [chars]
comma = {","}
semicolon = {";"}
dot = {"."}
// [literals]
filepath = { ("/"|('a'..'z' | 'a'..'z' | '0'..'9' | "_" | "-" | "."))+ }
include = { "#" ~ "include" ~ "\"" ~ filepath ~ "\"" }
include_global = { "#" ~ "include" ~ "<" ~ filepath ~ ">" }
round = { "(" ~ ((expr ~ comma)* ~ expr?) ~ ")" }
curly = { "{" ~ (code_expr)* ~ "}" }
escape = { "\\" ~ ANY }
raw_string = { (!("\\" | "\"") ~ ANY)+ }
string = { "\"" ~ (raw_string | escape )* ~ "\"" }
char = { "'" ~ (escape | ANY) ~ "'" }
bool = @{"true" | "false"}
keyword = @{"struct"|"return"}
map = { "#" ~ "map" ~ identifier ~ comma ~ identifier }
match_name = { "<match:" ~ identifier ~ ":" ~ identifier ~ ">" }
// [numbers]
hex = @{ "0" ~ ("x"|"X") ~ ('0'..'9' | 'a'..'f' | 'A'..'F')*}
float = @{ ('0'..'9')* ~ "." ~ ('0'..'9')+ }
int = @{ '0'..'9'+ }
// [identifiers]
identifier = @{ !(hex|float|int) ~ ("." | "::" | "_" | 'a'..'z' | 'A'..'Z') ~ ( "." | "::" | "_" | 'a'..'z' | 'A'..'Z' | int )*}
def_identifier = {identifier ~ ("<" ~ ((def_identifier ~ comma)* ~ def_identifier?) ~ ">")?}
// [definitions]
round_def = { "(" ~ ((var_def ~ comma)* ~ var_def?) ~ ")" }
curly_def = { "{" ~ (var_def ~ semicolon)* ~ "}" }
var_def = { (def_identifier ~ identifier) | var_def_ptr }
var_def_ptr = { def_identifier ~ "*" ~ identifier }
var_def_set = { var_def ~ "=" ~ expr }
var_set = { def_identifier ~ "=" ~ expr }
func_def = { def_identifier ~ identifier ~ round_def ~ curly }
struct_def = { "struct" ~ identifier ~ curly_def }
ecall = { identifier ~ ( "(" ~ ((def_identifier ~ comma)* ~ def_identifier?) ~ ")" )? }
ecurly = { "{" ~ ((ecall ~ comma)* ~ ecall?) ~ "}" }
enum_def = { "enum" ~ identifier ~ ecurly }
top_code = {"{"~ top_expr ~"}"}
namespace_def = {"namespace" ~ identifier ~ top_code}
impl_def = {"impl" ~ identifier ~ top_code}
// [Ptr]
ptr_fn_def = { def_identifier ~ "*" ~ identifier ~ round_def ~ curly }
ptr_set = { "*" ~ identifier ~ "=" ~ expr }
refrence = { "&" ~ identifier }
// [Operators]
if_operator = {"&&"|"||"}
operator = {"=="|"+"|"-"|"!="|">"|"<"|">="|"<="}
if_expr = {expr ~ (if_operator ~ (("("~if_expr*~")")|expr))*}
operation = {(term ~ operator)+ ~ term}
// [Statement]
return_stm = { "return" ~ expr }
if_stm = { "if" ~ if_expr ~ curly }
else_if_stm = { "else" ~ "if" ~ if_expr ~ curly }
else_stm = { "else" ~ curly }
rust_macro_lint = { "macro_rules" ~ "!" ~ identifier }
rust_code = { (rust_macro_lint | ANY)* }
call = {identifier ~ round}
term = {
call |
round |
char |
hex |
float |
int |
bool |
identifier |
string |
refrence |
match_name
}
expr = {
operation |
(term ~ dot ~ identifier ~ round?) |
term
}
code_expr = {
((
return_stm |
var_def_set|
var_def |
var_set |
ptr_set |
expr
) ~ semicolon) |
if_stm |
else_if_stm |
else_stm
}
top_expr = {
(
func_def |
namespace_def |
include |
include_global |
ptr_fn_def |
struct_def |
enum_def |
map |
impl_def |
match_name
)*
}
header_expr = {
map*
}