Compare commits
122
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60e5995dc6 | ||
|
|
c621a1bb8d | ||
|
|
58a79ad2ef | ||
|
|
490509cb14 | ||
|
|
bdca96212c | ||
|
|
e3d885e22d | ||
|
|
6917d36ac4 | ||
|
|
90de040ae8 | ||
|
|
9d024b7e25 | ||
|
|
50b05b6def | ||
|
|
2c426c78c6 | ||
|
|
47b179b782 | ||
|
|
5174cc34ee | ||
|
|
b188ef0eb2 | ||
|
|
3619f0e7dc | ||
|
|
ced2d47977 | ||
|
|
a6e52b0191 | ||
|
|
32c411ba78 | ||
|
|
1a80fe074b | ||
|
|
cbd060149d | ||
|
|
e6bf1e0d2c | ||
|
|
0c6723e967 | ||
|
|
b22c0e8527 | ||
|
|
6346ffc771 | ||
|
|
efe32d8e5f | ||
|
|
c6b9588f4d | ||
|
|
216c61228c | ||
|
|
3aba4a359b | ||
|
|
fa2c0b2658 | ||
|
|
0bb7146d13 | ||
|
|
3c5b030bdd | ||
|
|
6c7692208d | ||
|
|
8c89f9ff65 | ||
|
|
f9c5fb4ec8 | ||
|
|
527e450f9e | ||
|
|
459c4b1ee0 | ||
|
|
933f102680 | ||
|
|
6fbc2a086e | ||
|
|
80e17ffafb | ||
|
|
25f4b5470d | ||
|
|
cdb34984db | ||
|
|
9b04a17fdd | ||
|
|
626990216c | ||
|
|
78cac259f2 | ||
|
|
5912032dff | ||
|
|
00e10d1097 | ||
|
|
50fa660392 | ||
|
|
192769c8ad | ||
|
|
5920a9f236 | ||
|
|
d8d3b327dd | ||
|
|
5c732bb8d1 | ||
|
|
01532baf12 | ||
|
|
03f9794671 | ||
|
|
fd48d6c9c6 | ||
|
|
ef7ccc5aed | ||
|
|
23f726fd41 | ||
|
|
a6ad375c58 | ||
|
|
e4eeb20a2c | ||
|
|
5bdcd40edb | ||
|
|
c1cb9bd7bf | ||
|
|
e416af3403 | ||
|
|
3b0a450895 | ||
|
|
8cd16f4c4f | ||
|
|
2a833c6cab | ||
|
|
950dded614 | ||
|
|
43b6e95b12 | ||
|
|
73d37b9f35 | ||
|
|
d3c1be859d | ||
|
|
e97b3cac8f | ||
|
|
380755bf83 | ||
|
|
e063d4c685 | ||
|
|
28d4d784f2 | ||
|
|
bb9ad547a3 | ||
|
|
6f7f11719d | ||
|
|
81d0286226 | ||
|
|
22b1b377f3 | ||
|
|
dfa5487031 | ||
|
|
2fb38b6974 | ||
|
|
476d984d4a | ||
|
|
d3b6e88b14 | ||
|
|
5916daaada | ||
|
|
e6c030e8c8 | ||
|
|
4e18f4530f | ||
|
|
460d296759 | ||
|
|
5a475f3b8a | ||
|
|
0c2746eefc | ||
|
|
f69c53d3fc | ||
|
|
dff77a8c01 | ||
|
|
1b1d38cdba | ||
|
|
3e25bf0456 | ||
|
|
910657c755 | ||
|
|
020dd3b76b | ||
|
|
0bf32b16cd | ||
|
|
65f4c5278d | ||
|
|
bbcc639331 | ||
|
|
ed4a505a6a | ||
|
|
0e6c73e85c | ||
|
|
205e2d9fd3 | ||
|
|
630528a843 | ||
|
|
39b15d4207 | ||
|
|
91bee0c4fc | ||
|
|
8b409f4ccf | ||
|
|
c7ada72029 | ||
|
|
bd066e05d1 | ||
|
|
093c281ea9 | ||
|
|
60bc1d2510 | ||
|
|
6f6c32b646 | ||
|
|
2d56cf1212 | ||
|
|
aa5640175f | ||
|
|
f98b9d7514 | ||
|
|
dc49cddc20 | ||
|
|
a6fb70eebf | ||
|
|
c51ff01ce8 | ||
|
|
cba78c2ac9 | ||
|
|
81061f26a5 | ||
|
|
3342893aab | ||
|
|
580c3297cb | ||
|
|
5eeaf8c35d | ||
|
|
a9fdfe4100 | ||
|
|
c6e34bbc70 | ||
|
|
27c6eb74c3 | ||
|
|
2ccec652da |
@@ -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
@@ -26,5 +26,5 @@ target
|
||||
|
||||
/target
|
||||
|
||||
/test/build
|
||||
/test/output.json
|
||||
/mist-test/build
|
||||
/mist-test/output.json
|
||||
Generated
+9
-9
@@ -64,9 +64,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.185"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
@@ -75,17 +75,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "mist"
|
||||
version = "0.0.1-alpha0"
|
||||
name = "mist-lang"
|
||||
version = "0.0.2-alpha0"
|
||||
dependencies = [
|
||||
"parser",
|
||||
"mist-parser",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parser"
|
||||
version = "0.1.0"
|
||||
name = "mist-parser"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"pest",
|
||||
"pest_derive",
|
||||
@@ -221,9 +221,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.19.0"
|
||||
version = "1.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
||||
checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
|
||||
|
||||
[[package]]
|
||||
name = "ucd-trie"
|
||||
|
||||
+13
-3
@@ -1,9 +1,19 @@
|
||||
[package]
|
||||
name = "mist"
|
||||
version = "0.0.1-alpha0"
|
||||
name = "mist-lang"
|
||||
version = "0.0.2-alpha0"
|
||||
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]
|
||||
serde = { version = "1.0.228", features = ["serde_derive"] }
|
||||
serde_json = "1.0.149"
|
||||
parser = { path = "./parser" }
|
||||
mist-parser = { path = "./parser", version = "0.1.1"}
|
||||
|
||||
[[bin]]
|
||||
name = "mist"
|
||||
path = "src/main.rs"
|
||||
|
||||
@@ -4,13 +4,9 @@
|
||||
Originally this readme was part of the Carbon Language project, licensed with Apache-2.0
|
||||
-->
|
||||
|
||||
<!-- <p align="center">
|
||||
<a href="#why-build-carbon">Why?</a> |
|
||||
<a href="#language-goals">Goals</a> |
|
||||
<a href="#project-status">Status</a> |
|
||||
<a href="#getting-started">Getting started</a> |
|
||||
<a href="#join-us">Join us</a>
|
||||
</p> -->
|
||||
<p align="center">
|
||||
<a href="https://mist.selimaj.dev">Documentation</a>
|
||||
</p>
|
||||
|
||||
|
||||
<img src="code.png" align="right" width="575" alt="">
|
||||
|
||||
Generated
+7
@@ -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"
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "mist-test"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[[bin]]
|
||||
name = "main"
|
||||
path = "build/main.rs"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,95 @@
|
||||
use <super::task>;
|
||||
use <super::logger>;
|
||||
use <super::event>;
|
||||
|
||||
pub class Application {
|
||||
String name;
|
||||
|
||||
Vec<task::Task> tasks;
|
||||
Vec<String> plugins;
|
||||
|
||||
logger::Logger logger;
|
||||
|
||||
bool running;
|
||||
i32 ticks;
|
||||
|
||||
pub 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;
|
||||
}
|
||||
|
||||
pub void boot(self mut*) {
|
||||
self.logger.info("booting application");
|
||||
|
||||
self.running = true;
|
||||
|
||||
self.emit(event::Event::Startup);
|
||||
}
|
||||
|
||||
pub 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());
|
||||
}
|
||||
|
||||
pub void shutdown(self mut*) {
|
||||
self.emit(event::Event::Shutdown);
|
||||
|
||||
self.logger.warning("shutdown");
|
||||
|
||||
self.running = false;
|
||||
}
|
||||
|
||||
pub 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub enum Event {
|
||||
Startup,
|
||||
Shutdown,
|
||||
TaskExecuted(String),
|
||||
PluginLoaded(String),
|
||||
Error(String),
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use <std::fmt::Formatter>;
|
||||
use <std::fmt>;
|
||||
|
||||
pub trait TestLogging<T: fmt::Display>: fmt::Display {
|
||||
String get();
|
||||
}
|
||||
|
||||
pub enum LogLevel {
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
impl fmt::Display for LogLevel {
|
||||
fmt::Result fmt(self*, Formatter<'_> mut* f) {
|
||||
match (self) {
|
||||
LogLevel::Info => {
|
||||
return write!(f, "[INFO]");
|
||||
}
|
||||
|
||||
LogLevel::Warning => {
|
||||
return write!(f, "[WARN]");
|
||||
}
|
||||
|
||||
LogLevel::Error => {
|
||||
return write!(f, "[ERROR]");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub class Logger {
|
||||
String prefix;
|
||||
|
||||
pub constructor(str* prefix) {
|
||||
self.prefix = prefix.to_string();
|
||||
}
|
||||
|
||||
pub void info(self*, str* message) {
|
||||
self.log(LogLevel::Info, message);
|
||||
}
|
||||
|
||||
pub void warning(self*, str* message) {
|
||||
self.log(LogLevel::Warning, message);
|
||||
}
|
||||
|
||||
pub 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 {
|
||||
fmt::Result fmt(self*, Formatter<'_> mut* f) {
|
||||
return write!(f, "logger ({})", self.prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
pub mod app;
|
||||
pub mod task;
|
||||
pub mod plugin;
|
||||
pub mod logger;
|
||||
pub 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();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub struct PluginInfo {
|
||||
pub String name,
|
||||
pub String version,
|
||||
}
|
||||
|
||||
pub class PluginRegistry<T> {
|
||||
T plugins;
|
||||
|
||||
pub constructor(T plugins) {
|
||||
self.plugins = plugins;
|
||||
}
|
||||
|
||||
pub T plugins(self) {
|
||||
return self.plugins;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
pub enum TaskState {
|
||||
Pending,
|
||||
Running,
|
||||
Finished,
|
||||
Failed,
|
||||
}
|
||||
|
||||
pub struct Task {
|
||||
pub String name,
|
||||
pub TaskState state,
|
||||
pub i32 executions,
|
||||
}
|
||||
|
||||
pub Task create_task(str* name) {
|
||||
return Task {
|
||||
name: name.to_string(),
|
||||
state: TaskState::Pending,
|
||||
executions: 0,
|
||||
};
|
||||
}
|
||||
+7
-2
@@ -1,7 +1,12 @@
|
||||
[package]
|
||||
name = "parser"
|
||||
version = "0.1.0"
|
||||
name = "mist-parser"
|
||||
version = "0.1.1"
|
||||
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]
|
||||
pest = "2.8.6"
|
||||
|
||||
+102
-16
@@ -1,23 +1,26 @@
|
||||
use serde::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>);
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[derive(Debug, Clone, Serialize, Default)]
|
||||
pub struct Block(pub Vec<Statement>);
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum TypePostfix {
|
||||
Ref,
|
||||
RefMut,
|
||||
RefLifetime(Identifier),
|
||||
RefMutLifetime(Identifier),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum Visibility {
|
||||
Public,
|
||||
PublicTarget(Path),
|
||||
Private,
|
||||
}
|
||||
|
||||
@@ -38,13 +41,14 @@ pub enum TypeExprKind {
|
||||
Path(Path),
|
||||
PathParams(Path, Vec<TypeExpr>),
|
||||
Tuple(Vec<TypeExpr>),
|
||||
Lifetime(Identifier),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>);
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Path(pub Vec<String>);
|
||||
pub struct Path(pub Vec<Identifier>);
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum BinaryOp {
|
||||
@@ -59,6 +63,8 @@ pub enum BinaryOp {
|
||||
GreaterThan,
|
||||
LessThanOrEqual,
|
||||
GreaterThanOrEqual,
|
||||
And,
|
||||
Or,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -67,25 +73,75 @@ pub struct TopLevel(pub TopLevelKind, pub Vec<Attribute>);
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum TopLevelKind {
|
||||
ModAttribute,
|
||||
Include(Path),
|
||||
Import(Visibility, Path),
|
||||
Mod(Visibility, 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 {
|
||||
visibility: Visibility,
|
||||
name: String,
|
||||
fields: FieldList,
|
||||
name: Identifier,
|
||||
generics: Generics,
|
||||
fields: Vec<FieldDecl>,
|
||||
},
|
||||
FunctionDecl(FunctionDecl),
|
||||
ClassDecl {
|
||||
visibility: Visibility,
|
||||
name: String,
|
||||
fields: Vec<VarDeclStmt>,
|
||||
name: Identifier,
|
||||
generics: Generics,
|
||||
fields: Vec<FieldDeclStmt>,
|
||||
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)]
|
||||
pub struct ClassConstructor {
|
||||
pub visibility: Visibility,
|
||||
pub generics: Generics,
|
||||
pub params: ParamList,
|
||||
pub body: Block,
|
||||
}
|
||||
@@ -93,18 +149,19 @@ pub struct ClassConstructor {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct FunctionDecl {
|
||||
pub visibility: Visibility,
|
||||
pub name: String,
|
||||
pub name: Identifier,
|
||||
pub generics: Generics,
|
||||
pub params: ParamList,
|
||||
pub return_type: TypeExpr,
|
||||
pub body: Block,
|
||||
pub body: Option<Block>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum Postfix {
|
||||
FieldAccess(String),
|
||||
FieldAccess(Identifier),
|
||||
Call(Vec<Expression>),
|
||||
MacroCall(String),
|
||||
StructCall(Vec<(String, Expression)>),
|
||||
StructCall(Vec<(Identifier, Expression)>),
|
||||
Index(Expression),
|
||||
Binary(BinaryOp, Expression),
|
||||
}
|
||||
@@ -138,20 +195,30 @@ pub enum Statement {
|
||||
body: Box<Statement>,
|
||||
},
|
||||
For {
|
||||
pattern: String,
|
||||
mutable: bool,
|
||||
pattern: Pattern,
|
||||
iterator: Expression,
|
||||
body: Box<Statement>,
|
||||
},
|
||||
Match(Expression, Vec<(Pattern, Block)>),
|
||||
|
||||
Return(Option<Expression>),
|
||||
Break,
|
||||
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)]
|
||||
pub struct VarDecl {
|
||||
pub mutable: bool,
|
||||
pub name: String,
|
||||
pub name: Pattern,
|
||||
pub type_: Option<TypeExpr>,
|
||||
}
|
||||
|
||||
@@ -161,6 +228,19 @@ pub struct VarDeclStmt {
|
||||
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)]
|
||||
pub struct VarAssignStmt {
|
||||
pub target: Expression,
|
||||
@@ -192,3 +272,9 @@ pub enum Literal {
|
||||
Bool(bool),
|
||||
Tuple(Vec<Expression>),
|
||||
}
|
||||
|
||||
impl TypeExpr {
|
||||
pub fn no_px(kind: TypeExprKind) -> Self {
|
||||
Self(kind, Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
use std::fmt::Debug;
|
||||
|
||||
use pest::iterators::Pair;
|
||||
|
||||
use crate::Rule;
|
||||
|
||||
pub type AstResult<'a, T, ET = T> = Result<T, AstError<'a, ET>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ParseError<'a, T> {
|
||||
PreAst(pest::error::Error<Rule>),
|
||||
Ast(AstError<'a, T>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AstError<'a, T> {
|
||||
pub span: pest::Span<'a>,
|
||||
pub error_code: ErrorCode,
|
||||
pub error_message: String,
|
||||
pub recovered: Option<T>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ErrorCode {
|
||||
InvalidStatement,
|
||||
AstGenBug,
|
||||
}
|
||||
|
||||
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
|
||||
fn from(value: pest::error::Error<Rule>) -> Self {
|
||||
Self::PreAst(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> From<AstError<'a, T>> for ParseError<'a, T> {
|
||||
fn from(value: AstError<'a, T>) -> Self {
|
||||
Self::Ast(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, F> AstError<'a, F> {
|
||||
pub fn get<T>(self) -> AstError<'a, T> {
|
||||
AstError {
|
||||
span: self.span,
|
||||
error_code: self.error_code,
|
||||
error_message: self.error_message,
|
||||
recovered: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T, F> {
|
||||
Err(Self {
|
||||
span: pair.as_span(),
|
||||
error_code: ErrorCode::AstGenBug,
|
||||
error_message: format!("Possible bug, unimplemented: {:#?}", pair.as_rule()),
|
||||
recovered: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IntoErr<T, FA, FR> {
|
||||
fn get(self) -> T;
|
||||
fn get_map(self, m: impl Fn(FA) -> FR) -> T;
|
||||
}
|
||||
|
||||
impl<'a, T, TE, TE2> IntoErr<AstResult<'a, T, TE2>, TE, TE2> for AstResult<'a, T, TE> {
|
||||
fn get(self) -> AstResult<'a, T, TE2> {
|
||||
self.map_err(AstError::get)
|
||||
}
|
||||
|
||||
fn get_map(self, m: impl Fn(TE) -> TE2) -> AstResult<'a, T, TE2> {
|
||||
self.map_err(|e| AstError {
|
||||
span: e.span,
|
||||
error_code: e.error_code,
|
||||
error_message: e.error_message,
|
||||
recovered: e.recovered.map(m),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait GetLength {
|
||||
fn len(&self) -> usize;
|
||||
}
|
||||
|
||||
impl<T, E> GetLength for Result<Vec<T>, E> {
|
||||
fn len(&self) -> usize {
|
||||
if let Ok(v) = self { v.len() } else { 0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_recovered<'a, T: Debug, ET>(
|
||||
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
||||
where
|
||||
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, ET>>,
|
||||
{
|
||||
collect_recovered_map(pairs, T::try_from)
|
||||
}
|
||||
|
||||
pub fn collect_recovered_map<'a, T: Debug, F, ET>(
|
||||
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
||||
f: F,
|
||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
||||
where
|
||||
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T, ET>,
|
||||
{
|
||||
let mut items = Vec::new();
|
||||
let mut last_error: Option<AstError<'a, ET>> = None;
|
||||
|
||||
for pair in pairs {
|
||||
match f(pair) {
|
||||
Ok(item) => items.push(item),
|
||||
Err(e) => {
|
||||
last_error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match last_error {
|
||||
Some(ast_err) => Err(AstError {
|
||||
span: ast_err.span,
|
||||
error_code: ast_err.error_code,
|
||||
error_message: ast_err.error_message,
|
||||
recovered: Some(items),
|
||||
}),
|
||||
None => Ok(items),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AstErrorAnalyzer<'a, T>(pub Option<AstError<'a, T>>);
|
||||
|
||||
impl<'a, T> AstErrorAnalyzer<'a, T> {
|
||||
pub fn get<V: Clone, V2: Clone + Into<V>>(
|
||||
&mut self,
|
||||
r: AstResult<'a, V, V2>,
|
||||
) -> AstResult<'a, V, V2> {
|
||||
if let Err(e) = r {
|
||||
self.0 = Some(e.clone().get());
|
||||
|
||||
if let Some(recovered) = e.recovered {
|
||||
Ok(recovered.into())
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(self, v: T) -> AstResult<'a, T> {
|
||||
if let Some(mut e) = self.0 {
|
||||
e.recovered = Some(v);
|
||||
|
||||
Err(e)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
+421
-73
@@ -1,44 +1,138 @@
|
||||
// ======================================================
|
||||
// LEXICAL
|
||||
// ======================================================
|
||||
|
||||
WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
|
||||
COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
|
||||
|
||||
program = { SOI ~ top_level* ~ EOI }
|
||||
// ------------------------------------------------------
|
||||
// PRIMITIVES
|
||||
// ------------------------------------------------------
|
||||
|
||||
// primitives
|
||||
identifier = @{ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")* }
|
||||
integer = @{ ASCII_DIGIT+ }
|
||||
float = @{ ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+ }
|
||||
boolean = { "true" | "false" }
|
||||
string_lit = { "\"" ~ inner_str ~ "\"" }
|
||||
inner_str = @{ (!"\"" ~ ("\\\"" | ANY))* }
|
||||
static_path = { identifier ~ ("::" ~ identifier)* }
|
||||
|
||||
export = { "public" }
|
||||
mutable = { "mut" }
|
||||
sharp = _{ "#" }
|
||||
var = { "var" }
|
||||
var_decl = { (var | type_expr) ~ mutable? ~ identifier }
|
||||
integer = @{ ASCII_DIGIT+ }
|
||||
|
||||
float = @{
|
||||
ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+
|
||||
}
|
||||
|
||||
boolean = {
|
||||
"true"
|
||||
| "false"
|
||||
}
|
||||
|
||||
string_lit = {
|
||||
"\"" ~ inner_str ~ "\""
|
||||
}
|
||||
|
||||
inner_str = @{
|
||||
(!"\"" ~ ("\\\"" | ANY))*
|
||||
}
|
||||
|
||||
semicolon = _{ ";" }
|
||||
|
||||
// ================= CLASS =================
|
||||
class_constructor = {
|
||||
export? ~ "constructor" ~ "(" ~ param_list? ~ ")" ~ block
|
||||
static_path = {
|
||||
identifier ~ ("::" ~ identifier)*
|
||||
}
|
||||
|
||||
class_fields = { var_decl_statement* }
|
||||
// ======================================================
|
||||
// PROGRAM
|
||||
// ======================================================
|
||||
|
||||
self_param = { "self" ~ mutable? ~ deref_px? }
|
||||
|
||||
method = {
|
||||
export? ~ type_expr ~ identifier ~ "(" ~ self_param? ~ param_list? ~ ")" ~ block
|
||||
program = {
|
||||
SOI ~ top_level* ~ EOI
|
||||
}
|
||||
|
||||
class_decl = {
|
||||
"class" ~ identifier ~ "{" ~ class_fields ~ class_constructor ~ method* ~ "}"
|
||||
// ======================================================
|
||||
// MODIFIERS
|
||||
// ======================================================
|
||||
|
||||
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
||||
mutable = { "mut" }
|
||||
var = { "var" }
|
||||
|
||||
// ======================================================
|
||||
// ERROR RECOVERY
|
||||
// ======================================================
|
||||
|
||||
unexpected_statement = {
|
||||
(!(semicolon | "}" | statement) ~ ANY)+
|
||||
}
|
||||
|
||||
// ================= TOP LEVEL =================
|
||||
// ======================================================
|
||||
// GENERICS
|
||||
// ======================================================
|
||||
generic = { lifetime | (identifier ~ (":" ~ type_expr_param ~ ("+" ~ type_expr_param)*)?) }
|
||||
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
|
||||
|
||||
top_level = { (attributes ~ (import | function_decl | struct_decl | class_decl)) | mod_attribute }
|
||||
// ======================================================
|
||||
// TYPES
|
||||
// ======================================================
|
||||
|
||||
tuple_type = {
|
||||
"(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
|
||||
}
|
||||
|
||||
path_type = {
|
||||
static_path ~ ("<" ~ (type_expr_param ~ ("," ~ type_expr_param)*)? ~ ">")?
|
||||
}
|
||||
|
||||
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 = {
|
||||
"#" ~ "[" ~ meta ~ "]"
|
||||
@@ -49,39 +143,176 @@ mod_attribute = {
|
||||
}
|
||||
|
||||
meta = {
|
||||
static_path ~ ("=" ~ primary | "(" ~ meta_list? ~ ")")?
|
||||
static_path ~ ("=" ~ literal | "(" ~ meta_list? ~ ")")?
|
||||
}
|
||||
|
||||
meta_list = {
|
||||
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 = { export? ~ type_expr ~ identifier }
|
||||
field = {
|
||||
visibility? ~ type_expr ~ identifier
|
||||
}
|
||||
|
||||
param_list = { var_decl ~ ("," ~ var_decl)* ~ ","? }
|
||||
field_list = {
|
||||
field ~ ("," ~ field)* ~ ","?
|
||||
}
|
||||
|
||||
param_list = {
|
||||
var_decl ~ ("," ~ var_decl)* ~ ","?
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// IMPORTS / MODULES
|
||||
// ======================================================
|
||||
|
||||
import = {
|
||||
visibility? ~ "use" ~ "<" ~ static_path ~ ">" ~ semicolon
|
||||
}
|
||||
|
||||
mod_package = {
|
||||
visibility? ~ "mod" ~ identifier ~ semicolon
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// STRUCTS
|
||||
// ======================================================
|
||||
|
||||
struct_decl = {
|
||||
export? ~ "struct" ~ identifier ~ "{" ~ field_list? ~ "}"
|
||||
visibility? ~ "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 = {
|
||||
visibility? ~ "enum" ~ identifier ~ generics? ~ "{" ~ enum_fields ~ "}"
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// CLASSES
|
||||
// ======================================================
|
||||
|
||||
class_constructor = {
|
||||
visibility? ~ "constructor" ~ generics? ~ "(" ~ param_list? ~ ")" ~ block
|
||||
}
|
||||
|
||||
class_fields = {
|
||||
class_field*
|
||||
}
|
||||
|
||||
class_field = {
|
||||
field ~ ("=" ~ expr)? ~ semicolon
|
||||
}
|
||||
|
||||
self_param = {
|
||||
"self" ~ mutable? ~ deref_px?
|
||||
}
|
||||
|
||||
method = {
|
||||
visibility? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ block
|
||||
}
|
||||
|
||||
class_item = _{
|
||||
impl_decl
|
||||
| method
|
||||
}
|
||||
|
||||
class_decl = {
|
||||
visibility? ~ "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 = {
|
||||
visibility? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ semicolon
|
||||
}
|
||||
|
||||
trait_item = _{
|
||||
method
|
||||
| method_no_body
|
||||
}
|
||||
|
||||
trait_decl = {
|
||||
visibility? ~ "trait" ~ identifier ~ generics? ~ trait_requirements? ~ "{" ~ trait_item* ~ "}"
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// FUNCTIONS
|
||||
// ======================================================
|
||||
|
||||
function_decl = {
|
||||
export? ~ type_expr ~ identifier ~ "(" ~ param_list? ~ ")" ~ block
|
||||
visibility? ~ 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 | unexpected_statement)* ~ "}"
|
||||
}
|
||||
|
||||
statement = _{
|
||||
expr_stmt
|
||||
| var_decl_statement
|
||||
| match_stmt
|
||||
| assign_statement
|
||||
| if_stmt
|
||||
| while_stmt
|
||||
@@ -91,32 +322,61 @@ statement = _{
|
||||
| break_stmt
|
||||
| continue_stmt
|
||||
| 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* }
|
||||
statement_branch = { "(" ~ expr ~ ")" ~ statement }
|
||||
|
||||
else_if = {
|
||||
"else" ~ "if" ~ statement_branch
|
||||
}
|
||||
|
||||
else_if_list = {
|
||||
else_if*
|
||||
}
|
||||
|
||||
if_stmt = {
|
||||
"if" ~ "(" ~ expr ~ ")" ~ statement ~ else_if_list ~ ("else" ~ statement)?
|
||||
"if" ~ statement_branch ~ else_if_list ~ ("else" ~ statement)?
|
||||
}
|
||||
|
||||
// ------------------------------------------------------
|
||||
// LOOPS
|
||||
// ------------------------------------------------------
|
||||
|
||||
while_stmt = {
|
||||
"while" ~ "(" ~ expr ~ ")" ~ statement
|
||||
"while" ~ statement_branch
|
||||
}
|
||||
|
||||
c_for_stmt = {
|
||||
@@ -124,31 +384,84 @@ c_for_stmt = {
|
||||
}
|
||||
|
||||
for_stmt = {
|
||||
"for" ~ "(" ~ identifier ~ "in" ~ expr ~ ")" ~ statement
|
||||
"for" ~ "(" ~ mutable? ~ pattern ~ "in" ~ expr ~ ")" ~ statement
|
||||
}
|
||||
|
||||
// ================= EXPRESSIONS =================
|
||||
tuple_type = { "(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")" }
|
||||
path_type = { static_path ~ ("<" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ">")? }
|
||||
ref_type = { mutable? ~ "*" }
|
||||
type_expr = { (path_type | tuple_type) ~ ref_type* }
|
||||
// ------------------------------------------------------
|
||||
// MATCH
|
||||
// ------------------------------------------------------
|
||||
|
||||
match_item = {
|
||||
pattern ~ "=>" ~ block
|
||||
}
|
||||
|
||||
match_stmt = {
|
||||
"match" ~ "(" ~ expr ~ ")" ~ "{" ~ match_item* ~ "}"
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// EXPRESSIONS
|
||||
// ======================================================
|
||||
|
||||
// ------------------------------------------------------
|
||||
// TUPLES
|
||||
// ------------------------------------------------------
|
||||
|
||||
tuple = {
|
||||
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
|
||||
}
|
||||
|
||||
// ------------------------------------------------------
|
||||
// MACROS
|
||||
// ------------------------------------------------------
|
||||
|
||||
macro_inner_v = {
|
||||
"(" ~ macro_inner_v* ~ ")"
|
||||
| (!("(" | ")") ~ ANY)
|
||||
}
|
||||
|
||||
tuple = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" }
|
||||
// ------------------------------------------------------
|
||||
// PRIMARY EXPRESSIONS
|
||||
// ------------------------------------------------------
|
||||
|
||||
primary = {
|
||||
float
|
||||
| integer
|
||||
| boolean
|
||||
| string_lit
|
||||
literal
|
||||
| static_path
|
||||
| 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 = {
|
||||
field_px
|
||||
| call_px
|
||||
@@ -158,14 +471,29 @@ postfix = {
|
||||
| binary_px
|
||||
}
|
||||
|
||||
field_px = { "." ~ identifier }
|
||||
call_px = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" }
|
||||
macro_call_px = { "!" ~ "(" ~ macro_inner_v* ~ ")" }
|
||||
struct_px = { "{" ~ (struct_field_decl ~ ("," ~ struct_field_decl)*)? ~ ","? ~ "}" }
|
||||
index_px = { "[" ~ expr ~ "]" }
|
||||
binary_px = { bin_op ~ expr }
|
||||
bin_op = { "<=" | ">=" | "==" | "!=" | "+" | "-" | "*" | "/" | "%" | "<" | ">" }
|
||||
struct_field_decl = { identifier ~ ":" ~ expr }
|
||||
// ------------------------------------------------------
|
||||
// PREFIX EXPRESSIONS
|
||||
// ------------------------------------------------------
|
||||
|
||||
deref_px = {
|
||||
"*"
|
||||
}
|
||||
|
||||
mut_ref_px = {
|
||||
"&" ~ mutable
|
||||
}
|
||||
|
||||
ref_px = {
|
||||
"&"
|
||||
}
|
||||
|
||||
new_px = {
|
||||
"new"
|
||||
}
|
||||
|
||||
not_px = {
|
||||
"!"
|
||||
}
|
||||
|
||||
prefix = {
|
||||
deref_px
|
||||
@@ -175,13 +503,33 @@ prefix = {
|
||||
| not_px
|
||||
}
|
||||
|
||||
deref_px = { "*" }
|
||||
mut_ref_px = { "&" ~ mutable }
|
||||
ref_px = { "&" }
|
||||
new_px = { "new" }
|
||||
not_px = { "!" }
|
||||
prefix_list = {
|
||||
prefix*
|
||||
}
|
||||
|
||||
prefix_list = { prefix* }
|
||||
// ------------------------------------------------------
|
||||
// OPERATORS
|
||||
// ------------------------------------------------------
|
||||
|
||||
bin_op = {
|
||||
"<="
|
||||
| ">="
|
||||
| "=="
|
||||
| "!="
|
||||
| "&&"
|
||||
| "||"
|
||||
| "+"
|
||||
| "-"
|
||||
| "*"
|
||||
| "/"
|
||||
| "%"
|
||||
| "<"
|
||||
| ">"
|
||||
}
|
||||
|
||||
// ------------------------------------------------------
|
||||
// EXPRESSIONS
|
||||
// ------------------------------------------------------
|
||||
|
||||
expr = {
|
||||
prefix_list ~ primary ~ postfix*
|
||||
|
||||
+37
-575
@@ -2,609 +2,71 @@ use pest::Parser;
|
||||
use pest_derive::Parser;
|
||||
|
||||
pub mod ast;
|
||||
pub mod error;
|
||||
pub mod parser;
|
||||
|
||||
use ast::*;
|
||||
|
||||
use crate::error::{IntoErr, ParseError};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[grammar = "./src/grammar.pest"]
|
||||
pub struct MistParser;
|
||||
|
||||
// convenience alias for pest errors
|
||||
pub type ParseError = pest::error::Error<Rule>;
|
||||
|
||||
pub fn parse(source: &str) -> Result<Vec<TopLevel>, ParseError> {
|
||||
pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<TopLevel>>> {
|
||||
let mut pairs = MistParser::parse(Rule::program, source)?;
|
||||
|
||||
let mut statements = vec![];
|
||||
|
||||
let mut analyzer = error::AstErrorAnalyzer(None);
|
||||
|
||||
for pair in pairs.next().unwrap().into_inner() {
|
||||
if pair.as_rule() != Rule::EOI {
|
||||
statements.push(TopLevel::from(pair));
|
||||
statements.push(analyzer.get(TopLevel::try_from(pair)).get()?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(statements)
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for TypeExpr {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::type_expr => TypeExpr(
|
||||
TypeExprKind::from(inner.next().unwrap()),
|
||||
inner.map(TypePostfix::from).collect(),
|
||||
),
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
match analyzer.build(statements) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => Err(ParseError::Ast(e)),
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for TypePostfix {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let inner = pair.into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::ref_type => {
|
||||
if inner.peek().is_some() {
|
||||
TypePostfix::RefMut
|
||||
} else {
|
||||
TypePostfix::Ref
|
||||
}
|
||||
}
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for TypeExprKind {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::tuple_type => TypeExprKind::Tuple(inner.map(TypeExpr::from).collect()),
|
||||
Rule::path_type => {
|
||||
let path = Path::from(inner.next().unwrap());
|
||||
let params = inner.map(TypeExpr::from).collect::<Vec<_>>();
|
||||
|
||||
if params.len() == 0 {
|
||||
TypeExprKind::Path(path)
|
||||
} else {
|
||||
TypeExprKind::PathParams(path, params)
|
||||
}
|
||||
}
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Path {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
match pair.as_rule() {
|
||||
Rule::static_path => Path(pair.into_inner().map(|i| i.as_str().to_string()).collect()),
|
||||
_ => 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)
|
||||
#[macro_export]
|
||||
macro_rules! ast_ensure {
|
||||
($pair:expr, $rule:expr => $body:block) => {
|
||||
if $pair.as_rule() == $rule
|
||||
$body
|
||||
else {
|
||||
Err(AstError {
|
||||
span: $pair.as_span(),
|
||||
error_code: crate::error::ErrorCode::AstGenBug,
|
||||
error_message: format!("Possible bug: expected {:?}, got {}", $rule, $pair),
|
||||
recovered: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
FieldList(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for ParamList {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
ParamList(pair.into_inner().map(VarDecl::from).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Attribute {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
match pair.as_rule() {
|
||||
Rule::attribute => {
|
||||
// unwrap #[ ... ]
|
||||
Attribute::from(pair.into_inner().next().unwrap())
|
||||
}
|
||||
|
||||
Rule::meta => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
// first item is always the path
|
||||
let path = Path::from(inner.next().unwrap());
|
||||
|
||||
// check what comes next
|
||||
match inner.next() {
|
||||
None => {
|
||||
// #[path]
|
||||
Attribute::Path(path)
|
||||
}
|
||||
|
||||
Some(next) => match next.as_rule() {
|
||||
Rule::primary => {
|
||||
// #[path = literal]
|
||||
Attribute::NameValue {
|
||||
path,
|
||||
value: Literal::from(next),
|
||||
}
|
||||
}
|
||||
|
||||
Rule::meta_list => {
|
||||
// #[path(...)]
|
||||
let items = next.into_inner().map(Attribute::from).collect();
|
||||
|
||||
Attribute::List { path, items }
|
||||
}
|
||||
|
||||
_ => unreachable!("unexpected rule in meta: {:?}", next.as_rule()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Rule::meta_list => {
|
||||
// This case usually won't be hit directly,
|
||||
// but it's nice to keep it safe if reused
|
||||
let items = pair.into_inner().map(Attribute::from).collect::<Vec<_>>();
|
||||
|
||||
// NOTE: this shouldn't normally construct an Attribute alone
|
||||
// but you can panic or wrap depending on your design
|
||||
panic!("meta_list should be handled inside meta: {:?}", items);
|
||||
}
|
||||
|
||||
_ => unreachable!("unexpected rule: {:?}", pair.as_rule()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for TopLevel {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let attributes = inner
|
||||
.next()
|
||||
.unwrap()
|
||||
.into_inner()
|
||||
.map(Attribute::from)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
TopLevel(
|
||||
inner
|
||||
.next()
|
||||
.map(TopLevelKind::from)
|
||||
.unwrap_or(TopLevelKind::ModAttribute),
|
||||
attributes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for StatementBranch {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let condition = Expression::from(inner.next().unwrap());
|
||||
let body = Statement::from(inner.next().unwrap());
|
||||
|
||||
StatementBranch {
|
||||
condition,
|
||||
body: Box::new(body),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for ClassConstructor {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let visibility = Visibility::from(&mut inner);
|
||||
|
||||
let params = consume_rule(&mut inner, Rule::param_list)
|
||||
.map(ParamList::from)
|
||||
.unwrap_or_else(|| ParamList(Vec::new()));
|
||||
|
||||
Self {
|
||||
visibility,
|
||||
params,
|
||||
body: Block::from(inner.next().unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for TopLevelKind {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::import => TopLevelKind::Include(Path::from(inner.next().unwrap())),
|
||||
|
||||
Rule::function_decl => TopLevelKind::FunctionDecl(FunctionDecl::from(pair)),
|
||||
|
||||
Rule::struct_decl => {
|
||||
let visibility = Visibility::from(&mut inner);
|
||||
let name = inner.next().unwrap().as_str().to_string();
|
||||
let fields_pair = inner.next().unwrap();
|
||||
let fields = FieldList::from(fields_pair);
|
||||
|
||||
TopLevelKind::StructDecl {
|
||||
visibility,
|
||||
name,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
Rule::class_decl => TopLevelKind::ClassDecl {
|
||||
visibility: Visibility::from(&mut inner),
|
||||
name: inner.next().unwrap().as_str().to_string(),
|
||||
fields: inner
|
||||
.next()
|
||||
.unwrap()
|
||||
.into_inner()
|
||||
.map(VarDeclStmt::from)
|
||||
.collect(),
|
||||
constructor: ClassConstructor::from(inner.next().unwrap()),
|
||||
methods: inner.into_iter().map(FunctionDecl::from).collect(),
|
||||
},
|
||||
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Block {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
let statements = pair
|
||||
.into_inner()
|
||||
.flat_map(|pair| {
|
||||
if pair.as_rule() == Rule::statement_list {
|
||||
pair.into_inner().map(Statement::from).collect()
|
||||
} else {
|
||||
vec![Statement::from(pair)]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Block(statements)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Statement {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::statement => Statement::from(inner.next().unwrap()),
|
||||
|
||||
Rule::expr_stmt => Statement::Expression(Expression::from(inner.next().unwrap())),
|
||||
|
||||
Rule::block => Statement::Block(Block::from(inner.next().unwrap())),
|
||||
|
||||
Rule::var_decl_statement => Statement::VarDecl(VarDeclStmt::from(pair)),
|
||||
|
||||
Rule::return_stmt => {
|
||||
let expr = inner.next().map(Expression::from);
|
||||
|
||||
Statement::Return(expr)
|
||||
}
|
||||
|
||||
Rule::break_stmt => Statement::Break,
|
||||
|
||||
Rule::continue_stmt => Statement::Continue,
|
||||
|
||||
Rule::if_stmt => {
|
||||
let mut inner = inner.skip(2);
|
||||
|
||||
Statement::If {
|
||||
initial: pair.into(),
|
||||
else_if: inner
|
||||
.next()
|
||||
.unwrap()
|
||||
.into_inner()
|
||||
.map(StatementBranch::from)
|
||||
.collect(),
|
||||
else_branch: inner.next().map(Statement::from).map(Box::new),
|
||||
}
|
||||
}
|
||||
|
||||
Rule::while_stmt => Statement::While(pair.into()),
|
||||
|
||||
Rule::c_for_stmt => Statement::CStyleFor {
|
||||
init: Box::new(Statement::from(inner.next().unwrap())),
|
||||
condition: inner.next().unwrap().into(),
|
||||
update: Box::new(Statement::from(inner.next().unwrap())),
|
||||
body: Box::new(Statement::from(inner.next().unwrap())),
|
||||
},
|
||||
|
||||
Rule::for_stmt => Statement::For {
|
||||
pattern: inner.next().unwrap().as_str().to_string(),
|
||||
iterator: inner.next().unwrap().into(),
|
||||
body: Box::new(Statement::from(inner.next().unwrap())),
|
||||
},
|
||||
|
||||
Rule::assign_statement => Statement::VarAssign(VarAssignStmt {
|
||||
target: Expression::from(inner.next().unwrap()),
|
||||
value: Expression::from(inner.next().unwrap()),
|
||||
}),
|
||||
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Literal {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::primary => Self::from(inner.next().unwrap()),
|
||||
Rule::integer => Literal::Int(pair.as_str().parse::<i64>().unwrap()),
|
||||
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
|
||||
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
|
||||
Rule::string_lit => Literal::String(inner.as_str().to_string()),
|
||||
Rule::tuple => Literal::Tuple(inner.map(Expression::from).collect()),
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Expression {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::expr => {
|
||||
let prefixes: Vec<Prefix> = inner
|
||||
.next()
|
||||
.map(|p| p.into_inner().into_iter().map(Prefix::from).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let exp = Expression::from(inner.next().unwrap());
|
||||
|
||||
if inner.len() > 0 || prefixes.len() > 0 {
|
||||
Expression::Fix {
|
||||
initial: Box::new(exp),
|
||||
prefixes,
|
||||
postfixes: inner.map(|p| Postfix::from(p)).collect(),
|
||||
}
|
||||
} else {
|
||||
exp
|
||||
}
|
||||
}
|
||||
Rule::primary => Expression::from(inner.next().unwrap()),
|
||||
Rule::static_path => Expression::Path(Path::from(pair)),
|
||||
Rule::integer | Rule::float | Rule::boolean | Rule::string_lit | Rule::tuple => {
|
||||
Expression::Literal(Literal::from(pair))
|
||||
}
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Prefix {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
match pair.as_rule() {
|
||||
Rule::prefix => Self::from(pair.into_inner().next().unwrap()),
|
||||
Rule::deref_px => Self::Deref,
|
||||
Rule::mut_ref_px => Self::RefMut,
|
||||
Rule::ref_px => Self::Ref,
|
||||
Rule::new_px => Self::New,
|
||||
Rule::not_px => Self::Not,
|
||||
_ => unimplemented!("{pair:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for Postfix {
|
||||
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::postfix => Postfix::from(inner.next().unwrap()),
|
||||
|
||||
Rule::field_px => {
|
||||
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::struct_px => Postfix::StructCall(
|
||||
inner
|
||||
.map(|p| {
|
||||
let mut pi = p.into_inner();
|
||||
(
|
||||
pi.next().unwrap().as_str().to_string(),
|
||||
Expression::from(pi.next().unwrap()),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
|
||||
Rule::index_px => Postfix::Index(Expression::from(inner.next().unwrap())),
|
||||
|
||||
Rule::binary_px => {
|
||||
let op_pair = inner.next().unwrap();
|
||||
let op = match op_pair.as_str() {
|
||||
"+" => BinaryOp::Plus,
|
||||
"-" => BinaryOp::Minus,
|
||||
"*" => BinaryOp::Multiply,
|
||||
"/" => BinaryOp::Divide,
|
||||
"%" => BinaryOp::Modulo,
|
||||
"==" => BinaryOp::Equal,
|
||||
"!=" => BinaryOp::NotEqual,
|
||||
"<" => BinaryOp::LessThan,
|
||||
">" => BinaryOp::GreaterThan,
|
||||
"<=" => BinaryOp::LessThanOrEqual,
|
||||
">=" => BinaryOp::GreaterThanOrEqual,
|
||||
|
||||
_ => {
|
||||
unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str())
|
||||
}
|
||||
};
|
||||
Postfix::Binary(op, Expression::from(inner.next().unwrap()))
|
||||
}
|
||||
|
||||
Rule::macro_call_px => Postfix::MacroCall(inner.as_str().to_string()),
|
||||
#[macro_export]
|
||||
macro_rules! ast_expr {
|
||||
($($item:ident)::+ { $($k:ident: $v:expr),* $(,)? }) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
_ => unimplemented!("{rule:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
let v = $($item)::+ { $($k: analyzer.get($v).get()?),* };
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for VarDeclStmt {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl_statement => {
|
||||
let mut inner = pair.into_inner();
|
||||
analyzer.build(v)
|
||||
}};
|
||||
|
||||
let decl = VarDecl::from(inner.next().unwrap());
|
||||
($($item:ident)::+ ( $($v:expr),* $(,)? )) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
let init = inner.next().map(Expression::from);
|
||||
let v = $($item)::+ ( $(analyzer.get($v).get()?),* );
|
||||
|
||||
VarDeclStmt { decl, init }
|
||||
}
|
||||
analyzer.build(v)
|
||||
}};
|
||||
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for VarDecl {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let type_ = inner.next().and_then(|pair| {
|
||||
if pair.as_str().trim() == "var" {
|
||||
None
|
||||
} else {
|
||||
Some(TypeExpr::from(pair))
|
||||
}
|
||||
});
|
||||
let mutable = listen_rule(&mut inner, Rule::mutable);
|
||||
|
||||
let name = inner.next().unwrap().as_str().to_string();
|
||||
|
||||
VarDecl {
|
||||
mutable,
|
||||
name,
|
||||
type_,
|
||||
}
|
||||
}
|
||||
|
||||
_ => unimplemented!("{:?}", pair.as_rule()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pest::iterators::Pair<'_, Rule>> for FunctionDecl {
|
||||
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let visibility = Visibility::from(&mut inner);
|
||||
|
||||
let return_type = TypeExpr::from(inner.next().unwrap());
|
||||
|
||||
let name = inner.next().unwrap().as_str().to_string();
|
||||
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
|
||||
let mut param_inner = param.into_inner();
|
||||
let name = format!("self");
|
||||
|
||||
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
||||
|
||||
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
|
||||
|
||||
VarDecl {
|
||||
mutable: mutable && !is_ref,
|
||||
name,
|
||||
type_: Some(TypeExpr(
|
||||
TypeExprKind::Path(Path(vec![format!("Self")])),
|
||||
if is_ref {
|
||||
vec![if mutable {
|
||||
TypePostfix::RefMut
|
||||
} else {
|
||||
TypePostfix::Ref
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
)),
|
||||
}
|
||||
});
|
||||
|
||||
let params = consume_rule(&mut inner, Rule::param_list)
|
||||
.map({
|
||||
let self_param = self_param.clone();
|
||||
|params_pair| {
|
||||
let mut params = ParamList::from(params_pair);
|
||||
if let Some(x) = self_param {
|
||||
params.0.insert(0, x);
|
||||
}
|
||||
params
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| ParamList(self_param.into_iter().collect()));
|
||||
|
||||
let body = Block::from(inner.next().unwrap());
|
||||
|
||||
Self {
|
||||
visibility,
|
||||
name,
|
||||
params,
|
||||
return_type,
|
||||
body,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&mut pest::iterators::Pairs<'_, Rule>> for Visibility {
|
||||
fn from(pairs: &mut pest::iterators::Pairs<'_, Rule>) -> Self {
|
||||
if listen_rule(pairs, Rule::export) {
|
||||
Visibility::Public
|
||||
} else {
|
||||
Visibility::Private
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
|
||||
let consumed = pairs
|
||||
.peek()
|
||||
.map(|p| p.as_rule() == rule)
|
||||
.unwrap_or_default();
|
||||
|
||||
if consumed {
|
||||
pairs.next();
|
||||
}
|
||||
|
||||
consumed
|
||||
}
|
||||
|
||||
pub fn consume_rule<'a>(
|
||||
pairs: &mut pest::iterators::Pairs<'a, Rule>,
|
||||
rule: Rule,
|
||||
) -> Option<pest::iterators::Pair<'a, Rule>> {
|
||||
let consumed = pairs
|
||||
.peek()
|
||||
.map(|p| p.as_rule() == rule)
|
||||
.unwrap_or_default();
|
||||
|
||||
if consumed { pairs.next() } else { None }
|
||||
($($item:ident)::+) => {
|
||||
$($item)::+
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, AstResult, IntoErr},
|
||||
parser::listen_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl_statement => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(VarDeclStmt {
|
||||
decl: inner.next().unwrap().try_into(),
|
||||
init: inner.next().map(Expression::try_from).transpose()
|
||||
})
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::class_field => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(FieldDeclStmt {
|
||||
decl: inner.next().unwrap().try_into(),
|
||||
init: inner.next().map(Expression::try_from).transpose(),
|
||||
})
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let type_ = inner
|
||||
.next()
|
||||
.and_then(|pair| {
|
||||
if pair.as_str().trim() == "var" {
|
||||
None
|
||||
} else {
|
||||
Some(TypeExpr::try_from(pair))
|
||||
}
|
||||
})
|
||||
.transpose();
|
||||
|
||||
let mutable: AstResult<'_, bool> = Ok(listen_rule(&mut inner, Rule::mutable));
|
||||
|
||||
let name = Pattern::try_from(inner.next().unwrap());
|
||||
|
||||
ast_expr!(VarDecl {
|
||||
type_: type_,
|
||||
mutable: mutable,
|
||||
name: name,
|
||||
})
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::field => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(FieldDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
type_: TypeExpr::try_from(inner.next().unwrap()),
|
||||
name: Identifier::try_from(inner.next().unwrap()),
|
||||
})
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, GetLength, IntoErr, collect_recovered, collect_recovered_map},
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::expr => {
|
||||
let prefixes = inner
|
||||
.next()
|
||||
.map(|p| collect_recovered::<Prefix, Prefix>(p.into_inner()))
|
||||
.unwrap_or_else(|| Ok(Vec::new()));
|
||||
|
||||
let exp = Expression::try_from(inner.next().unwrap());
|
||||
|
||||
if inner.len() > 0 || prefixes.len() > 0 {
|
||||
ast_expr!(Expression::Fix {
|
||||
initial: exp.map(Box::new),
|
||||
prefixes: prefixes,
|
||||
postfixes: collect_recovered(inner),
|
||||
})
|
||||
} else {
|
||||
exp
|
||||
}
|
||||
}
|
||||
|
||||
Rule::primary => inner.next().unwrap().try_into(),
|
||||
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
|
||||
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
Ok(match pair.as_rule() {
|
||||
Rule::prefix => Self::try_from(pair.into_inner().next().unwrap())?,
|
||||
Rule::deref_px => Self::Deref,
|
||||
Rule::mut_ref_px => Self::RefMut,
|
||||
Rule::ref_px => Self::Ref,
|
||||
Rule::new_px => Self::New,
|
||||
Rule::not_px => Self::Not,
|
||||
|
||||
_ => return AstError::bug_unimplemented(pair),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
|
||||
|
||||
Rule::field_px => {
|
||||
ast_expr!(Postfix::FieldAccess(inner.next().unwrap().try_into()))
|
||||
}
|
||||
|
||||
Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
|
||||
|
||||
Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
|
||||
let mut pi = p.into_inner();
|
||||
Ok((
|
||||
Identifier::try_from(pi.next().unwrap())?,
|
||||
Expression::try_from(pi.next().unwrap()).get()?,
|
||||
))
|
||||
}))),
|
||||
|
||||
Rule::index_px => {
|
||||
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
|
||||
}
|
||||
|
||||
Rule::binary_px => {
|
||||
let op_pair = inner.next().unwrap();
|
||||
let op = match op_pair.as_str() {
|
||||
"+" => BinaryOp::Plus,
|
||||
"-" => BinaryOp::Minus,
|
||||
"*" => BinaryOp::Multiply,
|
||||
"/" => BinaryOp::Divide,
|
||||
"%" => BinaryOp::Modulo,
|
||||
"==" => BinaryOp::Equal,
|
||||
"!=" => BinaryOp::NotEqual,
|
||||
"<" => BinaryOp::LessThan,
|
||||
">" => BinaryOp::GreaterThan,
|
||||
"<=" => BinaryOp::LessThanOrEqual,
|
||||
">=" => BinaryOp::GreaterThanOrEqual,
|
||||
"&&" => BinaryOp::And,
|
||||
"||" => BinaryOp::Or,
|
||||
|
||||
_ => return AstError::bug_unimplemented(op_pair),
|
||||
};
|
||||
|
||||
Ok(Postfix::Binary(op, inner.next().unwrap().try_into().get()?))
|
||||
}
|
||||
|
||||
Rule::macro_call_px => Ok(Postfix::MacroCall(inner.as_str().to_string())),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
pub mod decl;
|
||||
pub mod expr;
|
||||
pub mod statement;
|
||||
pub mod types;
|
||||
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
ast_ensure!(pair, Rule::identifier => {
|
||||
Ok(Identifier(pair.as_str().to_string()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Path {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
Ok(match rule {
|
||||
Rule::primary => Self::try_from(inner.next().unwrap())?,
|
||||
Rule::literal => Self::try_from(inner.next().unwrap())?,
|
||||
Rule::integer => Literal::Int(pair.as_str().parse::<i64>().unwrap()),
|
||||
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
|
||||
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
|
||||
Rule::string_lit => Literal::String(inner.as_str().to_string()),
|
||||
Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
|
||||
_ => return AstError::bug_unimplemented(pair),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered(pair.into_inner()))),
|
||||
|
||||
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
collect_recovered(inner),
|
||||
)),
|
||||
|
||||
Rule::struct_pattern => ast_expr!(Pattern::Struct(
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
collect_recovered(inner),
|
||||
)),
|
||||
|
||||
Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
|
||||
|
||||
Rule::identifier => ast_expr!(Pattern::Id(pair.try_into())),
|
||||
|
||||
Rule::static_path => ast_expr!(Pattern::Path(pair.try_into())),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pairs: &mut pest::iterators::Pairs<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
Ok(consume_rule(pairs, Rule::visibility)
|
||||
.map(|pair| -> Result<Visibility, AstError<'a, Self>> {
|
||||
if let Some(path) = pair.into_inner().next() {
|
||||
ast_expr!(Visibility::PublicTarget(Path::try_from(path)))
|
||||
} else {
|
||||
Ok(Visibility::Public)
|
||||
}
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| Visibility::Private))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, AstResult, ErrorCode, IntoErr, collect_recovered},
|
||||
parser::listen_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
ast_ensure!(pair, Rule::block => {
|
||||
ast_expr!(Block(collect_recovered(pair.into_inner())))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::statement_branch => {
|
||||
ast_expr!(StatementBranch {
|
||||
condition: inner.next().unwrap().try_into(),
|
||||
body: inner.next().unwrap().try_into().map(Box::new),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::statement => Statement::try_from(inner.next().unwrap()),
|
||||
|
||||
Rule::expr_stmt => {
|
||||
ast_expr!(Statement::Expression(inner.next().unwrap().try_into()))
|
||||
}
|
||||
|
||||
Rule::block => ast_expr!(Statement::Block(pair.try_into())),
|
||||
|
||||
Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
|
||||
|
||||
Rule::return_stmt => {
|
||||
ast_expr!(Statement::Return(
|
||||
inner.next().map(Expression::try_from).transpose()
|
||||
))
|
||||
}
|
||||
|
||||
Rule::break_stmt => Ok(Statement::Break),
|
||||
|
||||
Rule::continue_stmt => Ok(Statement::Continue),
|
||||
|
||||
Rule::if_stmt => {
|
||||
ast_expr!(Statement::If {
|
||||
initial: inner.next().unwrap().try_into(),
|
||||
else_if: collect_recovered(inner.next().unwrap().into_inner()),
|
||||
else_branch: inner
|
||||
.next()
|
||||
.map(Statement::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.map(Box::new))
|
||||
.get_map(|v| { Some(Box::new(v)) }),
|
||||
})
|
||||
}
|
||||
|
||||
Rule::while_stmt => ast_expr!(Statement::While(inner.next().unwrap().try_into())),
|
||||
|
||||
Rule::c_for_stmt => ast_expr!(Statement::CStyleFor {
|
||||
init: inner.next().unwrap().try_into().map(Box::new),
|
||||
condition: inner.next().unwrap().try_into(),
|
||||
update: inner.next().unwrap().try_into().map(Box::new),
|
||||
body: inner.next().unwrap().try_into().map(Box::new),
|
||||
}),
|
||||
|
||||
Rule::for_stmt => ast_expr!(Statement::For {
|
||||
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
|
||||
pattern: inner.next().unwrap().try_into(),
|
||||
iterator: inner.next().unwrap().try_into(),
|
||||
body: inner.next().unwrap().try_into().map(Box::new),
|
||||
}),
|
||||
|
||||
Rule::assign_statement => ast_expr!(VarAssignStmt {
|
||||
target: inner.next().unwrap().try_into(),
|
||||
value: inner.next().unwrap().try_into(),
|
||||
})
|
||||
.map(Statement::VarAssign)
|
||||
.get_map(Statement::VarAssign),
|
||||
|
||||
Rule::match_stmt => ast_expr!(Statement::Match(
|
||||
inner.next().unwrap().try_into(),
|
||||
inner
|
||||
.map(|match_itms| {
|
||||
let mut match_inner = match_itms.into_inner();
|
||||
Ok((
|
||||
Pattern::try_from(match_inner.next().unwrap()).get()?,
|
||||
Block::try_from(match_inner.next().unwrap()).get()?,
|
||||
))
|
||||
})
|
||||
.collect::<AstResult<'a, Vec<_>>>(),
|
||||
)),
|
||||
|
||||
Rule::unexpected_statement => {
|
||||
return Err(AstError {
|
||||
span: pair.as_span(),
|
||||
error_code: ErrorCode::InvalidStatement,
|
||||
error_message: "Invalid Statement".to_string(),
|
||||
recovered: None,
|
||||
});
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, GetLength, IntoErr, collect_recovered},
|
||||
parser::{consume_rule, listen_rule},
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::ref_type => {
|
||||
let mutable = listen_rule(&mut inner, Rule::mutable);
|
||||
let lifetime = consume_rule(&mut inner, Rule::lifetime)
|
||||
.map(|pair| Identifier::try_from(pair.into_inner().next().unwrap()))
|
||||
.transpose()
|
||||
.get()?;
|
||||
|
||||
Ok(if mutable {
|
||||
if let Some(lifetime) = lifetime {
|
||||
TypePostfix::RefMutLifetime(lifetime)
|
||||
} else {
|
||||
TypePostfix::RefMut
|
||||
}
|
||||
} else {
|
||||
if let Some(lifetime) = lifetime {
|
||||
TypePostfix::RefLifetime(lifetime)
|
||||
} else {
|
||||
TypePostfix::Ref
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExprKind {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::tuple_type => ast_expr!(TypeExprKind::Tuple(collect_recovered(inner))),
|
||||
Rule::path_type => {
|
||||
let path = Path::try_from(inner.next().unwrap());
|
||||
let params = collect_recovered(inner);
|
||||
|
||||
if params.len() == 0 {
|
||||
ast_expr!(TypeExprKind::Path(path))
|
||||
} else {
|
||||
ast_expr!(TypeExprKind::PathParams(path, params))
|
||||
}
|
||||
}
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::type_expr => ast_expr!(TypeExpr(
|
||||
inner.next().unwrap().try_into(),
|
||||
collect_recovered(inner),
|
||||
)),
|
||||
Rule::type_expr_param => Self::try_from(inner.next().unwrap()),
|
||||
Rule::lifetime => ast_expr!(TypeExprKind::Lifetime(inner.next().unwrap().try_into()))
|
||||
.get_map(TypeExpr::no_px)
|
||||
.map(TypeExpr::no_px),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::generics => ast_expr!(Generics(collect_recovered(inner))),
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
||||
ast_expr!(Generic::Lifetime(
|
||||
pair.into_inner().next().unwrap().try_into(),
|
||||
))
|
||||
} else {
|
||||
ast_expr!(Generic::Type(
|
||||
inner.next().unwrap().try_into(),
|
||||
collect_recovered(inner),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::attribute => {
|
||||
// unwrap #[ ... ]
|
||||
Attribute::try_from(pair.into_inner().next().unwrap())
|
||||
}
|
||||
|
||||
Rule::meta => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
// first item is always the path
|
||||
let path = inner.next().unwrap().try_into().get()?;
|
||||
|
||||
// check what comes next
|
||||
match inner.next() {
|
||||
None => {
|
||||
// #[path]
|
||||
Ok(Attribute::Path(path))
|
||||
}
|
||||
|
||||
Some(next) => match next.as_rule() {
|
||||
Rule::primary => {
|
||||
// #[path = literal]
|
||||
Ok(Attribute::NameValue {
|
||||
path,
|
||||
value: inner.next().unwrap().try_into().get()?,
|
||||
})
|
||||
}
|
||||
|
||||
Rule::meta_list => {
|
||||
// #[path(...)]
|
||||
Ok(Attribute::List {
|
||||
path,
|
||||
items: collect_recovered(next.into_inner()).get()?,
|
||||
})
|
||||
}
|
||||
|
||||
_ => unreachable!("unexpected rule in meta: {:?}", next.as_rule()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Rule::meta_list => {
|
||||
// This case usually won't be hit directly,
|
||||
// but it's nice to keep it safe if reused
|
||||
let items = pair
|
||||
.into_inner()
|
||||
.map(Attribute::try_from)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// NOTE: this shouldn't normally construct an Attribute alone
|
||||
// but you can panic or wrap depending on your design
|
||||
panic!("meta_list should be handled inside meta: {:?}", items);
|
||||
}
|
||||
|
||||
_ => unreachable!("unexpected rule: {:?}", pair.as_rule()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassConstructor {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
Ok(Self {
|
||||
visibility: Visibility::try_from(&mut inner).get()?,
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.unwrap_or_default(),
|
||||
|
||||
params: consume_rule(&mut inner, Rule::param_list)
|
||||
.map(ParamList::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.unwrap_or_default(),
|
||||
|
||||
body: inner.next().unwrap().try_into().get()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
|
||||
match rule {
|
||||
Rule::impl_decl | Rule::impl_for_decl => {
|
||||
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
|
||||
}
|
||||
|
||||
Rule::method => Ok(ClassItem::Method(pair.try_into().get()?)),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into().get()?)),
|
||||
|
||||
Rule::enum_tuple => Ok(EnumItem::Tuple(
|
||||
inner.next().unwrap().try_into().get()?,
|
||||
collect_recovered(inner.next().unwrap().into_inner()).get()?,
|
||||
)),
|
||||
|
||||
Rule::enum_struct => Ok(EnumItem::Struct(
|
||||
inner.next().unwrap().try_into().get()?,
|
||||
inner
|
||||
.next()
|
||||
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
|
||||
.transpose()
|
||||
.get()?
|
||||
.unwrap_or_default(),
|
||||
)),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, AstResult, IntoErr, collect_recovered},
|
||||
parser::{consume_rule, listen_rule},
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.into_inner();
|
||||
let visibility = Visibility::try_from(&mut inner);
|
||||
let return_type = TypeExpr::try_from(inner.next().unwrap());
|
||||
let name = Identifier::try_from(inner.next().unwrap());
|
||||
|
||||
let generics = consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default());
|
||||
|
||||
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
|
||||
let mut param_inner = param.into_inner();
|
||||
let name = Pattern::Id(Identifier(String::from("self")));
|
||||
|
||||
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
||||
|
||||
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
|
||||
|
||||
VarDecl {
|
||||
mutable: mutable && !is_ref,
|
||||
name: name.clone(),
|
||||
type_: Some(TypeExpr(
|
||||
TypeExprKind::Path(Path(vec![Identifier("Self".to_string())])),
|
||||
if is_ref {
|
||||
vec![if mutable {
|
||||
TypePostfix::RefMut
|
||||
} else {
|
||||
TypePostfix::Ref
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
)),
|
||||
}
|
||||
});
|
||||
|
||||
let params = consume_rule(&mut inner, Rule::param_list)
|
||||
.map({
|
||||
let self_param = self_param.clone();
|
||||
|params_pair| -> AstResult<'a, ParamList> {
|
||||
let mut params = ParamList::try_from(params_pair)?;
|
||||
if let Some(x) = self_param {
|
||||
params.0.insert(0, x);
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
|
||||
|
||||
let body = inner.next().map(Block::try_from).transpose();
|
||||
|
||||
ast_expr!(Self {
|
||||
visibility: visibility,
|
||||
return_type: return_type,
|
||||
name: name,
|
||||
generics: generics,
|
||||
params: params,
|
||||
body: body,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::impl_for_decl => Ok(ImplDecl {
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.unwrap_or_default(),
|
||||
trait_: Some(inner.next().unwrap().try_into().get()?),
|
||||
target: inner.next().unwrap().try_into().get()?,
|
||||
methods: collect_recovered(inner).get()?,
|
||||
}),
|
||||
|
||||
Rule::impl_decl => Ok(ImplDecl {
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.unwrap_or_default(),
|
||||
trait_: None,
|
||||
target: inner.next().unwrap().try_into().get()?,
|
||||
methods: collect_recovered(inner).get()?,
|
||||
}),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
pub mod attribute;
|
||||
pub mod class;
|
||||
pub mod enums;
|
||||
pub mod function;
|
||||
pub mod impl_decl;
|
||||
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
let attributes = collect_recovered(inner.next().unwrap().into_inner());
|
||||
|
||||
ast_expr!(TopLevel(
|
||||
inner
|
||||
.next()
|
||||
.map(TopLevelKind::try_from)
|
||||
.unwrap_or(Ok(TopLevelKind::ModAttribute)),
|
||||
attributes,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::import => ast_expr!(TopLevelKind::Import(
|
||||
Visibility::try_from(&mut inner),
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
)),
|
||||
|
||||
Rule::function_decl => ast_expr!(TopLevelKind::FunctionDecl(pair.try_into())),
|
||||
|
||||
Rule::struct_decl => ast_expr!(TopLevelKind::StructDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
|
||||
name: inner.next().unwrap().try_into(),
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
|
||||
fields: inner
|
||||
.next()
|
||||
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
}),
|
||||
|
||||
Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
|
||||
name: inner.next().unwrap().try_into(),
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
|
||||
fields: collect_recovered(inner.next().unwrap().into_inner()),
|
||||
|
||||
constructor: inner.next().unwrap().try_into(),
|
||||
|
||||
items: collect_recovered(inner),
|
||||
}),
|
||||
|
||||
Rule::enum_decl => ast_expr!(TopLevelKind::EnumDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
|
||||
name: inner.next().unwrap().try_into(),
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
|
||||
fields: collect_recovered(inner),
|
||||
}),
|
||||
|
||||
Rule::mod_package => ast_expr!(TopLevelKind::Mod(
|
||||
Visibility::try_from(&mut inner),
|
||||
inner.next().unwrap().try_into(),
|
||||
)),
|
||||
|
||||
Rule::impl_for_decl | Rule::impl_decl => {
|
||||
ast_expr!(TopLevelKind::ImplDecl(pair.try_into()))
|
||||
}
|
||||
|
||||
Rule::trait_decl => ast_expr!(TopLevelKind::TraitDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
|
||||
name: inner.next().unwrap().try_into(),
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics)
|
||||
.map(Generics::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
|
||||
requirements: consume_rule(&mut inner, Rule::trait_requirements)
|
||||
.map(|pair| collect_recovered::<TypeExpr, TypeExpr>(pair.into_inner()))
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
|
||||
items: collect_recovered(inner),
|
||||
}),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
pub mod common;
|
||||
pub mod items;
|
||||
|
||||
use crate::Rule;
|
||||
|
||||
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
|
||||
let consumed = pairs
|
||||
.peek()
|
||||
.map(|p| p.as_rule() == rule)
|
||||
.unwrap_or_default();
|
||||
|
||||
if consumed {
|
||||
pairs.next();
|
||||
}
|
||||
|
||||
consumed
|
||||
}
|
||||
|
||||
pub fn consume_rule<'a>(
|
||||
pairs: &mut pest::iterators::Pairs<'a, Rule>,
|
||||
rule: Rule,
|
||||
) -> Option<pest::iterators::Pair<'a, Rule>> {
|
||||
let consumed = pairs
|
||||
.peek()
|
||||
.map(|p| p.as_rule() == rule)
|
||||
.unwrap_or_default();
|
||||
|
||||
if consumed { pairs.next() } else { None }
|
||||
}
|
||||
+322
-34
@@ -1,7 +1,8 @@
|
||||
use parser::ast::{
|
||||
Attribute, BinaryOp, Block, Expression, FunctionDecl, Literal, Path, Postfix, Prefix,
|
||||
Statement, StatementBranch, TopLevel, TopLevelKind, TypeExpr, TypeExprKind, TypePostfix,
|
||||
VarAssignStmt, VarDecl, VarDeclStmt, Visibility,
|
||||
use mist_parser::ast::{
|
||||
Attribute, BinaryOp, Block, ClassItem, EnumItem, Expression, FieldDecl, FunctionDecl, Generic,
|
||||
Generics, Identifier, ImplDecl, Literal, Path, Pattern, Postfix, Prefix, Statement,
|
||||
StatementBranch, TopLevel, TopLevelKind, TypeExpr, TypeExprKind, TypePostfix, VarAssignStmt,
|
||||
VarDecl, VarDeclStmt, Visibility,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -96,6 +97,7 @@ impl GetRust for TypeExprKind {
|
||||
fn get_rust(&self) -> String {
|
||||
match self {
|
||||
TypeExprKind::Path(path) => get_static_type_path(path),
|
||||
TypeExprKind::Lifetime(name) => format!("'{}", name.get_rust()),
|
||||
TypeExprKind::PathParams(path, params) => {
|
||||
format!(
|
||||
"{}<{}>",
|
||||
@@ -197,7 +199,7 @@ impl GetRust for Option<&Vec<Prefix>> {
|
||||
impl GetRust for Postfix {
|
||||
fn get_rust(&self) -> String {
|
||||
match self {
|
||||
Postfix::FieldAccess(field) => format!(".{}", field),
|
||||
Postfix::FieldAccess(field) => format!(".{}", field.get_rust()),
|
||||
|
||||
Postfix::Call(args) => {
|
||||
let args = args
|
||||
@@ -215,7 +217,7 @@ impl GetRust for Postfix {
|
||||
Postfix::StructCall(fields) => {
|
||||
let fields = fields
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}: {}", k, v.get_rust()))
|
||||
.map(|(k, v)| format!("{}: {}", k.get_rust(), v.get_rust()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("{{ {} }}", fields)
|
||||
@@ -238,6 +240,8 @@ impl GetRust for Postfix {
|
||||
BinaryOp::GreaterThan => ">",
|
||||
BinaryOp::LessThanOrEqual => "<=",
|
||||
BinaryOp::GreaterThanOrEqual => ">=",
|
||||
BinaryOp::And => "&&",
|
||||
BinaryOp::Or => "||",
|
||||
};
|
||||
format!(" {} {}", op_str, rhs.get_rust())
|
||||
}
|
||||
@@ -308,21 +312,81 @@ impl ToRust for TopLevelKind {
|
||||
fn to_rust(&self, cg: &mut RustCodegen) {
|
||||
match self {
|
||||
Self::ModAttribute => {}
|
||||
Self::Include(path) => {
|
||||
cg.addln(&format!("use {};", path.get_rust()));
|
||||
Self::Import(vis, path) => {
|
||||
cg.addln(&format!("{} use {};", vis.get_rust(), path.get_rust()))
|
||||
}
|
||||
Self::Mod(vis, id) => cg.addln(&format!("{} mod {};", vis.get_rust(), id.get_rust())),
|
||||
Self::FunctionDecl(decl) => decl.to_rust(cg),
|
||||
Self::ImplDecl(impl_) => impl_.to_rust(cg),
|
||||
Self::StructDecl {
|
||||
visibility,
|
||||
name,
|
||||
generics,
|
||||
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;
|
||||
|
||||
for (field_name, _, ty) in &fields.0 {
|
||||
let ty = ty.get_rust();
|
||||
cg.add_indentedln(&format!("pub {}: {},", field_name, ty));
|
||||
for field in fields {
|
||||
cg.add_indentedln(&field.get_rust());
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -331,24 +395,42 @@ impl ToRust for TopLevelKind {
|
||||
Self::ClassDecl {
|
||||
visibility,
|
||||
name,
|
||||
generics,
|
||||
fields,
|
||||
constructor,
|
||||
methods,
|
||||
items,
|
||||
} => {
|
||||
// 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;
|
||||
|
||||
for field in fields {
|
||||
let ty = field.decl.type_.clone().unwrap().get_rust();
|
||||
cg.add_indentedln(&format!("pub {}: {},", field.decl.name, ty));
|
||||
cg.add_indentedln(&field.decl.get_rust());
|
||||
}
|
||||
|
||||
cg.indent -= 1;
|
||||
cg.addln("}\n");
|
||||
|
||||
// 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;
|
||||
|
||||
let params_str = constructor
|
||||
@@ -359,9 +441,11 @@ impl ToRust for TopLevelKind {
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
cg.add_indentedln("#[allow(invalid_value)]");
|
||||
cg.add_indentedln(&format!(
|
||||
"{}fn new({}) -> Self {{",
|
||||
"{}fn new{}({}) -> Self {{",
|
||||
constructor.visibility.get_rust(),
|
||||
constructor.generics.get_rust(),
|
||||
params_str
|
||||
));
|
||||
cg.indent += 1;
|
||||
@@ -372,7 +456,7 @@ impl ToRust for TopLevelKind {
|
||||
if let Some(init) = &field.init {
|
||||
cg.add_indentedln(&format!(
|
||||
"this.{} = {};",
|
||||
field.decl.name,
|
||||
field.decl.name.get_rust(),
|
||||
init.get_rust()
|
||||
));
|
||||
}
|
||||
@@ -384,7 +468,7 @@ impl ToRust for TopLevelKind {
|
||||
.params
|
||||
.0
|
||||
.iter()
|
||||
.map(|e| e.name.to_string())
|
||||
.map(|e| e.name.get_rust())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
));
|
||||
@@ -396,8 +480,9 @@ impl ToRust for TopLevelKind {
|
||||
|
||||
// Constructor function
|
||||
cg.add_indentedln(&format!(
|
||||
"{}fn construct_class(&mut self, {}) {{",
|
||||
"{}fn construct_class{}(&mut self, {}) {{",
|
||||
constructor.visibility.get_rust(),
|
||||
constructor.generics.get_rust(),
|
||||
params_str
|
||||
));
|
||||
cg.indent += 1;
|
||||
@@ -407,12 +492,30 @@ impl ToRust for TopLevelKind {
|
||||
cg.indent -= 1;
|
||||
cg.add_indentedln("}\n");
|
||||
|
||||
for method in methods {
|
||||
method.to_rust(cg);
|
||||
for item in items {
|
||||
match item {
|
||||
ClassItem::ImplDecl(_) => {}
|
||||
ClassItem::Method(method) => method.to_rust(cg),
|
||||
}
|
||||
}
|
||||
|
||||
cg.indent -= 1;
|
||||
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 +549,23 @@ impl ToRust for Statement {
|
||||
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 {
|
||||
initial,
|
||||
else_if,
|
||||
@@ -498,11 +618,17 @@ impl ToRust for Statement {
|
||||
}
|
||||
|
||||
Statement::For {
|
||||
mutable,
|
||||
pattern,
|
||||
iterator,
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -528,36 +654,76 @@ impl ToRust for FunctionDecl {
|
||||
.join(", ");
|
||||
|
||||
cg.add_indentedln(&format!(
|
||||
"{}fn {}({}) -> {} {{",
|
||||
"{}fn {}{}({}) -> {}",
|
||||
self.visibility.get_rust(),
|
||||
self.name,
|
||||
self.name.get_rust(),
|
||||
self.generics.get_rust(),
|
||||
params_str,
|
||||
self.return_type.get_rust()
|
||||
));
|
||||
if let Some(body) = &self.body {
|
||||
cg.add_indentedln("{\n");
|
||||
cg.indent += 1;
|
||||
self.body.to_rust(cg);
|
||||
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;
|
||||
|
||||
for method in &self.methods {
|
||||
method.to_rust(cg);
|
||||
}
|
||||
|
||||
cg.indent -= 1;
|
||||
cg.add_indentedln("}");
|
||||
}
|
||||
}
|
||||
|
||||
impl GetRust for VarDecl {
|
||||
fn get_rust(&self) -> String {
|
||||
let mutability = if self.mutable { "mut " } else { "" };
|
||||
|
||||
let ty = self
|
||||
.type_
|
||||
.as_ref()
|
||||
.map(|t| format!(": {}", t.get_rust()))
|
||||
.unwrap_or_default();
|
||||
|
||||
format!("{}{}{}", mutability, self.name, ty)
|
||||
format!(
|
||||
"{}{}{}",
|
||||
get_mutable(self.mutable),
|
||||
self.name.get_rust(),
|
||||
ty
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl GetRust for Path {
|
||||
fn get_rust(&self) -> String {
|
||||
self.0.join("::")
|
||||
self.0
|
||||
.iter()
|
||||
.map(Identifier::get_rust)
|
||||
.collect::<Vec<String>>()
|
||||
.join("::")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,6 +732,8 @@ impl GetRust for TypePostfix {
|
||||
match self {
|
||||
TypePostfix::Ref => format!("&"),
|
||||
TypePostfix::RefMut => format!("&mut "),
|
||||
TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
|
||||
TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -573,10 +741,126 @@ impl GetRust for TypePostfix {
|
||||
impl GetRust for Visibility {
|
||||
fn get_rust(&self) -> String {
|
||||
match self {
|
||||
Visibility::Public => "pub ",
|
||||
Visibility::Private => "",
|
||||
Visibility::Public => "pub ".to_string(),
|
||||
Visibility::PublicTarget(path) => format!("pub({}) ", path.get_rust()),
|
||||
Visibility::Private => "".to_string(),
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,3 +877,7 @@ pub fn get_static_type_path(path: &Path) -> String {
|
||||
pub fn get_type_postfixes(postfixes: &[TypePostfix]) -> String {
|
||||
postfixes.iter().map(TypePostfix::get_rust).collect()
|
||||
}
|
||||
|
||||
pub fn get_mutable(mutable: bool) -> String {
|
||||
if mutable { "mut " } else { "" }.to_string()
|
||||
}
|
||||
|
||||
+121
-48
@@ -1,5 +1,11 @@
|
||||
use std::{fs, path::PathBuf, process, time::Instant};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use mist_parser::error::ParseError;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -21,58 +27,126 @@ pub fn build() {
|
||||
// 2. load config
|
||||
let config = load_config(&root);
|
||||
|
||||
let src = root.join(&config.src);
|
||||
|
||||
for entry in fs::read_dir(src).unwrap() {
|
||||
if let Ok(entry) = entry {
|
||||
let entry_path = root.join(&entry.path());
|
||||
let src_dir = root.join(&config.src);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
build_dir(&root, &src_dir, &src_dir, &out_dir);
|
||||
|
||||
let elapsed = start.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| match e {
|
||||
ParseError::Ast(e) => {
|
||||
let start_pos = e.span.start_pos().line_col();
|
||||
|
||||
let span = e.span.as_str();
|
||||
|
||||
format!(
|
||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
||||
path.as_os_str().display(),
|
||||
start_pos.0,
|
||||
start_pos.1,
|
||||
e.error_message,
|
||||
span,
|
||||
if span.ends_with("\n") { "" } else { "\n" },
|
||||
"^".repeat(span.trim().len()),
|
||||
)
|
||||
}
|
||||
ParseError::PreAst(e) => format!("{e}"),
|
||||
});
|
||||
|
||||
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> {
|
||||
let mut dir = std::env::current_dir().ok()?;
|
||||
|
||||
@@ -87,9 +161,8 @@ pub fn find_project_root() -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_config(root: &std::path::Path) -> Config {
|
||||
let content =
|
||||
std::fs::read_to_string(root.join("mist.json")).expect("failed to read mist.json");
|
||||
fn load_config(root: &Path) -> Config {
|
||||
let content = fs::read_to_string(root.join("mist.json")).expect("failed to read mist.json");
|
||||
|
||||
serde_json::from_str(&content).expect("invalid mist.json format")
|
||||
}
|
||||
|
||||
+16
-12
@@ -1,4 +1,4 @@
|
||||
use std::process;
|
||||
use std::process::{self, Command};
|
||||
|
||||
pub mod codegen;
|
||||
pub mod compiler;
|
||||
@@ -12,13 +12,11 @@ fn main() {
|
||||
}
|
||||
|
||||
match args[1].as_str() {
|
||||
"build" => {
|
||||
if args.len() < 2 {
|
||||
eprintln!("error: expected a file path\n usage: mist build");
|
||||
process::exit(1);
|
||||
}
|
||||
"run" | "build" | "r" | "b" => {
|
||||
compiler::build();
|
||||
Command::new("cargo").args(&args[1..]).status().unwrap();
|
||||
}
|
||||
"transpile" | "t" => compiler::build(),
|
||||
"version" | "--version" | "-v" => {
|
||||
println!("mist {}", env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
@@ -34,11 +32,17 @@ fn main() {
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
println!("mist - the mist compiler");
|
||||
println!();
|
||||
println!("Mist - the mist compiler\n");
|
||||
println!(" View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
|
||||
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
|
||||
println!("usage:");
|
||||
println!(" mist build compile the project in the current directory");
|
||||
println!(" mist check <file.ms> parse and validate without compiling");
|
||||
println!(" mist version print the compiler version");
|
||||
println!(" mist help print this message");
|
||||
println!(" \x1b[36m mist run\x1b[0m run the project in the current directory\n");
|
||||
println!(
|
||||
" \x1b[36m mist build\x1b[0m build the project in the current directory\n"
|
||||
);
|
||||
println!(
|
||||
" \x1b[36m mist transpile\x1b[0m transpile the project in the current directory\n"
|
||||
);
|
||||
println!(" \x1b[36m mist version \x1b[0m print the compiler version\n");
|
||||
println!(" \x1b[36m mist help\x1b[0m print this message\n");
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user