lexer
This commit is contained in:
-38
@@ -1,38 +0,0 @@
|
||||
# Generated by Cargo
|
||||
# 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
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
|
||||
# Added by cargo
|
||||
/target
|
||||
|
||||
#MacOS
|
||||
.DS_Store
|
||||
|
||||
#Wyst files for testing
|
||||
*.wst
|
||||
|
||||
|
||||
# Wyst build output taht contains rust files
|
||||
/build
|
||||
|
||||
# Wyst compiled output
|
||||
out
|
||||
|
||||
/log.txt
|
||||
/lsp.log
|
||||
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/wyst.iml" filepath="$PROJECT_DIR$/.idea/wyst.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-11
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Vendored
-7
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"rust-analyzer.linkedProjects": [
|
||||
"./Cargo.toml"
|
||||
],
|
||||
"rust-analyzer.showUnlinkedFileNotification": false,
|
||||
"cSpell.enabled": false
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "wyst"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
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"
|
||||
@@ -5,7 +5,7 @@
|
||||
<h1 align="center">Wyst
|
||||
</h1>
|
||||
|
||||
<h3 align="center">Wyst is a programing language that has similar syntax to C and transpiles to Rust</h3>
|
||||
<h3 align="center">Wyst is a programing language that is inspired by C and transpiles to Go</h3>
|
||||
|
||||
```c
|
||||
#include <stdio.h>
|
||||
@@ -15,6 +15,3 @@ int main() {
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
# Alpha
|
||||
We are on pure alpha. if you would like to contribute please open a new issue.
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Wyst stdlib
|
||||
|
||||
## > [!NOTE]
|
||||
> any changes made here should be documented before pushed to master
|
||||
@@ -1,7 +0,0 @@
|
||||
#[macro_export]
|
||||
|
||||
macro_rules! _0x7072696e7466 {
|
||||
($($arg:tt)*) => {
|
||||
print!($($arg)*)
|
||||
};
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
use std::str;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
use std::{fs, io::Read, process};
|
||||
mod compiler;
|
||||
mod transpiler;
|
||||
mod utils;
|
||||
|
||||
use clap::{App, Arg};
|
||||
use compiler::{compile_rust, transpile_file};
|
||||
use utils::match_code;
|
||||
|
||||
fn main() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
if !matches.is_present("build") {
|
||||
fs::remove_dir_all("build").expect("Error removing build");
|
||||
}
|
||||
process::exit(ecode as i32);
|
||||
}
|
||||
}
|
||||
@@ -1,436 +0,0 @@
|
||||
use crate::utils::{ModManager, ProblemCap};
|
||||
use pest::iterators::{Pair, Pairs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// The Parser
|
||||
use pest::{error::Error, Parser};
|
||||
use pest_derive::Parser;
|
||||
#[derive(Parser)]
|
||||
#[grammar = "wyst.pest"]
|
||||
pub struct WystParser;
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
pub struct State {
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub file: Option<String>,
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl Default for Inject {
|
||||
fn default() -> Self {
|
||||
Inject {
|
||||
inject: false,
|
||||
state: State {
|
||||
line: 0,
|
||||
column: 0,
|
||||
file: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
@@ -1,273 +0,0 @@
|
||||
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#"
|
||||
|
||||
|
||||
@@ @@@ @
|
||||
@@@@ @@@@@ @@@@
|
||||
@@@@ @@@@@@@@@@@@@@@@@@@ @@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@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@@ @@@ @@
|
||||
|
||||
|
||||
"#;
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
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*
|
||||
}
|
||||
Reference in New Issue
Block a user