Compare commits

..
Author SHA1 Message Date
selimaj-dev e416af3403 Updated lock 2026-05-10 19:42:06 +02:00
selimaj-dev 3b0a450895 Removed README from cargo 2026-05-10 19:38:11 +02:00
selimaj-dev 8cd16f4c4f Updated name and details 2026-05-10 19:37:36 +02:00
selimaj-dev 2a833c6cab Updated cargo name 2026-05-10 19:35:04 +02:00
selimaj-dev 950dded614 Removed workflow 2026-05-10 19:32:28 +02:00
selimaj-dev 43b6e95b12 Update for binary 2026-05-10 19:32:03 +02:00
selimaj-dev 73d37b9f35 Merge pull request #26 from mist-go/impl-traits
Impl traits
2026-05-10 18:19:07 +02:00
selimaj-dev d3c1be859d Fix methods with no body 2026-05-10 18:14:01 +02:00
selimaj-dev e97b3cac8f Methods with no body 2026-05-10 18:10:13 +02:00
selimaj-dev 380755bf83 traits 2026-05-10 18:08:15 +02:00
selimaj-dev e063d4c685 Traits 2026-05-10 17:55:08 +02:00
selimaj-dev 28d4d784f2 Class impl 2026-05-10 17:35:33 +02:00
selimaj-dev bb9ad547a3 External impl 2026-05-10 17:25:34 +02:00
selimaj-dev 6f7f11719d Impl for 2026-05-10 17:18:53 +02:00
selimaj-dev 81d0286226 AST and codegen 2026-05-10 17:08:58 +02:00
selimaj-dev 22b1b377f3 Impl grammar 2026-05-10 16:59:21 +02:00
selimaj-dev dfa5487031 Refactored fields 2026-05-10 16:45:07 +02:00
selimaj-dev 2fb38b6974 Class fields 2026-05-10 16:38:13 +02:00
selimaj-dev 476d984d4a Merge pull request #25 from mist-go/lifetimes-and-proper-tests
Lifetimes and proper tests
2026-05-10 04:09:05 +02:00
selimaj-dev d3b6e88b14 Running simple app 2026-05-10 04:03:50 +02:00
selimaj-dev 5916daaada Fixed class lifetimes 2026-05-10 04:01:54 +02:00
selimaj-dev e6c030e8c8 Fixed problems 2026-05-10 03:54:47 +02:00
selimaj-dev 4e18f4530f Fix 2026-05-10 03:44:34 +02:00
selimaj-dev 460d296759 Fixed directories 2026-05-10 03:37:40 +02:00
selimaj-dev 5a475f3b8a Full app 2026-05-10 03:35:13 +02:00
selimaj-dev 0c2746eefc Fixed self param 2026-05-10 03:27:20 +02:00
selimaj-dev f69c53d3fc Removed unsafe warning (will work on later) 2026-05-10 03:19:08 +02:00
selimaj-dev dff77a8c01 Fixed lifetime mutability 2026-05-10 03:13:23 +02:00
selimaj-dev 1b1d38cdba Mist test 2026-05-10 03:11:39 +02:00
selimaj-dev 3e25bf0456 Refrence lifetimes 2026-05-10 00:35:14 +02:00
selimaj-dev 910657c755 Lifetimes 2026-05-08 20:15:56 +02:00
selimaj-dev 020dd3b76b Generic lifetimes 2026-05-08 20:08:03 +02:00
selimaj-dev 0bf32b16cd Merge pull request #24 from mist-go/generics
Generics
2026-05-08 18:20:42 +02:00
selimaj-dev 65f4c5278d Constructor generics 2026-05-08 17:14:39 +02:00
selimaj-dev bbcc639331 More generics 2026-05-08 17:09:01 +02:00
selimaj-dev ed4a505a6a fix generics 2026-05-08 17:00:03 +02:00
selimaj-dev 0e6c73e85c generics codege 2026-05-08 16:54:11 +02:00
selimaj-dev 205e2d9fd3 generics parsing and AST 2026-05-08 16:48:31 +02:00
selimaj-dev 630528a843 Organized grammar 2026-05-08 15:55:09 +02:00
selimaj-dev 39b15d4207 More binary op 2026-05-08 15:43:57 +02:00
selimaj-dev 91bee0c4fc Merge pull request #23 from mist-go/enums-matching
Enums matching
2026-05-07 23:47:28 +02:00
selimaj-dev 8b409f4ccf Improved for loop 2026-05-07 23:43:22 +02:00
selimaj-dev c7ada72029 Match patterns 2026-05-07 23:33:27 +02:00
selimaj-dev bd066e05d1 Fix class 2026-05-07 23:00:20 +02:00
selimaj-dev 093c281ea9 Working match 2026-05-07 22:53:59 +02:00
selimaj-dev 60bc1d2510 Fix match 2026-05-07 22:49:49 +02:00
selimaj-dev 6f6c32b646 match astgen 2026-05-07 22:44:54 +02:00
selimaj-dev 2d56cf1212 match codegen 2026-05-07 22:39:38 +02:00
selimaj-dev aa5640175f match ast 2026-05-07 22:35:19 +02:00
selimaj-dev f98b9d7514 match grammar 2026-05-07 22:32:53 +02:00
selimaj-dev dc49cddc20 Patterns 2026-05-07 22:25:35 +02:00
selimaj-dev a6fb70eebf Pattern AST and grammar 2026-05-07 22:10:26 +02:00
selimaj-dev c51ff01ce8 pattern grammar and ast 2026-05-07 22:01:12 +02:00
selimaj-dev cba78c2ac9 Fix enum codegen 2026-05-07 21:22:31 +02:00
selimaj-dev 81061f26a5 Enum astgen 2026-05-07 21:21:41 +02:00
selimaj-dev 3342893aab Enum codegen 2026-05-07 21:10:27 +02:00
selimaj-dev 580c3297cb Enum ast 2026-05-07 21:02:01 +02:00
selimaj-dev 5eeaf8c35d Enum grammar 2026-05-07 20:59:15 +02:00
selimaj-dev a9fdfe4100 Identifier in ASt 2026-05-07 18:54:07 +02:00
selimaj-dev c6e34bbc70 mod decl 2026-05-07 18:17:35 +02:00
selimaj-dev 27c6eb74c3 mod decl 2026-05-07 18:15:48 +02:00
selimaj-dev 2ccec652da refactored import syntax 2026-05-07 18:08:58 +02:00
21 changed files with 1476 additions and 761 deletions
-56
View File
@@ -1,56 +0,0 @@
name: Release Build
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Release tag to upload to (e.g. 0.1.0)"
required: false
type: string
jobs:
build:
name: Build (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: Build release binary
run: cargo build --release
# --- Get release tag ---
- name: Get release tag
id: get_tag
shell: bash
run: |
TAG="${{ inputs.tag }}"
if [ "${{ github.event_name }}" = "release" ]; then
TAG="${{ github.event.release.tag_name }}"
elif [ -z "$TAG" ]; then
TAG=$(git describe --tags $(git rev-list --tags --max-count=1))
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
- name: Upload to GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.get_tag.outputs.tag }}
files: |
target/release/mist*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+2 -2
View File
@@ -26,5 +26,5 @@ target
/target /target
/test/build /mist-test/build
/test/output.json /mist-test/output.json
Generated
+8 -8
View File
@@ -64,9 +64,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.185" version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]] [[package]]
name = "memchr" name = "memchr"
@@ -75,16 +75,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]] [[package]]
name = "mist" name = "mist-lang"
version = "0.0.1-alpha0" version = "0.0.1-alpha2"
dependencies = [ dependencies = [
"parser", "mist-parser",
"serde", "serde",
"serde_json", "serde_json",
] ]
[[package]] [[package]]
name = "parser" name = "mist-parser"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"pest", "pest",
@@ -221,9 +221,9 @@ dependencies = [
[[package]] [[package]]
name = "typenum" name = "typenum"
version = "1.19.0" version = "1.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
[[package]] [[package]]
name = "ucd-trie" name = "ucd-trie"
+13 -3
View File
@@ -1,9 +1,19 @@
[package] [package]
name = "mist" name = "mist-lang"
version = "0.0.1-alpha0" version = "0.0.1-alpha2"
edition = "2024" edition = "2024"
description = "The Mist programming language compiler"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
readme = "README.md"
keywords = ["compiler", "language", "mist"]
categories = ["compilers"]
[dependencies] [dependencies]
serde = { version = "1.0.228", features = ["serde_derive"] } serde = { version = "1.0.228", features = ["serde_derive"] }
serde_json = "1.0.149" serde_json = "1.0.149"
parser = { path = "./parser" } mist-parser = { path = "./parser", version = "0.1.0"}
[[bin]]
name = "mist"
path = "src/main.rs"
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "mist-test"
version = "0.1.0"
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "mist-test"
version = "0.1.0"
edition = "2024"
[[bin]]
name = "main"
path = "build/main.rs"
[dependencies]
+95
View File
@@ -0,0 +1,95 @@
use <super::task>;
use <super::logger>;
use <super::event>;
public class Application {
String name;
Vec<task::Task> tasks;
Vec<String> plugins;
logger::Logger logger;
bool running;
i32 ticks;
public constructor(str* name) {
self.name = name.to_string();
self.tasks = new Vec();
self.plugins = new Vec();
self.logger = new logger::Logger("app");
self.running = false;
self.ticks = 0;
}
public void boot(self mut*) {
self.logger.info("booting application");
self.running = true;
self.emit(event::Event::Startup);
}
public void run(self mut*) {
while(self.running) {
self.tick();
if(self.ticks >= 5) {
self.shutdown();
}
}
}
void tick(self mut*) {
self.logger.info("tick");
self.ticks = self.ticks + 1;
var task = task::create_task("background-job");
self.tasks.push(task);
println!("tasks: {}", self.tasks.len());
}
public void shutdown(self mut*) {
self.emit(event::Event::Shutdown);
self.logger.warning("shutdown");
self.running = false;
}
public void register_plugin(self mut*, String name) {
self.plugins.push(name.clone());
self.emit(event::Event::PluginLoaded(name));
}
void emit(self*, event::Event event) {
match(event) {
event::Event::Startup => {
self.logger.info("startup event");
}
event::Event::Shutdown => {
self.logger.info("shutdown event");
}
event::Event::PluginLoaded(name) => {
println!("plugin loaded: {}", name);
}
event::Event::TaskExecuted(name) => {
println!("task executed: {}", name);
}
event::Event::Error(message) => {
self.logger.error(&message);
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
public enum Event {
Startup,
Shutdown,
TaskExecuted(String),
PluginLoaded(String),
Error(String),
}
+71
View File
@@ -0,0 +1,71 @@
use <std::fmt>;
public trait TestLogging<T: fmt::Display>: fmt::Display {
String get();
}
public enum LogLevel {
Info,
Warning,
Error,
}
impl fmt::Display for LogLevel {
std::fmt::Result fmt(self*, std::fmt::Formatter<'_> mut* f) {
match (self) {
LogLevel::Info => {
return write!(f, "[INFO]");
}
LogLevel::Warning => {
return write!(f, "[WARN]");
}
LogLevel::Error => {
return write!(f, "[ERROR]");
}
}
}
}
public class Logger {
String prefix;
public constructor(str* prefix) {
self.prefix = prefix.to_string();
}
public void info(self*, str* message) {
self.log(LogLevel::Info, message);
}
public void warning(self*, str* message) {
self.log(LogLevel::Warning, message);
}
public void error(self*, str* message) {
self.log(LogLevel::Error, message);
}
void log(self*, LogLevel level, str* message) {
match(level) {
LogLevel::Info => {
println!("{level} {} {}", self.prefix, message);
}
LogLevel::Warning => {
println!("{level} {} {}", self.prefix, message);
}
LogLevel::Error => {
println!("{level} {} {}", self.prefix, message);
}
}
}
impl fmt::Display {
std::fmt::Result fmt(self*, std::fmt::Formatter<'_> mut* f) {
return write!(f, "logger ({})", self.prefix);
}
}
}
+15
View File
@@ -0,0 +1,15 @@
mod app;
mod task;
mod plugin;
mod logger;
mod event;
void main() {
var mut app_instance = new app::Application("mist-app");
// greeting::register(&mut app_instance);
// statistics::register(&mut app_instance);
app_instance.boot();
app_instance.run();
}
+16
View File
@@ -0,0 +1,16 @@
public struct PluginInfo {
public String name,
public String version,
}
public class PluginRegistry<T> {
T plugins;
public constructor(T plugins) {
self.plugins = plugins;
}
public T plugins(self) {
return self.plugins;
}
}
+20
View File
@@ -0,0 +1,20 @@
public enum TaskState {
Pending,
Running,
Finished,
Failed,
}
public struct Task {
public String name,
public TaskState state,
public i32 executions,
}
public Task create_task(str* name) {
return Task {
name: name.to_string(),
state: TaskState::Pending,
executions: 0,
};
}
+6 -1
View File
@@ -1,7 +1,12 @@
[package] [package]
name = "parser" name = "mist-parser"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
description = "The Mist programming language parser"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
keywords = ["compiler", "language", "mist"]
categories = ["compilers"]
[dependencies] [dependencies]
pest = "2.8.6" pest = "2.8.6"
+95 -16
View File
@@ -1,18 +1,20 @@
use serde::Serialize; use serde::Serialize;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct FieldList(pub Vec<(String, Visibility, TypeExpr)>); pub struct Identifier(pub String);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize, Default)]
pub struct ParamList(pub Vec<VarDecl>); pub struct ParamList(pub Vec<VarDecl>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize, Default)]
pub struct Block(pub Vec<Statement>); pub struct Block(pub Vec<Statement>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub enum TypePostfix { pub enum TypePostfix {
Ref, Ref,
RefMut, RefMut,
RefLifetime(Identifier),
RefMutLifetime(Identifier),
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
@@ -38,13 +40,14 @@ pub enum TypeExprKind {
Path(Path), Path(Path),
PathParams(Path, Vec<TypeExpr>), PathParams(Path, Vec<TypeExpr>),
Tuple(Vec<TypeExpr>), Tuple(Vec<TypeExpr>),
Lifetime(Identifier),
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>); pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct Path(pub Vec<String>); pub struct Path(pub Vec<Identifier>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub enum BinaryOp { pub enum BinaryOp {
@@ -59,6 +62,8 @@ pub enum BinaryOp {
GreaterThan, GreaterThan,
LessThanOrEqual, LessThanOrEqual,
GreaterThanOrEqual, GreaterThanOrEqual,
And,
Or,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
@@ -67,25 +72,75 @@ pub struct TopLevel(pub TopLevelKind, pub Vec<Attribute>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub enum TopLevelKind { pub enum TopLevelKind {
ModAttribute, ModAttribute,
Include(Path), Import(Path),
Mod(Identifier),
ImplDecl(ImplDecl),
TraitDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
requirements: Vec<TypeExpr>,
items: Vec<FunctionDecl>,
},
EnumDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
fields: Vec<EnumItem>,
},
StructDecl { StructDecl {
visibility: Visibility, visibility: Visibility,
name: String, name: Identifier,
fields: FieldList, generics: Generics,
fields: Vec<FieldDecl>,
}, },
FunctionDecl(FunctionDecl), FunctionDecl(FunctionDecl),
ClassDecl { ClassDecl {
visibility: Visibility, visibility: Visibility,
name: String, name: Identifier,
fields: Vec<VarDeclStmt>, generics: Generics,
fields: Vec<FieldDeclStmt>,
constructor: ClassConstructor, constructor: ClassConstructor,
methods: Vec<FunctionDecl>, items: Vec<ClassItem>,
}, },
} }
#[derive(Debug, Clone, Serialize)]
pub enum ClassItem {
Method(FunctionDecl),
ImplDecl(ImplDecl),
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct Generics(pub Vec<Generic>);
#[derive(Debug, Clone, Serialize)]
pub enum Generic {
Lifetime(Identifier),
Type(Identifier, Vec<TypeExpr>),
}
#[derive(Debug, Clone, Serialize)]
pub enum Pattern {
NamedTuple(Path, Vec<Identifier>),
Struct(Path, Vec<Identifier>),
Tuple(Vec<Identifier>),
Literal(Literal),
Path(Path),
Id(Identifier),
}
#[derive(Debug, Clone, Serialize)]
pub enum EnumItem {
Named(Identifier),
Tuple(Identifier, Vec<TypeExpr>),
Struct(Identifier, Vec<FieldDecl>),
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct ClassConstructor { pub struct ClassConstructor {
pub visibility: Visibility, pub visibility: Visibility,
pub generics: Generics,
pub params: ParamList, pub params: ParamList,
pub body: Block, pub body: Block,
} }
@@ -93,18 +148,19 @@ pub struct ClassConstructor {
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct FunctionDecl { pub struct FunctionDecl {
pub visibility: Visibility, pub visibility: Visibility,
pub name: String, pub name: Identifier,
pub generics: Generics,
pub params: ParamList, pub params: ParamList,
pub return_type: TypeExpr, pub return_type: TypeExpr,
pub body: Block, pub body: Option<Block>,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub enum Postfix { pub enum Postfix {
FieldAccess(String), FieldAccess(Identifier),
Call(Vec<Expression>), Call(Vec<Expression>),
MacroCall(String), MacroCall(String),
StructCall(Vec<(String, Expression)>), StructCall(Vec<(Identifier, Expression)>),
Index(Expression), Index(Expression),
Binary(BinaryOp, Expression), Binary(BinaryOp, Expression),
} }
@@ -138,20 +194,30 @@ pub enum Statement {
body: Box<Statement>, body: Box<Statement>,
}, },
For { For {
pattern: String, mutable: bool,
pattern: Pattern,
iterator: Expression, iterator: Expression,
body: Box<Statement>, body: Box<Statement>,
}, },
Match(Expression, Vec<(Pattern, Block)>),
Return(Option<Expression>), Return(Option<Expression>),
Break, Break,
Continue, Continue,
} }
#[derive(Debug, Clone, Serialize)]
pub struct ImplDecl {
pub generics: Generics,
pub target: TypeExpr,
pub trait_: Option<TypeExpr>,
pub methods: Vec<FunctionDecl>,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct VarDecl { pub struct VarDecl {
pub mutable: bool, pub mutable: bool,
pub name: String, pub name: Pattern,
pub type_: Option<TypeExpr>, pub type_: Option<TypeExpr>,
} }
@@ -161,6 +227,19 @@ pub struct VarDeclStmt {
pub init: Option<Expression>, pub init: Option<Expression>,
} }
#[derive(Debug, Clone, Serialize)]
pub struct FieldDecl {
pub visibility: Visibility,
pub type_: TypeExpr,
pub name: Identifier,
}
#[derive(Debug, Clone, Serialize)]
pub struct FieldDeclStmt {
pub decl: FieldDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct VarAssignStmt { pub struct VarAssignStmt {
pub target: Expression, pub target: Expression,
+413 -71
View File
@@ -1,44 +1,130 @@
// ======================================================
// LEXICAL
// ======================================================
WHITESPACE = _{ " " | "\t" | "\r" | "\n" } WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
COMMENT = _{ "//" ~ (!"\n" ~ ANY)* } COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
program = { SOI ~ top_level* ~ EOI } // ------------------------------------------------------
// PRIMITIVES
// ------------------------------------------------------
// primitives identifier = @{ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")* }
identifier = @{ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")* }
integer = @{ ASCII_DIGIT+ } integer = @{ ASCII_DIGIT+ }
float = @{ ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+ }
boolean = { "true" | "false" } float = @{
string_lit = { "\"" ~ inner_str ~ "\"" } ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+
inner_str = @{ (!"\"" ~ ("\\\"" | ANY))* } }
static_path = { identifier ~ ("::" ~ identifier)* }
boolean = {
"true"
| "false"
}
string_lit = {
"\"" ~ inner_str ~ "\""
}
inner_str = @{
(!"\"" ~ ("\\\"" | ANY))*
}
export = { "public" }
mutable = { "mut" }
sharp = _{ "#" }
var = { "var" }
var_decl = { (var | type_expr) ~ mutable? ~ identifier }
semicolon = _{ ";" } semicolon = _{ ";" }
// ================= CLASS ================= static_path = {
class_constructor = { identifier ~ ("::" ~ identifier)*
export? ~ "constructor" ~ "(" ~ param_list? ~ ")" ~ block
} }
class_fields = { var_decl_statement* } // ======================================================
// PROGRAM
// ======================================================
self_param = { "self" ~ mutable? ~ deref_px? } program = {
SOI ~ top_level* ~ EOI
method = {
export? ~ type_expr ~ identifier ~ "(" ~ self_param? ~ param_list? ~ ")" ~ block
} }
class_decl = { // ======================================================
"class" ~ identifier ~ "{" ~ class_fields ~ class_constructor ~ method* ~ "}" // MODIFIERS
// ======================================================
export = { "public" }
mutable = { "mut" }
var = { "var" }
// ======================================================
// GENERICS
// ======================================================
generic = { lifetime | (identifier ~ (":" ~ type_expr_param ~ ("+" ~ type_expr_param)*)?) }
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
// ======================================================
// TYPES
// ======================================================
tuple_type = {
"(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
} }
// ================= TOP LEVEL ================= path_type = {
static_path ~ ("<" ~ (type_expr_param ~ ("," ~ type_expr_param)*)? ~ ">")?
}
top_level = { (attributes ~ (import | function_decl | struct_decl | class_decl)) | mod_attribute } ref_type = {
mutable? ~ lifetime? ~ "*"
}
type_expr = {
(path_type | tuple_type) ~ ref_type*
}
lifetime = {
"'" ~ identifier
}
type_expr_param = {
type_expr
| lifetime
}
// ======================================================
// LITERALS
// ======================================================
literal = {
float
| integer
| boolean
| string_lit
}
// ======================================================
// PATTERNS
// ======================================================
tuple_pattern = {
"(" ~ (identifier ~ ("," ~ identifier)*)? ~ ")"
}
named_tuple_pattern = {
static_path ~ "(" ~ (identifier ~ ("," ~ identifier)*)? ~ ")"
}
struct_pattern = {
static_path ~ "{" ~ (identifier ~ ("," ~ identifier)*)? ~ "}"
}
pattern = _{
named_tuple_pattern
| tuple_pattern
| struct_pattern
| literal
| static_path
}
// ======================================================
// ATTRIBUTES / META
// ======================================================
attribute = { attribute = {
"#" ~ "[" ~ meta ~ "]" "#" ~ "[" ~ meta ~ "]"
@@ -49,39 +135,180 @@ mod_attribute = {
} }
meta = { meta = {
static_path ~ ("=" ~ primary | "(" ~ meta_list? ~ ")")? static_path ~ ("=" ~ literal | "(" ~ meta_list? ~ ")")?
} }
meta_list = { meta_list = {
meta ~ ("," ~ meta)* ~ ","? meta ~ ("," ~ meta)* ~ ","?
} }
attributes = { attribute* } attributes = {
attribute*
}
import = { sharp ~ "include" ~ "<" ~ static_path ~ ">" } // ======================================================
// DECLARATION HELPERS
// ======================================================
var_decl = {
(var | type_expr) ~ mutable? ~ pattern
}
field_list = { field ~ ("," ~ field)* ~ ","? } field = {
field = { export? ~ type_expr ~ identifier } export? ~ type_expr ~ identifier
}
param_list = { var_decl ~ ("," ~ var_decl)* ~ ","? } field_list = {
field ~ ("," ~ field)* ~ ","?
}
param_list = {
var_decl ~ ("," ~ var_decl)* ~ ","?
}
// ======================================================
// IMPORTS / MODULES
// ======================================================
import = {
"use" ~ "<" ~ static_path ~ ">" ~ semicolon
}
mod_package = {
"mod" ~ identifier ~ semicolon
}
// ======================================================
// STRUCTS
// ======================================================
struct_decl = { struct_decl = {
export? ~ "struct" ~ identifier ~ "{" ~ field_list? ~ "}" export? ~ "struct" ~ identifier ~ generics? ~ "{" ~ field_list? ~ "}"
} }
// ======================================================
// ENUMS
// ======================================================
enum_named = {
identifier
}
enum_tuple = {
identifier ~ tuple_type
}
enum_struct = {
identifier ~ "{" ~ field_list ~ "}"
}
enum_field = _{
enum_tuple
| enum_struct
| enum_named
}
enum_fields = _{
enum_field ~ ("," ~ enum_field)* ~ ","?
}
enum_decl = {
export? ~ "enum" ~ identifier ~ generics? ~ "{" ~ enum_fields ~ "}"
}
// ======================================================
// CLASSES
// ======================================================
class_constructor = {
export? ~ "constructor" ~ generics? ~ "(" ~ param_list? ~ ")" ~ block
}
class_fields = {
class_field*
}
class_field = {
field ~ ("=" ~ expr)? ~ semicolon
}
self_param = {
"self" ~ mutable? ~ deref_px?
}
method = {
export? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ block
}
class_item = _{
impl_decl
| method
}
class_decl = {
export? ~ "class" ~ identifier ~ generics? ~ "{" ~ class_fields ~ class_constructor ~ class_item* ~ "}"
}
// ======================================================
// IMPL
// ======================================================
impl_for_decl = {
"impl" ~ generics? ~ type_expr ~ "for" ~ type_expr ~ "{" ~ method* ~ "}"
}
impl_decl = {
"impl" ~ generics? ~ type_expr ~ "{" ~ method* ~ "}"
}
// ======================================================
// Traits
// ======================================================
trait_requirements = { ":" ~ type_expr_param ~ ("+" ~ type_expr_param)* }
method_no_body = {
export? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ semicolon
}
trait_item = _{
method
| method_no_body
}
trait_decl = {
export? ~ "trait" ~ identifier ~ generics? ~ trait_requirements? ~ "{" ~ trait_item* ~ "}"
}
// ======================================================
// FUNCTIONS
// ======================================================
function_decl = { function_decl = {
export? ~ type_expr ~ identifier ~ "(" ~ param_list? ~ ")" ~ block export? ~ type_expr ~ identifier ~ "(" ~ param_list? ~ ")" ~ block
} }
// ================= STATEMENTS ================= // ======================================================
// TOP LEVEL
// ======================================================
block = { "{" ~ statement_list ~ "}" } top_level = {
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | mod_package | function_decl))
| mod_attribute
}
statement_list = { statement* } // ======================================================
// STATEMENTS
// ======================================================
block = {
"{" ~ statement_list ~ "}"
}
statement_list = {
statement*
}
statement = _{ statement = _{
expr_stmt expr_stmt
| var_decl_statement | match_stmt
| assign_statement | assign_statement
| if_stmt | if_stmt
| while_stmt | while_stmt
@@ -91,30 +318,57 @@ statement = _{
| break_stmt | break_stmt
| continue_stmt | continue_stmt
| block | block
| var_decl_statement
} }
// --- basic statements --- // ------------------------------------------------------
// BASIC STATEMENTS
// ------------------------------------------------------
expr_stmt = { expr ~ semicolon } expr_stmt = {
expr ~ semicolon
}
return_stmt = { "return" ~ expr? ~ semicolon } return_stmt = {
"return" ~ expr? ~ semicolon
}
break_stmt = { "break" ~ semicolon } break_stmt = {
"break" ~ semicolon
}
continue_stmt = { "continue" ~ semicolon } continue_stmt = {
"continue" ~ semicolon
}
var_decl_statement = { var_decl ~ ("=" ~ expr)? ~ semicolon } var_decl_statement = {
var_decl ~ ("=" ~ expr)? ~ semicolon
}
assign_statement = { expr ~ "=" ~ expr ~ semicolon } assign_statement = {
expr ~ "=" ~ expr ~ semicolon
}
else_if = { "else" ~ "if" ~ "(" ~ expr ~ ")" ~ statement } // ------------------------------------------------------
// CONDITIONALS
// ------------------------------------------------------
else_if_list = { else_if* } else_if = {
"else" ~ "if" ~ "(" ~ expr ~ ")" ~ statement
}
else_if_list = {
else_if*
}
if_stmt = { if_stmt = {
"if" ~ "(" ~ expr ~ ")" ~ statement ~ else_if_list ~ ("else" ~ statement)? "if" ~ "(" ~ expr ~ ")" ~ statement ~ else_if_list ~ ("else" ~ statement)?
} }
// ------------------------------------------------------
// LOOPS
// ------------------------------------------------------
while_stmt = { while_stmt = {
"while" ~ "(" ~ expr ~ ")" ~ statement "while" ~ "(" ~ expr ~ ")" ~ statement
} }
@@ -124,31 +378,84 @@ c_for_stmt = {
} }
for_stmt = { for_stmt = {
"for" ~ "(" ~ identifier ~ "in" ~ expr ~ ")" ~ statement "for" ~ "(" ~ mutable? ~ pattern ~ "in" ~ expr ~ ")" ~ statement
} }
// ================= EXPRESSIONS ================= // ------------------------------------------------------
tuple_type = { "(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")" } // MATCH
path_type = { static_path ~ ("<" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ">")? } // ------------------------------------------------------
ref_type = { mutable? ~ "*" }
type_expr = { (path_type | tuple_type) ~ ref_type* } match_item = {
pattern ~ "=>" ~ block
}
match_stmt = {
"match" ~ "(" ~ expr ~ ")" ~ "{" ~ match_item* ~ "}"
}
// ======================================================
// EXPRESSIONS
// ======================================================
// ------------------------------------------------------
// TUPLES
// ------------------------------------------------------
tuple = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
}
// ------------------------------------------------------
// MACROS
// ------------------------------------------------------
macro_inner_v = { macro_inner_v = {
"(" ~ macro_inner_v* ~ ")" "(" ~ macro_inner_v* ~ ")"
| (!("(" | ")") ~ ANY) | (!("(" | ")") ~ ANY)
} }
tuple = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" } // ------------------------------------------------------
// PRIMARY EXPRESSIONS
// ------------------------------------------------------
primary = { primary = {
float literal
| integer
| boolean
| string_lit
| static_path | static_path
| tuple | tuple
} }
// ------------------------------------------------------
// POSTFIX EXPRESSIONS
// ------------------------------------------------------
field_px = {
"." ~ identifier
}
call_px = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
}
macro_call_px = {
"!" ~ "(" ~ macro_inner_v* ~ ")"
}
struct_field_decl = {
identifier ~ ":" ~ expr
}
struct_px = {
"{" ~ (struct_field_decl ~ ("," ~ struct_field_decl)*)? ~ ","? ~ "}"
}
index_px = {
"[" ~ expr ~ "]"
}
binary_px = {
bin_op ~ expr
}
postfix = { postfix = {
field_px field_px
| call_px | call_px
@@ -158,14 +465,29 @@ postfix = {
| binary_px | binary_px
} }
field_px = { "." ~ identifier } // ------------------------------------------------------
call_px = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" } // PREFIX EXPRESSIONS
macro_call_px = { "!" ~ "(" ~ macro_inner_v* ~ ")" } // ------------------------------------------------------
struct_px = { "{" ~ (struct_field_decl ~ ("," ~ struct_field_decl)*)? ~ ","? ~ "}" }
index_px = { "[" ~ expr ~ "]" } deref_px = {
binary_px = { bin_op ~ expr } "*"
bin_op = { "<=" | ">=" | "==" | "!=" | "+" | "-" | "*" | "/" | "%" | "<" | ">" } }
struct_field_decl = { identifier ~ ":" ~ expr }
mut_ref_px = {
"&" ~ mutable
}
ref_px = {
"&"
}
new_px = {
"new"
}
not_px = {
"!"
}
prefix = { prefix = {
deref_px deref_px
@@ -175,13 +497,33 @@ prefix = {
| not_px | not_px
} }
deref_px = { "*" } prefix_list = {
mut_ref_px = { "&" ~ mutable } prefix*
ref_px = { "&" } }
new_px = { "new" }
not_px = { "!" }
prefix_list = { prefix* } // ------------------------------------------------------
// OPERATORS
// ------------------------------------------------------
bin_op = {
"<="
| ">="
| "=="
| "!="
| "&&"
| "||"
| "+"
| "-"
| "*"
| "/"
| "%"
| "<"
| ">"
}
// ------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------
expr = { expr = {
prefix_list ~ primary ~ postfix* prefix_list ~ primary ~ postfix*
+276 -55
View File
@@ -36,6 +36,11 @@ impl From<pest::iterators::Pair<'_, Rule>> for TypeExpr {
TypeExprKind::from(inner.next().unwrap()), TypeExprKind::from(inner.next().unwrap()),
inner.map(TypePostfix::from).collect(), inner.map(TypePostfix::from).collect(),
), ),
Rule::type_expr_param => TypeExpr::from(inner.next().unwrap()),
Rule::lifetime => TypeExpr(
TypeExprKind::Lifetime(Identifier::from(inner.next().unwrap())),
Vec::new(),
),
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
} }
} }
@@ -44,14 +49,26 @@ impl From<pest::iterators::Pair<'_, Rule>> for TypeExpr {
impl From<pest::iterators::Pair<'_, Rule>> for TypePostfix { impl From<pest::iterators::Pair<'_, Rule>> for TypePostfix {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self { fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule(); let rule = pair.as_rule();
let inner = pair.into_inner(); let mut inner = pair.into_inner();
match rule { match rule {
Rule::ref_type => { Rule::ref_type => {
if inner.peek().is_some() { let mutable = listen_rule(&mut inner, Rule::mutable);
TypePostfix::RefMut let lifetime = consume_rule(&mut inner, Rule::lifetime)
.map(|pair| Identifier::from(pair.into_inner().next().unwrap()));
if mutable {
if let Some(lifetime) = lifetime {
TypePostfix::RefMutLifetime(lifetime)
} else {
TypePostfix::RefMut
}
} else { } else {
TypePostfix::Ref if let Some(lifetime) = lifetime {
TypePostfix::RefLifetime(lifetime)
} else {
TypePostfix::Ref
}
} }
} }
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
@@ -84,29 +101,12 @@ impl From<pest::iterators::Pair<'_, Rule>> for TypeExprKind {
impl From<pest::iterators::Pair<'_, Rule>> for Path { impl From<pest::iterators::Pair<'_, Rule>> for Path {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self { fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() { match pair.as_rule() {
Rule::static_path => Path(pair.into_inner().map(|i| i.as_str().to_string()).collect()), Rule::static_path => Path(pair.into_inner().map(Identifier::from).collect()),
_ => unimplemented!("{pair:#?}"), _ => unimplemented!("{pair:#?}"),
} }
} }
} }
impl From<pest::iterators::Pair<'_, Rule>> for FieldList {
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
let params = pair
.into_inner()
.map(|p| {
let mut param_inner = p.into_inner();
let visibility = Visibility::from(&mut param_inner);
let param_type = TypeExpr::from(param_inner.next().unwrap());
let param_name = param_inner.next().unwrap().as_str().to_string();
(param_name, visibility, param_type)
})
.collect();
FieldList(params)
}
}
impl From<pest::iterators::Pair<'_, Rule>> for ParamList { impl From<pest::iterators::Pair<'_, Rule>> for ParamList {
fn from(pair: pest::iterators::Pair<Rule>) -> Self { fn from(pair: pest::iterators::Pair<Rule>) -> Self {
ParamList(pair.into_inner().map(VarDecl::from).collect()) ParamList(pair.into_inner().map(VarDecl::from).collect())
@@ -211,54 +211,186 @@ impl From<pest::iterators::Pair<'_, Rule>> for ClassConstructor {
let visibility = Visibility::from(&mut inner); let visibility = Visibility::from(&mut inner);
let generics = consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default();
let params = consume_rule(&mut inner, Rule::param_list) let params = consume_rule(&mut inner, Rule::param_list)
.map(ParamList::from) .map(ParamList::from)
.unwrap_or_else(|| ParamList(Vec::new())); .unwrap_or_else(|| ParamList(Vec::new()));
Self { Self {
visibility, visibility,
generics,
params, params,
body: Block::from(inner.next().unwrap()), body: Block::from(inner.next().unwrap()),
} }
} }
} }
impl From<pest::iterators::Pair<'_, Rule>> for Generics {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
let inner = pair.clone().into_inner();
match rule {
Rule::generics => Generics(
inner
.map(|pair| {
let mut inner = pair.into_inner();
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
Generic::Lifetime(Identifier::from(pair.into_inner().next().unwrap()))
} else {
Generic::Type(
Identifier::from(inner.next().unwrap()),
inner.map(TypeExpr::from).collect(),
)
}
})
.collect(),
),
_ => unimplemented!("{rule:#?}"),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for TopLevelKind { impl From<pest::iterators::Pair<'_, Rule>> for TopLevelKind {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self { fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
match rule { match rule {
Rule::import => TopLevelKind::Include(Path::from(inner.next().unwrap())), Rule::import => TopLevelKind::Import(Path::from(inner.next().unwrap())),
Rule::function_decl => TopLevelKind::FunctionDecl(FunctionDecl::from(pair)), Rule::function_decl => TopLevelKind::FunctionDecl(FunctionDecl::from(pair)),
Rule::struct_decl => { Rule::struct_decl => TopLevelKind::StructDecl {
let visibility = Visibility::from(&mut inner); visibility: Visibility::from(&mut inner),
let name = inner.next().unwrap().as_str().to_string(); name: Identifier::from(inner.next().unwrap()),
let fields_pair = inner.next().unwrap(); generics: consume_rule(&mut inner, Rule::generics)
let fields = FieldList::from(fields_pair); .map(Generics::from)
.unwrap_or_default(),
TopLevelKind::StructDecl { fields: inner
visibility, .next()
name, .map(|pair| pair.into_inner().map(FieldDecl::from).collect())
fields, .unwrap_or_default(),
} },
}
Rule::class_decl => TopLevelKind::ClassDecl { Rule::class_decl => TopLevelKind::ClassDecl {
visibility: Visibility::from(&mut inner), visibility: Visibility::from(&mut inner),
name: inner.next().unwrap().as_str().to_string(), name: Identifier::from(inner.next().unwrap()),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default(),
fields: inner fields: inner
.next() .next()
.unwrap() .unwrap()
.into_inner() .into_inner()
.map(VarDeclStmt::from) .map(FieldDeclStmt::from)
.collect(), .collect(),
constructor: ClassConstructor::from(inner.next().unwrap()), constructor: ClassConstructor::from(inner.next().unwrap()),
methods: inner.into_iter().map(FunctionDecl::from).collect(), items: inner.into_iter().map(ClassItem::from).collect(),
}, },
Rule::enum_decl => TopLevelKind::EnumDecl {
visibility: Visibility::from(&mut inner),
name: Identifier::from(inner.next().unwrap()),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default(),
fields: inner.map(EnumItem::from).collect(),
},
Rule::mod_package => TopLevelKind::Mod(Identifier::from(inner.next().unwrap())),
Rule::impl_for_decl | Rule::impl_decl => TopLevelKind::ImplDecl(ImplDecl::from(pair)),
Rule::trait_decl => TopLevelKind::TraitDecl {
visibility: Visibility::from(&mut inner),
name: Identifier::from(inner.next().unwrap()),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default(),
requirements: consume_rule(&mut inner, Rule::trait_requirements)
.map(|pair| pair.into_inner().map(TypeExpr::from).collect())
.unwrap_or_default(),
items: inner.map(FunctionDecl::from).collect(),
},
_ => unimplemented!("{rule:#?}"),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for ClassItem {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
match rule {
Rule::impl_decl | Rule::impl_for_decl => ClassItem::ImplDecl(ImplDecl::from(pair)),
Rule::method => ClassItem::Method(FunctionDecl::from(pair)),
_ => unimplemented!("{rule:#?}"),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for ImplDecl {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::impl_for_decl => ImplDecl {
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default(),
trait_: Some(TypeExpr::from(inner.next().unwrap())),
target: TypeExpr::from(inner.next().unwrap()),
methods: inner.map(FunctionDecl::from).collect(),
},
Rule::impl_decl => ImplDecl {
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default(),
trait_: None,
target: TypeExpr::from(inner.next().unwrap()),
methods: inner.map(FunctionDecl::from).collect(),
},
_ => unimplemented!("{rule:#?}"),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for EnumItem {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::enum_named => EnumItem::Named(Identifier::from(inner.next().unwrap())),
Rule::enum_tuple => EnumItem::Tuple(
Identifier::from(inner.next().unwrap()),
inner
.next()
.unwrap()
.into_inner()
.map(TypeExpr::from)
.collect(),
),
Rule::enum_struct => EnumItem::Struct(
Identifier::from(inner.next().unwrap()),
inner
.next()
.map(|pair| pair.into_inner().map(FieldDecl::from).collect())
.unwrap_or_default(),
),
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
} }
} }
@@ -329,7 +461,8 @@ impl From<pest::iterators::Pair<'_, Rule>> for Statement {
}, },
Rule::for_stmt => Statement::For { Rule::for_stmt => Statement::For {
pattern: inner.next().unwrap().as_str().to_string(), mutable: listen_rule(&mut inner, Rule::mutable),
pattern: Pattern::from(inner.next().unwrap()),
iterator: inner.next().unwrap().into(), iterator: inner.next().unwrap().into(),
body: Box::new(Statement::from(inner.next().unwrap())), body: Box::new(Statement::from(inner.next().unwrap())),
}, },
@@ -339,6 +472,19 @@ impl From<pest::iterators::Pair<'_, Rule>> for Statement {
value: Expression::from(inner.next().unwrap()), value: Expression::from(inner.next().unwrap()),
}), }),
Rule::match_stmt => Statement::Match(
Expression::from(inner.next().unwrap()),
inner
.map(|match_itms| {
let mut match_inner = match_itms.into_inner();
(
Pattern::from(match_inner.next().unwrap()),
Block::from(match_inner.next().unwrap()),
)
})
.collect(),
),
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
} }
} }
@@ -351,6 +497,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for Literal {
match rule { match rule {
Rule::primary => Self::from(inner.next().unwrap()), Rule::primary => Self::from(inner.next().unwrap()),
Rule::literal => Self::from(inner.next().unwrap()),
Rule::integer => Literal::Int(pair.as_str().parse::<i64>().unwrap()), Rule::integer => Literal::Int(pair.as_str().parse::<i64>().unwrap()),
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()), Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()), Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
@@ -387,9 +534,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for Expression {
} }
Rule::primary => Expression::from(inner.next().unwrap()), Rule::primary => Expression::from(inner.next().unwrap()),
Rule::static_path => Expression::Path(Path::from(pair)), Rule::static_path => Expression::Path(Path::from(pair)),
Rule::integer | Rule::float | Rule::boolean | Rule::string_lit | Rule::tuple => { Rule::literal => Expression::Literal(Literal::from(pair)),
Expression::Literal(Literal::from(pair))
}
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
} }
} }
@@ -417,10 +562,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for Postfix {
match rule { match rule {
Rule::postfix => Postfix::from(inner.next().unwrap()), Rule::postfix => Postfix::from(inner.next().unwrap()),
Rule::field_px => { Rule::field_px => Postfix::FieldAccess(Identifier::from(inner.next().unwrap())),
let field_name = inner.next().unwrap().as_str().to_string();
Postfix::FieldAccess(field_name)
}
Rule::call_px => Postfix::Call(inner.map(Expression::from).collect()), Rule::call_px => Postfix::Call(inner.map(Expression::from).collect()),
@@ -429,7 +571,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for Postfix {
.map(|p| { .map(|p| {
let mut pi = p.into_inner(); let mut pi = p.into_inner();
( (
pi.next().unwrap().as_str().to_string(), Identifier::from(pi.next().unwrap()),
Expression::from(pi.next().unwrap()), Expression::from(pi.next().unwrap()),
) )
}) })
@@ -452,6 +594,8 @@ impl From<pest::iterators::Pair<'_, Rule>> for Postfix {
">" => BinaryOp::GreaterThan, ">" => BinaryOp::GreaterThan,
"<=" => BinaryOp::LessThanOrEqual, "<=" => BinaryOp::LessThanOrEqual,
">=" => BinaryOp::GreaterThanOrEqual, ">=" => BinaryOp::GreaterThanOrEqual,
"&&" => BinaryOp::And,
"||" => BinaryOp::Or,
_ => { _ => {
unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str()) unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str())
@@ -485,6 +629,53 @@ impl From<pest::iterators::Pair<'_, Rule>> for VarDeclStmt {
} }
} }
impl From<pest::iterators::Pair<'_, Rule>> for FieldDeclStmt {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() {
Rule::class_field => {
let mut inner = pair.into_inner();
let decl = FieldDecl::from(inner.next().unwrap());
let init = inner.next().map(Expression::from);
FieldDeclStmt { decl, init }
}
_ => unimplemented!(),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for Pattern {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::tuple_pattern => Pattern::Tuple(inner.map(Identifier::from).collect()),
Rule::named_tuple_pattern => Pattern::NamedTuple(
Path::from(inner.next().unwrap()),
inner.map(Identifier::from).collect(),
),
Rule::struct_pattern => Pattern::Struct(
Path::from(inner.next().unwrap()),
inner.map(Identifier::from).collect(),
),
Rule::literal => Pattern::Literal(Literal::from(pair)),
Rule::identifier => Pattern::Id(Identifier::from(pair)),
Rule::static_path => Pattern::Path(Path::from(pair)),
_ => unimplemented!("{rule:?}"),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for VarDecl { impl From<pest::iterators::Pair<'_, Rule>> for VarDecl {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self { fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() { match pair.as_rule() {
@@ -500,7 +691,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for VarDecl {
}); });
let mutable = listen_rule(&mut inner, Rule::mutable); let mutable = listen_rule(&mut inner, Rule::mutable);
let name = inner.next().unwrap().as_str().to_string(); let name = Pattern::from(inner.next().unwrap());
VarDecl { VarDecl {
mutable, mutable,
@@ -514,18 +705,41 @@ impl From<pest::iterators::Pair<'_, Rule>> for VarDecl {
} }
} }
impl From<pest::iterators::Pair<'_, Rule>> for FieldDecl {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() {
Rule::field => {
let mut inner = pair.into_inner();
let visibility = Visibility::from(&mut inner);
let type_ = TypeExpr::from(inner.next().unwrap());
let name = Identifier::from(inner.next().unwrap());
FieldDecl {
visibility,
type_,
name,
}
}
_ => unimplemented!("{:?}", pair.as_rule()),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for FunctionDecl { impl From<pest::iterators::Pair<'_, Rule>> for FunctionDecl {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self { fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let visibility = Visibility::from(&mut inner); let visibility = Visibility::from(&mut inner);
let return_type = TypeExpr::from(inner.next().unwrap()); let return_type = TypeExpr::from(inner.next().unwrap());
let name = Identifier::from(inner.next().unwrap());
let generics = consume_rule(&mut inner, Rule::generics)
.map(Generics::from)
.unwrap_or_default();
let name = inner.next().unwrap().as_str().to_string();
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| { let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
let mut param_inner = param.into_inner(); let mut param_inner = param.into_inner();
let name = format!("self"); let name = Pattern::Id(Identifier(String::from("self")));
let mutable = listen_rule(&mut param_inner, Rule::mutable); let mutable = listen_rule(&mut param_inner, Rule::mutable);
@@ -533,9 +747,9 @@ impl From<pest::iterators::Pair<'_, Rule>> for FunctionDecl {
VarDecl { VarDecl {
mutable: mutable && !is_ref, mutable: mutable && !is_ref,
name, name: name.clone(),
type_: Some(TypeExpr( type_: Some(TypeExpr(
TypeExprKind::Path(Path(vec![format!("Self")])), TypeExprKind::Path(Path(vec![Identifier("Self".to_string())])),
if is_ref { if is_ref {
vec![if mutable { vec![if mutable {
TypePostfix::RefMut TypePostfix::RefMut
@@ -562,11 +776,12 @@ impl From<pest::iterators::Pair<'_, Rule>> for FunctionDecl {
}) })
.unwrap_or_else(|| ParamList(self_param.into_iter().collect())); .unwrap_or_else(|| ParamList(self_param.into_iter().collect()));
let body = Block::from(inner.next().unwrap()); let body = inner.next().map(Block::from);
Self { Self {
visibility, visibility,
name, name,
generics,
params, params,
return_type, return_type,
body, body,
@@ -608,3 +823,9 @@ pub fn consume_rule<'a>(
if consumed { pairs.next() } else { None } if consumed { pairs.next() } else { None }
} }
impl From<pest::iterators::Pair<'_, Rule>> for Identifier {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
Identifier(pair.as_str().to_string())
}
}
+319 -33
View File
@@ -1,7 +1,8 @@
use parser::ast::{ use mist_parser::ast::{
Attribute, BinaryOp, Block, Expression, FunctionDecl, Literal, Path, Postfix, Prefix, Attribute, BinaryOp, Block, ClassItem, EnumItem, Expression, FieldDecl, FunctionDecl, Generic,
Statement, StatementBranch, TopLevel, TopLevelKind, TypeExpr, TypeExprKind, TypePostfix, Generics, Identifier, ImplDecl, Literal, Path, Pattern, Postfix, Prefix, Statement,
VarAssignStmt, VarDecl, VarDeclStmt, Visibility, StatementBranch, TopLevel, TopLevelKind, TypeExpr, TypeExprKind, TypePostfix, VarAssignStmt,
VarDecl, VarDeclStmt, Visibility,
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -96,6 +97,7 @@ impl GetRust for TypeExprKind {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
match self { match self {
TypeExprKind::Path(path) => get_static_type_path(path), TypeExprKind::Path(path) => get_static_type_path(path),
TypeExprKind::Lifetime(name) => format!("'{}", name.get_rust()),
TypeExprKind::PathParams(path, params) => { TypeExprKind::PathParams(path, params) => {
format!( format!(
"{}<{}>", "{}<{}>",
@@ -197,7 +199,7 @@ impl GetRust for Option<&Vec<Prefix>> {
impl GetRust for Postfix { impl GetRust for Postfix {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
match self { match self {
Postfix::FieldAccess(field) => format!(".{}", field), Postfix::FieldAccess(field) => format!(".{}", field.get_rust()),
Postfix::Call(args) => { Postfix::Call(args) => {
let args = args let args = args
@@ -215,7 +217,7 @@ impl GetRust for Postfix {
Postfix::StructCall(fields) => { Postfix::StructCall(fields) => {
let fields = fields let fields = fields
.iter() .iter()
.map(|(k, v)| format!("{}: {}", k, v.get_rust())) .map(|(k, v)| format!("{}: {}", k.get_rust(), v.get_rust()))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
format!("{{ {} }}", fields) format!("{{ {} }}", fields)
@@ -238,6 +240,8 @@ impl GetRust for Postfix {
BinaryOp::GreaterThan => ">", BinaryOp::GreaterThan => ">",
BinaryOp::LessThanOrEqual => "<=", BinaryOp::LessThanOrEqual => "<=",
BinaryOp::GreaterThanOrEqual => ">=", BinaryOp::GreaterThanOrEqual => ">=",
BinaryOp::And => "&&",
BinaryOp::Or => "||",
}; };
format!(" {} {}", op_str, rhs.get_rust()) format!(" {} {}", op_str, rhs.get_rust())
} }
@@ -308,21 +312,79 @@ impl ToRust for TopLevelKind {
fn to_rust(&self, cg: &mut RustCodegen) { fn to_rust(&self, cg: &mut RustCodegen) {
match self { match self {
Self::ModAttribute => {} Self::ModAttribute => {}
Self::Include(path) => { Self::Import(path) => cg.addln(&format!("use {};", path.get_rust())),
cg.addln(&format!("use {};", path.get_rust())); Self::Mod(id) => cg.addln(&format!("mod {};", id.get_rust())),
}
Self::FunctionDecl(decl) => decl.to_rust(cg), Self::FunctionDecl(decl) => decl.to_rust(cg),
Self::ImplDecl(impl_) => impl_.to_rust(cg),
Self::StructDecl { Self::StructDecl {
visibility, visibility,
name, name,
generics,
fields, fields,
} => { } => {
cg.addln(&format!("{}struct {} {{", visibility.get_rust(), name)); cg.addln(&format!(
"{}struct {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1; cg.indent += 1;
for (field_name, _, ty) in &fields.0 { for field in fields {
let ty = ty.get_rust(); cg.add_indentedln(&field.get_rust());
cg.add_indentedln(&format!("pub {}: {},", field_name, ty)); }
cg.indent -= 1;
cg.addln("}\n");
}
Self::EnumDecl {
visibility,
name,
generics,
fields,
} => {
cg.addln(&format!(
"{}enum {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indentedln(&(format!("{}", field.get_rust()) + ","));
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::TraitDecl {
visibility,
name,
generics,
requirements,
items,
} => {
cg.addln(&format!(
"{}trait {}{}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust(),
if requirements.len() != 0 {
String::from(": ")
+ &requirements
.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join("+")
} else {
String::new()
},
));
cg.indent += 1;
for item in items {
item.to_rust(cg);
} }
cg.indent -= 1; cg.indent -= 1;
@@ -331,24 +393,42 @@ impl ToRust for TopLevelKind {
Self::ClassDecl { Self::ClassDecl {
visibility, visibility,
name, name,
generics,
fields, fields,
constructor, constructor,
methods, items,
} => { } => {
// Struct decl // Struct decl
cg.addln(&format!("{}struct {} {{", visibility.get_rust(), name)); cg.addln(&format!(
"{}struct {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1; cg.indent += 1;
for field in fields { for field in fields {
let ty = field.decl.type_.clone().unwrap().get_rust(); cg.add_indentedln(&field.decl.get_rust());
cg.add_indentedln(&format!("pub {}: {},", field.decl.name, ty));
} }
cg.indent -= 1; cg.indent -= 1;
cg.addln("}\n"); cg.addln("}\n");
// Constructor // Constructor
cg.addln(&format!("impl {} {{", name)); cg.addln(&format!(
"impl{} {}{} {{",
generics.get_rust(),
name.get_rust(),
format!(
"<{}>",
generics
.0
.iter()
.map(|v| (false, v).get_rust())
.collect::<Vec<_>>()
.join(", ")
)
));
cg.indent += 1; cg.indent += 1;
let params_str = constructor let params_str = constructor
@@ -359,9 +439,11 @@ impl ToRust for TopLevelKind {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
cg.add_indentedln("#[allow(invalid_value)]");
cg.add_indentedln(&format!( cg.add_indentedln(&format!(
"{}fn new({}) -> Self {{", "{}fn new{}({}) -> Self {{",
constructor.visibility.get_rust(), constructor.visibility.get_rust(),
constructor.generics.get_rust(),
params_str params_str
)); ));
cg.indent += 1; cg.indent += 1;
@@ -372,7 +454,7 @@ impl ToRust for TopLevelKind {
if let Some(init) = &field.init { if let Some(init) = &field.init {
cg.add_indentedln(&format!( cg.add_indentedln(&format!(
"this.{} = {};", "this.{} = {};",
field.decl.name, field.decl.name.get_rust(),
init.get_rust() init.get_rust()
)); ));
} }
@@ -384,7 +466,7 @@ impl ToRust for TopLevelKind {
.params .params
.0 .0
.iter() .iter()
.map(|e| e.name.to_string()) .map(|e| e.name.get_rust())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
)); ));
@@ -396,8 +478,9 @@ impl ToRust for TopLevelKind {
// Constructor function // Constructor function
cg.add_indentedln(&format!( cg.add_indentedln(&format!(
"{}fn construct_class(&mut self, {}) {{", "{}fn construct_class{}(&mut self, {}) {{",
constructor.visibility.get_rust(), constructor.visibility.get_rust(),
constructor.generics.get_rust(),
params_str params_str
)); ));
cg.indent += 1; cg.indent += 1;
@@ -407,12 +490,30 @@ impl ToRust for TopLevelKind {
cg.indent -= 1; cg.indent -= 1;
cg.add_indentedln("}\n"); cg.add_indentedln("}\n");
for method in methods { for item in items {
method.to_rust(cg); match item {
ClassItem::ImplDecl(_) => {}
ClassItem::Method(method) => method.to_rust(cg),
}
} }
cg.indent -= 1; cg.indent -= 1;
cg.addln("}\n"); cg.addln("}\n");
for item in items {
match item {
ClassItem::ImplDecl(impl_) => {
let mut impl_ = impl_.clone();
impl_.trait_ = Some(impl_.target);
impl_.target =
TypeExpr(TypeExprKind::Path(Path(vec![name.clone()])), Vec::new());
impl_.to_rust(cg);
}
ClassItem::Method(_) => {}
}
}
} }
} }
} }
@@ -446,6 +547,23 @@ impl ToRust for Statement {
cg.add_indentedln(&format!("{} = {};", target.get_rust(), value.get_rust(),)); cg.add_indentedln(&format!("{} = {};", target.get_rust(), value.get_rust(),));
} }
Statement::Match(expr, match_items) => {
cg.add_indentedln(&format!("match {} {{", expr.get_rust()));
cg.indent += 1;
for itm in match_items {
cg.add_indentedln(&format!("{} =>", itm.0.get_rust()));
cg.add_indentedln("{");
cg.indent += 1;
itm.1.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}");
}
cg.indent -= 1;
cg.add_indentedln("}");
}
Statement::If { Statement::If {
initial, initial,
else_if, else_if,
@@ -498,11 +616,17 @@ impl ToRust for Statement {
} }
Statement::For { Statement::For {
mutable,
pattern, pattern,
iterator, iterator,
body, body,
} => { } => {
cg.add_indentedln(&format!("for {} in {}", pattern, iterator.get_rust())); cg.add_indentedln(&format!(
"for {}{} in {}",
get_mutable(*mutable),
pattern.get_rust(),
iterator.get_rust()
));
cg.ensure_brackets(body); cg.ensure_brackets(body);
} }
@@ -528,36 +652,76 @@ impl ToRust for FunctionDecl {
.join(", "); .join(", ");
cg.add_indentedln(&format!( cg.add_indentedln(&format!(
"{}fn {}({}) -> {} {{", "{}fn {}{}({}) -> {}",
self.visibility.get_rust(), self.visibility.get_rust(),
self.name, self.name.get_rust(),
self.generics.get_rust(),
params_str, params_str,
self.return_type.get_rust() self.return_type.get_rust()
)); ));
if let Some(body) = &self.body {
cg.add_indentedln("{\n");
cg.indent += 1;
body.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}\n");
} else {
cg.add(";");
}
}
}
impl ToRust for ImplDecl {
fn to_rust(&self, cg: &mut RustCodegen) {
if let Some(trait_) = &self.trait_ {
cg.add_indentedln(&format!(
"impl{} {} for {} {{",
self.generics.get_rust(),
trait_.get_rust(),
self.target.get_rust()
));
} else {
cg.add_indentedln(&format!(
"impl{} {} {{",
self.generics.get_rust(),
self.target.get_rust()
));
}
cg.indent += 1; cg.indent += 1;
self.body.to_rust(cg);
for method in &self.methods {
method.to_rust(cg);
}
cg.indent -= 1; cg.indent -= 1;
cg.add_indentedln("}\n"); cg.add_indentedln("}");
} }
} }
impl GetRust for VarDecl { impl GetRust for VarDecl {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
let mutability = if self.mutable { "mut " } else { "" };
let ty = self let ty = self
.type_ .type_
.as_ref() .as_ref()
.map(|t| format!(": {}", t.get_rust())) .map(|t| format!(": {}", t.get_rust()))
.unwrap_or_default(); .unwrap_or_default();
format!("{}{}{}", mutability, self.name, ty) format!(
"{}{}{}",
get_mutable(self.mutable),
self.name.get_rust(),
ty
)
} }
} }
impl GetRust for Path { impl GetRust for Path {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
self.0.join("::") self.0
.iter()
.map(Identifier::get_rust)
.collect::<Vec<String>>()
.join("::")
} }
} }
@@ -566,6 +730,8 @@ impl GetRust for TypePostfix {
match self { match self {
TypePostfix::Ref => format!("&"), TypePostfix::Ref => format!("&"),
TypePostfix::RefMut => format!("&mut "), TypePostfix::RefMut => format!("&mut "),
TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
} }
} }
} }
@@ -580,6 +746,122 @@ impl GetRust for Visibility {
} }
} }
impl GetRust for Identifier {
fn get_rust(&self) -> String {
self.0.clone()
}
}
impl GetRust for EnumItem {
fn get_rust(&self) -> String {
match self {
Self::Named(id) => id.get_rust(),
Self::Struct(id, s) => format!(
"{} {{{}}}",
id.get_rust(),
s.iter()
.map(|field| format!("{}: {}", field.name.get_rust(), field.type_.get_rust()))
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(id, t) => format!(
"{} ({})",
id.get_rust(),
t.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GetRust for Pattern {
fn get_rust(&self) -> String {
match self {
Self::Id(id) => id.get_rust(),
Self::Path(path) => path.get_rust(),
Self::Literal(lit) => lit.get_rust(),
Self::Struct(path, ids) => format!(
"{} {{{}}}",
path.get_rust(),
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(ids) => format!(
"({})",
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
Self::NamedTuple(path, ids) => {
format!(
"{} ({})",
path.get_rust(),
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
}
impl GetRust for Generics {
fn get_rust(&self) -> String {
if self.0.len() == 0 {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(|v| (true, v).get_rust())
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetRust for (bool, &Generic) {
fn get_rust(&self) -> String {
match &self.1 {
Generic::Lifetime(name) => format!("'{}", name.get_rust()),
Generic::Type(name, requirements) => {
name.get_rust()
+ &(if !self.0 && requirements.len() == 0 {
String::new()
} else {
format!(
": {}",
requirements
.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join("+")
)
})
}
}
}
}
impl GetRust for FieldDecl {
fn get_rust(&self) -> String {
format!(
"{}{}: {},",
self.visibility.get_rust(),
self.name.get_rust(),
self.type_.get_rust()
)
}
}
pub fn get_static_type_path(path: &Path) -> String { pub fn get_static_type_path(path: &Path) -> String {
let rust_path = path.get_rust(); let rust_path = path.get_rust();
@@ -593,3 +875,7 @@ pub fn get_static_type_path(path: &Path) -> String {
pub fn get_type_postfixes(postfixes: &[TypePostfix]) -> String { pub fn get_type_postfixes(postfixes: &[TypePostfix]) -> String {
postfixes.iter().map(TypePostfix::get_rust).collect() postfixes.iter().map(TypePostfix::get_rust).collect()
} }
pub fn get_mutable(mutable: bool) -> String {
if mutable { "mut " } else { "" }.to_string()
}
+103 -49
View File
@@ -1,4 +1,9 @@
use std::{fs, path::PathBuf, process, time::Instant}; use std::{
fs,
path::{Path, PathBuf},
process,
time::Instant,
};
use serde::Deserialize; use serde::Deserialize;
@@ -21,58 +26,108 @@ pub fn build() {
// 2. load config // 2. load config
let config = load_config(&root); let config = load_config(&root);
let src = root.join(&config.src); let src_dir = root.join(&config.src);
let out_dir = root.join(&config.output);
for entry in fs::read_dir(src).unwrap() { build_dir(&root, &src_dir, &src_dir, &out_dir);
if let Ok(entry) = entry {
let entry_path = root.join(&entry.path());
let out_dir = root.join(&config.output);
let file_name = entry.file_name();
let file_name = file_name.to_string_lossy();
// 3. read entry file
let source = match fs::read_to_string(&entry_path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read entry file\n {}", e);
process::exit(1);
}
};
let parser_result = parser::parse(&source).map_err(|e| e.to_string());
let ast = match parser_result {
Ok(ast) => ast,
Err(e) => {
eprintln!("error: parse failed\n{}", e);
process::exit(1);
}
};
// semantic::walk_ast(semantic::scope::Scope::from_top(&root, &ast), &mut ast);
let mut gc = crate::codegen::RustCodegen::new();
let output = gc.generate(&ast);
if let Err(e) = fs::create_dir_all(&out_dir) {
eprintln!("error: failed to create build dir\n {}", e);
process::exit(1);
}
let out_file = out_dir.join(file_name.replace(".mist", ".rs"));
if let Err(e) = fs::write(&out_file, output) {
eprintln!("error: failed to write output\n {}", e);
process::exit(1);
}
}
}
let elapsed = start.elapsed(); let elapsed = start.elapsed();
println!("build finished in {:.2?}", elapsed); println!("build finished in {:.2?}", elapsed);
} }
fn build_dir(root: &Path, base_src: &Path, current_dir: &Path, out_dir: &Path) {
let entries = match fs::read_dir(current_dir) {
Ok(entries) => entries,
Err(e) => {
eprintln!(
"error: failed to read directory {}\n {}",
current_dir.display(),
e
);
process::exit(1);
}
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
eprintln!("error: failed to read directory entry\n {}", e);
process::exit(1);
}
};
let path = entry.path();
// recurse into nested directories
if path.is_dir() {
build_dir(root, base_src, &path, out_dir);
continue;
}
// skip non-mist files
if path.extension().and_then(|e| e.to_str()) != Some("mist") {
continue;
}
let relative = path.strip_prefix(base_src).unwrap();
let output_path = out_dir.join(relative).with_extension("rs");
// create parent directories
if let Some(parent) = output_path.parent() {
if let Err(e) = fs::create_dir_all(parent) {
eprintln!(
"error: failed to create output directory {}\n {}",
parent.display(),
e
);
process::exit(1);
}
}
// read source
let source = match fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read file {}\n {}", path.display(), e);
process::exit(1);
}
};
let parser_result = mist_parser::parse(&source).map_err(|e| e.to_string());
let ast = match parser_result {
Ok(ast) => ast,
Err(e) => {
eprintln!("error: parse failed in {}\n{}", path.display(), e);
process::exit(1);
}
};
// semantic::walk_ast(semantic::scope::Scope::from_top(root, &ast), &mut ast);
let mut gc = crate::codegen::RustCodegen::new();
let output = gc.generate(&ast);
if let Err(e) = fs::write(&output_path, output) {
eprintln!(
"error: failed to write output {}\n {}",
output_path.display(),
e
);
process::exit(1);
}
}
}
pub fn find_project_root() -> Option<PathBuf> { pub fn find_project_root() -> Option<PathBuf> {
let mut dir = std::env::current_dir().ok()?; let mut dir = std::env::current_dir().ok()?;
@@ -87,9 +142,8 @@ pub fn find_project_root() -> Option<PathBuf> {
} }
} }
fn load_config(root: &std::path::Path) -> Config { fn load_config(root: &Path) -> Config {
let content = let content = fs::read_to_string(root.join("mist.json")).expect("failed to read mist.json");
std::fs::read_to_string(root.join("mist.json")).expect("failed to read mist.json");
serde_json::from_str(&content).expect("invalid mist.json format") serde_json::from_str(&content).expect("invalid mist.json format")
} }
-450
View File
@@ -1,450 +0,0 @@
{
"fmt": {
"package_name": "fmt",
"structs": {},
"functions": {
"append": {
"export": true,
"name": "Append",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"b": {
"export": true,
"var_type": "[]byte",
"name": "b"
}
},
"return_types": [
"[]byte"
]
},
"appendf": {
"export": true,
"name": "Appendf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"b": {
"export": true,
"var_type": "[]byte",
"name": "b"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
}
},
"return_types": [
"[]byte"
]
},
"appendln": {
"export": true,
"name": "Appendln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"b": {
"export": true,
"var_type": "[]byte",
"name": "b"
}
},
"return_types": [
"[]byte"
]
},
"errorf": {
"export": true,
"name": "Errorf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
}
},
"return_types": [
"error"
]
},
"formatString": {
"export": true,
"name": "FormatString",
"params": {
"state": {
"export": true,
"var_type": "fmt.State",
"name": "state"
},
"verb": {
"export": true,
"var_type": "rune",
"name": "verb"
}
},
"return_types": [
"string"
]
},
"fprint": {
"export": true,
"name": "Fprint",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"w": {
"export": true,
"var_type": "io.Writer",
"name": "w"
}
},
"return_types": [
"int",
"error"
]
},
"fprintf": {
"export": true,
"name": "Fprintf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
},
"w": {
"export": true,
"var_type": "io.Writer",
"name": "w"
}
},
"return_types": [
"int",
"error"
]
},
"fprintln": {
"export": true,
"name": "Fprintln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"w": {
"export": true,
"var_type": "io.Writer",
"name": "w"
}
},
"return_types": [
"int",
"error"
]
},
"fscan": {
"export": true,
"name": "Fscan",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"r": {
"export": true,
"var_type": "io.Reader",
"name": "r"
}
},
"return_types": [
"int",
"error"
]
},
"fscanf": {
"export": true,
"name": "Fscanf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
},
"r": {
"export": true,
"var_type": "io.Reader",
"name": "r"
}
},
"return_types": [
"int",
"error"
]
},
"fscanln": {
"export": true,
"name": "Fscanln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"r": {
"export": true,
"var_type": "io.Reader",
"name": "r"
}
},
"return_types": [
"int",
"error"
]
},
"print": {
"export": true,
"name": "Print",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"int",
"error"
]
},
"printf": {
"export": true,
"name": "Printf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
}
},
"return_types": [
"int",
"error"
]
},
"println": {
"export": true,
"name": "Println",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"int",
"error"
]
},
"scan": {
"export": true,
"name": "Scan",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"int",
"error"
]
},
"scanf": {
"export": true,
"name": "Scanf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
}
},
"return_types": [
"int",
"error"
]
},
"scanln": {
"export": true,
"name": "Scanln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"int",
"error"
]
},
"sprint": {
"export": true,
"name": "Sprint",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"string"
]
},
"sprintf": {
"export": true,
"name": "Sprintf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
}
},
"return_types": [
"string"
]
},
"sprintln": {
"export": true,
"name": "Sprintln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
}
},
"return_types": [
"string"
]
},
"sscan": {
"export": true,
"name": "Sscan",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"str": {
"export": true,
"var_type": "string",
"name": "str"
}
},
"return_types": [
"int",
"error"
]
},
"sscanf": {
"export": true,
"name": "Sscanf",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"format": {
"export": true,
"var_type": "string",
"name": "format"
},
"str": {
"export": true,
"var_type": "string",
"name": "str"
}
},
"return_types": [
"int",
"error"
]
},
"sscanln": {
"export": true,
"name": "Sscanln",
"params": {
"a": {
"export": true,
"var_type": "[]any",
"name": "a"
},
"str": {
"export": true,
"var_type": "string",
"name": "str"
}
},
"return_types": [
"int",
"error"
]
}
}
}
}
-17
View File
@@ -1,17 +0,0 @@
class MyClass {
String message;
public constructor(str* name) {
self.message = format!("Hello {}!", name);
}
public void greet(self*) {
println!("{}", self.message);
}
}
void main() {
var my_class = new MyClass("World");
my_class.greet();
var x = 1 + 2 + 3;
}