Compare commits
140
Commits
0.3.5-alpha.0
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
352d0594b2 | ||
|
|
48ca58725a | ||
|
|
708b956750 | ||
|
|
df9e31e26d | ||
|
|
c716b6352c | ||
|
|
6f675b4253 | ||
|
|
5079b10819 | ||
|
|
d834ff595d | ||
|
|
70ec348f4d | ||
|
|
93ba0e97da | ||
|
|
9c0aa3d182 | ||
|
|
e1b851911d | ||
|
|
72f7b8430d | ||
|
|
0100abfa53 | ||
|
|
01b7e816ee | ||
|
|
ac94882e5a | ||
|
|
9220ee3b29 | ||
|
|
b15f13880a | ||
|
|
d538168692 | ||
|
|
b68e4245d4 | ||
|
|
c5354ff424 | ||
|
|
be68f93038 | ||
|
|
e3c9657b07 | ||
|
|
2aab50d36d | ||
|
|
e75b707981 | ||
|
|
18a13dd170 | ||
|
|
aacc08b983 | ||
|
|
df8e67fd4f | ||
|
|
08771fe5be | ||
|
|
0d2199ee3a | ||
|
|
442d1e66a8 | ||
|
|
8198b8d5cb | ||
|
|
44ac3c365d | ||
|
|
c564fc3e90 | ||
|
|
bb006c1ba2 | ||
|
|
4b69bbaed0 | ||
|
|
f574d6e8af | ||
|
|
13664413c5 | ||
|
|
b6256283a6 | ||
|
|
f30613f094 | ||
|
|
a1fd169568 | ||
|
|
3c5f13f3f6 | ||
|
|
f4f92c57ee | ||
|
|
df34c72c97 | ||
|
|
517a2e5a2b | ||
|
|
eeac773c06 | ||
|
|
4f3966d8d8 | ||
|
|
409301b3d6 | ||
|
|
223bafaad7 | ||
|
|
603ce1eb1e | ||
|
|
b02439edfc | ||
|
|
0449789159 | ||
|
|
2738f57bd9 | ||
|
|
f3046e3442 | ||
|
|
28e9fb664c | ||
|
|
3a8537682e | ||
|
|
eb23ff1e5a | ||
|
|
b8394bba52 | ||
|
|
ff861095e3 | ||
|
|
744adeb068 | ||
|
|
113ae54e6e | ||
|
|
c7bf4f7131 | ||
|
|
579d229cad | ||
|
|
d62d884add | ||
|
|
5346cd05be | ||
|
|
493c668495 | ||
|
|
4579c656b9 | ||
|
|
68cf239f92 | ||
|
|
9021da224e | ||
|
|
d0a72b49f0 | ||
|
|
a5dad690bf | ||
|
|
e9b7312362 | ||
|
|
6e67fd852b | ||
|
|
67acef8270 | ||
|
|
a3da192b9a | ||
|
|
310ff6b53c | ||
|
|
4e1bcf36fc | ||
|
|
c1d7152992 | ||
|
|
bd938ec3e7 | ||
|
|
bfaa9eeea5 | ||
|
|
3ff4c2ab08 | ||
|
|
3d30e0a092 | ||
|
|
502bde1536 | ||
|
|
d8fd8cf999 | ||
|
|
3ce8fe5278 | ||
|
|
2426e585d6 | ||
|
|
2174b99a3f | ||
|
|
31eebb4baa | ||
|
|
41f8b94c82 | ||
|
|
64081bc494 | ||
|
|
3c6ebb66c6 | ||
|
|
a867dbc797 | ||
|
|
a2fc8a4922 | ||
|
|
dbfcaa9b0d | ||
|
|
76541040c9 | ||
|
|
3ddb1bc601 | ||
|
|
bf5d243036 | ||
|
|
b6b5214684 | ||
|
|
a37dffb94b | ||
|
|
84c75c290f | ||
|
|
46e9783257 | ||
|
|
9b7de09b0a | ||
|
|
6c9c0e03d2 | ||
|
|
e5509e89a4 | ||
|
|
fda193b8ff | ||
|
|
c78c9985f4 | ||
|
|
d0341deef9 | ||
|
|
26c0fb34e0 | ||
|
|
75dd2e4af2 | ||
|
|
c47beae67d | ||
|
|
c6c33bf83b | ||
|
|
065dc575a5 | ||
|
|
a1a3ce1a29 | ||
|
|
a63199a41d | ||
|
|
33430f9541 | ||
|
|
2549535e4b | ||
|
|
243b4ba5d0 | ||
|
|
4ab7827955 | ||
|
|
2c11131e1a | ||
|
|
93e7a0fdef | ||
|
|
0dd9e2fb37 | ||
|
|
ae60aee85c | ||
|
|
6cc46751f9 | ||
|
|
2ef2232b84 | ||
|
|
0cbfa10281 | ||
|
|
9ce6d44eb4 | ||
|
|
1f2e989522 | ||
|
|
ca11866328 | ||
|
|
055d50edd5 | ||
|
|
c8d7f05e67 | ||
|
|
9b1519b068 | ||
|
|
dc8acdc2bd | ||
|
|
97de75252d | ||
|
|
2f12f5ac53 | ||
|
|
e4b7b4abf9 | ||
|
|
208e4dac6b | ||
|
|
b73396afb7 | ||
|
|
7f7c1e2000 | ||
|
|
2f6303ba30 | ||
|
|
2ae4ca510d |
@@ -29,3 +29,6 @@ target
|
|||||||
**/build
|
**/build
|
||||||
|
|
||||||
.mist/
|
.mist/
|
||||||
|
|
||||||
|
analyzer.bat
|
||||||
|
analyzer.sh
|
||||||
|
|||||||
Generated
+15
-5
@@ -292,6 +292,12 @@ version = "0.17.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "httparse"
|
name = "httparse"
|
||||||
version = "1.10.1"
|
version = "1.10.1"
|
||||||
@@ -470,10 +476,12 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-analyzer"
|
name = "mist-analyzer"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cargo_metadata",
|
"cargo_metadata",
|
||||||
"dashmap 6.1.0",
|
"dashmap 6.1.0",
|
||||||
|
"heck",
|
||||||
|
"mist-api",
|
||||||
"mist-codegen",
|
"mist-codegen",
|
||||||
"mist-parser",
|
"mist-parser",
|
||||||
"pest",
|
"pest",
|
||||||
@@ -481,12 +489,13 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"toml",
|
||||||
"tower-lsp",
|
"tower-lsp",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-api"
|
name = "mist-api"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cargo_metadata",
|
"cargo_metadata",
|
||||||
"mist-codegen",
|
"mist-codegen",
|
||||||
@@ -498,7 +507,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-codegen"
|
name = "mist-codegen"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytecount",
|
"bytecount",
|
||||||
"mist-parser",
|
"mist-parser",
|
||||||
@@ -506,15 +515,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-lang"
|
name = "mist-lang"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"mist-analyzer",
|
"mist-analyzer",
|
||||||
"mist-api",
|
"mist-api",
|
||||||
|
"toml",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mist-parser"
|
name = "mist-parser"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"pest",
|
"pest",
|
||||||
"pest_derive",
|
"pest_derive",
|
||||||
|
|||||||
+6
-5
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-lang"
|
name = "mist-lang"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language compiler"
|
description = "The Mist programming language compiler"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -18,6 +18,7 @@ include = [
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
mist-analyzer = { workspace = true }
|
mist-analyzer = { workspace = true }
|
||||||
mist-api = { workspace = true }
|
mist-api = { workspace = true }
|
||||||
|
toml = "1.1.2"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
@@ -32,10 +33,10 @@ exclude = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
mist-parser = { path = "crates/parser", version = "0.3.5-alpha.0" }
|
mist-parser = { path = "crates/parser", version = "0.4.0" }
|
||||||
mist-analyzer = { path = "crates/analyzer", version = "0.3.5-alpha.0" }
|
mist-analyzer = { path = "crates/analyzer", version = "0.4.0" }
|
||||||
mist-codegen = { path = "crates/codegen", version = "0.3.5-alpha.0" }
|
mist-codegen = { path = "crates/codegen", version = "0.4.0" }
|
||||||
mist-api = { path = "crates/mist-api", version = "0.3.5-alpha.0" }
|
mist-api = { path = "crates/mist-api", version = "0.4.0" }
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mist"
|
name = "mist"
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
package = "main.mist"
|
package = "main.mist"
|
||||||
packages = []
|
packages = []
|
||||||
|
include = ["crates/*"]
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Originally this readme was part of the Carbon Language project, licensed with Ap
|
|||||||
-->
|
-->
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://mist.selimaj.dev">Documentation</a>
|
<a href="https://mist.selimaj.dev/docs">Documentation</a> ∙ <a href="https://mist.selimaj.dev/blog">Blog</a> ∙ <a href="https://mist.selimaj.dev/faq">FAQ</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ The `div` reduces the vertical height. The `picture` prevents autolinking.
|
|||||||
|
|
||||||
**Fast and works with Rust**
|
**Fast and works with Rust**
|
||||||
|
|
||||||
- All of your favourite Rust libraries work with Mist
|
- All of your favorite Rust libraries work with Mist
|
||||||
- Compiles directly into efficient Rust code
|
- Compiles directly into efficient Rust code
|
||||||
- Zero-cost abstractions, no runtime overhead
|
- Zero-cost abstractions, no runtime overhead
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
@echo off
|
|
||||||
|
|
||||||
cd D:\projects\mist\mist
|
|
||||||
|
|
||||||
mist build >nul 2>&1
|
|
||||||
|
|
||||||
cd mist-test
|
|
||||||
|
|
||||||
D:\projects\mist\mist\target\debug\mist-analyzer.exe
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 55 KiB |
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-analyzer"
|
name = "mist-analyzer"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language Analyzer LSP"
|
description = "The Mist programming language Analyzer LSP"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -9,6 +9,7 @@ keywords = ["language-server", "language", "mist"]
|
|||||||
categories = ["compilers"]
|
categories = ["compilers"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
mist-api = { workspace = true }
|
||||||
mist-parser = { workspace = true }
|
mist-parser = { workspace = true }
|
||||||
mist-codegen = { workspace = true }
|
mist-codegen = { workspace = true }
|
||||||
pest = "2.8.6"
|
pest = "2.8.6"
|
||||||
@@ -21,3 +22,5 @@ cargo_metadata = "0.23.1"
|
|||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
ropey = "1"
|
ropey = "1"
|
||||||
|
heck = "0.5.0"
|
||||||
|
toml = "1.1.2"
|
||||||
|
|||||||
+1115
-189
File diff suppressed because it is too large
Load Diff
@@ -103,7 +103,8 @@ impl RustAnalyzer {
|
|||||||
pub fn new(
|
pub fn new(
|
||||||
notification_tx: tokio::sync::mpsc::UnboundedSender<Value>,
|
notification_tx: tokio::sync::mpsc::UnboundedSender<Value>,
|
||||||
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let mut child = tokio::process::Command::new("rust-analyzer")
|
let mut child = tokio::process::Command::new("rustup")
|
||||||
|
.args(["run", "stable", "rust-analyzer"])
|
||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
@@ -129,7 +130,10 @@ impl RustAnalyzer {
|
|||||||
match stderr.read(&mut buf).await {
|
match stderr.read(&mut buf).await {
|
||||||
Ok(0) => break,
|
Ok(0) => break,
|
||||||
Ok(n) => {
|
Ok(n) => {
|
||||||
eprintln!("[ra-stderr] {}", String::from_utf8_lossy(&buf[..n]).trim_end());
|
eprintln!(
|
||||||
|
"[ra-stderr] {}",
|
||||||
|
String::from_utf8_lossy(&buf[..n]).trim_end()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("[ra-stderr] read error: {e}");
|
eprintln!("[ra-stderr] read error: {e}");
|
||||||
@@ -323,10 +327,7 @@ impl RustAnalyzer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
self.notify(
|
self.notify(<Initialized as Notification>::METHOD, InitializedParams {})
|
||||||
<Initialized as Notification>::METHOD,
|
|
||||||
InitializedParams {},
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -373,6 +374,23 @@ impl RustAnalyzer {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn did_save(
|
||||||
|
&mut self,
|
||||||
|
uri: Url,
|
||||||
|
text: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didSave",
|
||||||
|
json!({
|
||||||
|
"textDocument": {
|
||||||
|
"uri": uri,
|
||||||
|
},
|
||||||
|
"text": text,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn did_close(
|
pub async fn did_close(
|
||||||
&mut self,
|
&mut self,
|
||||||
uri: Url,
|
uri: Url,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
|
|||||||
|
|
||||||
use mist_codegen::RustCodegen;
|
use mist_codegen::RustCodegen;
|
||||||
use mist_parser::rev_mapper::Mapping;
|
use mist_parser::rev_mapper::Mapping;
|
||||||
use mist_parser::parse;
|
use mist_parser::{MistFmtConfig, parse, parse_module};
|
||||||
|
|
||||||
pub struct TranspiledFile {
|
pub struct TranspiledFile {
|
||||||
pub mist_path: PathBuf,
|
pub mist_path: PathBuf,
|
||||||
@@ -11,35 +11,105 @@ pub struct TranspiledFile {
|
|||||||
pub mapping: Mapping,
|
pub mapping: Mapping,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn transpile_mist(
|
#[derive(Debug)]
|
||||||
mist_path: &Path,
|
pub enum TranspileError<'a> {
|
||||||
source: &str,
|
Parse(mist_parser::error::ParseError<'a>),
|
||||||
extra_mod_decl: &str,
|
Semantic(Vec<mist_parser::semantics::SemanticError>),
|
||||||
) -> Result<TranspiledFile, String> {
|
|
||||||
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
|
|
||||||
// Package files (package.mist) must output as <dir>/mod.rs so the Rust module
|
|
||||||
// hierarchy resolves correctly (pub mod <child>; declarations look for sibling
|
|
||||||
// .rs files, and the parent module declaration looks for <dir>/mod.rs).
|
|
||||||
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
|
|
||||||
rust_path.set_file_name("mod.rs");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
|
/// Resolve the output `.rs` path for a `.mist` source file.
|
||||||
|
///
|
||||||
|
/// Always checks for a `pub module x;` declaration via `parse_module` and
|
||||||
|
/// uses the declared module name as the filename when present. Falls back
|
||||||
|
/// to the literal file stem when parsing fails or the file has no module
|
||||||
|
/// declaration.
|
||||||
|
pub fn resolve_rust_path(mist_path: &Path, source: Option<&str>) -> PathBuf {
|
||||||
|
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
|
||||||
|
// Package files (package.mist) must output as <dir>/mod.rs so the Rust
|
||||||
|
// module hierarchy resolves correctly.
|
||||||
|
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
|
||||||
|
rust_path.set_file_name("mod.rs");
|
||||||
|
} else if let Some(src) = source {
|
||||||
|
// Prioritize the module declaration from the source over the file stem.
|
||||||
|
// Every caller re-parses so we always pick up the current declaration.
|
||||||
|
if let Ok(Some((_, ref name))) = parse_module(src) {
|
||||||
|
if rust_path.file_name().map(|v| v.to_str()).unwrap_or_default() != Some("mod.rs") {
|
||||||
|
if let Some(ext) = rust_path.extension().map(|e| e.to_owned()) {
|
||||||
|
let mut new_name = std::ffi::OsString::from(&name.0);
|
||||||
|
new_name.push(".");
|
||||||
|
new_name.push(ext);
|
||||||
|
rust_path.set_file_name(new_name);
|
||||||
|
} else {
|
||||||
|
rust_path.set_file_name(&name.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rust_path
|
||||||
|
}
|
||||||
|
|
||||||
for item in &parsed {
|
pub fn transpile_mist<'a>(
|
||||||
mist_parser::semantics::check_class_semantics(item)
|
mist_path: &Path,
|
||||||
.map_err(|e| format!("semantic error: {}", e[0].error_message))?;
|
source: &'a str,
|
||||||
|
extra_mod_decl: &str,
|
||||||
|
) -> Result<TranspiledFile, TranspileError<'a>> {
|
||||||
|
let rust_path = resolve_rust_path(mist_path, Some(source));
|
||||||
|
|
||||||
|
let parsed = parse(source).map_err(TranspileError::Parse)?;
|
||||||
|
|
||||||
|
for item in &parsed.items {
|
||||||
|
mist_parser::semantics::check_class_semantics(item).map_err(TranspileError::Semantic)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
|
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
|
||||||
let output = codegen.generate(parsed);
|
|
||||||
|
|
||||||
codegen.mapping.shift_rust(extra_mod_decl.lines().count() as isize, 0);
|
codegen.generate(parsed.mod_attributes);
|
||||||
|
|
||||||
|
codegen.add(extra_mod_decl);
|
||||||
|
|
||||||
|
let output = codegen.generate(parsed.items);
|
||||||
|
|
||||||
Ok(TranspiledFile {
|
Ok(TranspiledFile {
|
||||||
mist_path: mist_path.to_path_buf(),
|
mist_path: mist_path.to_path_buf(),
|
||||||
rust_path,
|
rust_path,
|
||||||
rust_content: format!("{}{}", extra_mod_decl, output),
|
rust_content: output,
|
||||||
mapping: codegen.mapping,
|
mapping: codegen.mapping,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// No Semantics
|
||||||
|
pub fn transpile_mist_no_sem(
|
||||||
|
mist_path: &Path,
|
||||||
|
source: &str,
|
||||||
|
extra_mod_decl: &str,
|
||||||
|
) -> Result<TranspiledFile, String> {
|
||||||
|
let rust_path = resolve_rust_path(mist_path, Some(source));
|
||||||
|
|
||||||
|
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
|
||||||
|
|
||||||
|
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
|
||||||
|
|
||||||
|
codegen.generate(parsed.mod_attributes);
|
||||||
|
|
||||||
|
codegen.add(extra_mod_decl);
|
||||||
|
|
||||||
|
let output = codegen.generate(parsed.items);
|
||||||
|
|
||||||
|
Ok(TranspiledFile {
|
||||||
|
mist_path: mist_path.to_path_buf(),
|
||||||
|
rust_path,
|
||||||
|
rust_content: output,
|
||||||
|
mapping: codegen.mapping,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn format_mist(source: &str, _config: MistFmtConfig) -> Result<String, String> {
|
||||||
|
// let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
|
||||||
|
|
||||||
|
// let mut codegen = MistCodegen::new(config);
|
||||||
|
// codegen.generate(parsed.mod_attributes);
|
||||||
|
// let output = codegen.generate(parsed.items);
|
||||||
|
|
||||||
|
// Ok(output)
|
||||||
|
Ok(source.to_string())
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-codegen"
|
name = "mist-codegen"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language Rust code generator"
|
description = "The Mist programming language Rust code generator"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ pub struct ClassProcessedData {
|
|||||||
items: Vec<ClassItem>,
|
items: Vec<ClassItem>,
|
||||||
methods: Vec<Spanned<FunctionDecl>>,
|
methods: Vec<Spanned<FunctionDecl>>,
|
||||||
v_table: Vec<Identifier>,
|
v_table: Vec<Identifier>,
|
||||||
override_v_table: HashMap<Override, Spanned<Vec<Identifier>>>,
|
override_v_table: HashMap<Override, Spanned<Vec<(Identifier, bool)>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClassProcessedData {
|
impl ClassProcessedData {
|
||||||
@@ -45,13 +45,13 @@ impl ClassProcessedData {
|
|||||||
.collect::<Vec<Spanned<FunctionDecl>>>();
|
.collect::<Vec<Spanned<FunctionDecl>>>();
|
||||||
|
|
||||||
let mut v_table = Vec::new();
|
let mut v_table = Vec::new();
|
||||||
let mut override_v_table = std::collections::HashMap::new();
|
let mut override_v_table = HashMap::new();
|
||||||
|
|
||||||
for method in &methods {
|
for method in &methods {
|
||||||
if matches!(method.item.visibility, Visibility::Public) {
|
if matches!(method.item.visibility, Visibility::Public) {
|
||||||
match &method.item.is_override {
|
match &method.item.is_override {
|
||||||
None => {
|
None => {
|
||||||
if method.item.is_using_self() {
|
if method.item.is_virtual && method.item.self_param.is_some() {
|
||||||
v_table.push(method.item.name.clone());
|
v_table.push(method.item.name.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,7 +64,7 @@ impl ClassProcessedData {
|
|||||||
item: Vec::new(),
|
item: Vec::new(),
|
||||||
})
|
})
|
||||||
.item
|
.item
|
||||||
.push(method.item.name.clone());
|
.push((method.item.name.clone(), method.item.is_virtual));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ impl ClassProcessedData {
|
|||||||
cg.add(&get_type_from_path(inherits).get_rust());
|
cg.add(&get_type_from_path(inherits).get_rust());
|
||||||
cg.addln(",");
|
cg.addln(",");
|
||||||
} else {
|
} else {
|
||||||
cg.add_indentedln("pub _vptr: &'static [*const std::ffi::c_void],");
|
cg.add_indentedln("pub _vptr: &'static [*const core::ffi::c_void],");
|
||||||
}
|
}
|
||||||
|
|
||||||
for field in &self.fields {
|
for field in &self.fields {
|
||||||
@@ -174,11 +174,11 @@ impl ClassProcessedData {
|
|||||||
self.v_table.len()
|
self.v_table.len()
|
||||||
));
|
));
|
||||||
|
|
||||||
cg.add_indentedln("pub const __V_TABLE: &'static [*const std::ffi::c_void] = &{");
|
cg.add_indentedln("pub const __V_TABLE: &'static [*const core::ffi::c_void] = &{");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
if has_parent {
|
if has_parent {
|
||||||
cg.add_indentedln("let mut table = [std::ptr::null(); Self::__V_COUNT];");
|
cg.add_indentedln("let mut table = [core::ptr::null(); Self::__V_COUNT];");
|
||||||
|
|
||||||
cg.add_indentedln(&format!("let parent_table = {}::__V_TABLE;", parent_path));
|
cg.add_indentedln(&format!("let parent_table = {}::__V_TABLE;", parent_path));
|
||||||
cg.add_indentedln(
|
cg.add_indentedln(
|
||||||
@@ -191,20 +191,20 @@ impl ClassProcessedData {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap_or(self.inherits.as_ref().unwrap())
|
.unwrap_or(self.inherits.as_ref().unwrap())
|
||||||
.get_rust();
|
.get_rust();
|
||||||
for method_ident in &overriden_method_idents.item {
|
for (method_ident, is_virtual) in &overriden_method_idents.item {
|
||||||
cg.add_indentedln(&format!(
|
cg.add_indentedln(&format!(
|
||||||
"table[{}::__FN_{}] = {}::__m_{} as *const std::ffi::c_void;",
|
"table[{}::__FN_{}] = {}::{} as *const core::ffi::c_void;",
|
||||||
base_class_path,
|
base_class_path,
|
||||||
method_ident.0.to_uppercase(),
|
method_ident.0.to_uppercase(),
|
||||||
self.self_path.get_rust(),
|
self.self_path.get_rust(),
|
||||||
method_ident.get_rust()
|
get_virtual_name(method_ident, *is_virtual)
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for method_name in &self.v_table {
|
for method_name in &self.v_table {
|
||||||
cg.add_indentedln(&format!(
|
cg.add_indentedln(&format!(
|
||||||
"table[Self::__FN_{}] = Self::__m_{} as *const std::ffi::c_void;",
|
"table[Self::__FN_{}] = Self::__m_{} as *const core::ffi::c_void;",
|
||||||
method_name.0.to_uppercase(),
|
method_name.0.to_uppercase(),
|
||||||
method_name.get_rust()
|
method_name.get_rust()
|
||||||
));
|
));
|
||||||
@@ -216,7 +216,7 @@ impl ClassProcessedData {
|
|||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
for method_name in &self.v_table {
|
for method_name in &self.v_table {
|
||||||
cg.add_indentedln(&format!(
|
cg.add_indentedln(&format!(
|
||||||
"Self::__m_{} as *const std::ffi::c_void,",
|
"Self::__m_{} as *const core::ffi::c_void,",
|
||||||
method_name.get_rust()
|
method_name.get_rust()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -263,7 +263,7 @@ impl ClassProcessedData {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let TypeExpr::Ref { mutable, .. } = params.remove(0) {
|
if let Some((_, _, mutable)) = &method.item.self_param {
|
||||||
method.gen_span(cg);
|
method.gen_span(cg);
|
||||||
cg.add_indented(&format!("{}::__m_", target_rust_path));
|
cg.add_indented(&format!("{}::__m_", target_rust_path));
|
||||||
cg.add(&method.item.name.get_rust());
|
cg.add(&method.item.name.get_rust());
|
||||||
@@ -273,7 +273,7 @@ impl ClassProcessedData {
|
|||||||
0,
|
0,
|
||||||
TypeExpr::Ref {
|
TypeExpr::Ref {
|
||||||
lifetime: None,
|
lifetime: None,
|
||||||
mutable,
|
mutable: *mutable,
|
||||||
ty: Box::new(get_type_from_path(&target_path)),
|
ty: Box::new(get_type_from_path(&target_path)),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -293,7 +293,7 @@ impl ClassProcessedData {
|
|||||||
|
|
||||||
// Deref tests for override targets
|
// Deref tests for override targets
|
||||||
if self.inherits.is_some() && !self.override_v_table.is_empty() {
|
if self.inherits.is_some() && !self.override_v_table.is_empty() {
|
||||||
cg.add_indentedln("let this: &Self = &unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
cg.add_indentedln("let this: &Self = &unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
||||||
|
|
||||||
for (override_tier, v) in &self.override_v_table {
|
for (override_tier, v) in &self.override_v_table {
|
||||||
if let Some(path) = &override_tier.0 {
|
if let Some(path) = &override_tier.0 {
|
||||||
@@ -346,14 +346,15 @@ impl ClassProcessedData {
|
|||||||
cg.addln(") -> Self {");
|
cg.addln(") -> Self {");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
cg.add_indentedln("let mut this: Self = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
cg.add_indentedln("let mut this: Self = unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
|
||||||
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
|
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
|
||||||
|
|
||||||
for field in &self.fields {
|
for field in &self.fields {
|
||||||
if let Some(init) = &field.item.init {
|
if let Some(init) = &field.item.init {
|
||||||
field.gen_span(cg);
|
field.gen_span(cg);
|
||||||
cg.add_indentedln(&format!("this.{} = ", field.item.decl.name.get_rust()));
|
cg.add_indented(&format!("this.{} = ", field.item.decl.name.get_rust()));
|
||||||
init.gen_rust(ctx, cg);
|
init.gen_rust(ctx, cg);
|
||||||
|
cg.addln(";");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,7 +363,6 @@ impl ClassProcessedData {
|
|||||||
if *i > 0 {
|
if *i > 0 {
|
||||||
cg.add(", ");
|
cg.add(", ");
|
||||||
}
|
}
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
param.name.gen_rust(ctx, cg);
|
param.name.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
cg.addln(");");
|
cg.addln(");");
|
||||||
@@ -375,29 +375,17 @@ impl ClassProcessedData {
|
|||||||
cg.indent -= 1;
|
cg.indent -= 1;
|
||||||
cg.add_indentedln("}\n");
|
cg.add_indentedln("}\n");
|
||||||
|
|
||||||
let mut constructor_params = vec![VarDecl {
|
|
||||||
name: Pattern::Path(false, Path(vec![Identifier(String::from("self"))])),
|
|
||||||
type_: Some(TypeExpr::Ref {
|
|
||||||
lifetime: None,
|
|
||||||
mutable: true,
|
|
||||||
ty: Box::new(TypeExpr::Path(
|
|
||||||
Path(vec![Identifier(String::from("Self"))]),
|
|
||||||
None,
|
|
||||||
)),
|
|
||||||
}),
|
|
||||||
}];
|
|
||||||
|
|
||||||
constructor_params.append(&mut constructor.item.params.0.clone());
|
|
||||||
|
|
||||||
Spanned {
|
Spanned {
|
||||||
line: constructor.line,
|
line: constructor.line,
|
||||||
column: constructor.column,
|
column: constructor.column,
|
||||||
item: FunctionDecl {
|
item: FunctionDecl {
|
||||||
visibility: constructor.item.visibility.clone(),
|
visibility: constructor.item.visibility.clone(),
|
||||||
|
is_virtual: false,
|
||||||
is_override: None,
|
is_override: None,
|
||||||
name: Identifier(String::from("constructor")),
|
name: Identifier(String::from("constructor")),
|
||||||
generics: constructor.item.generics.clone(),
|
generics: constructor.item.generics.clone(),
|
||||||
params: ParamList(constructor_params),
|
params: constructor.item.params.clone(),
|
||||||
|
self_param: Some((true, None, true)),
|
||||||
return_type: Some(TypeExpr::Tuple(Vec::new())),
|
return_type: Some(TypeExpr::Tuple(Vec::new())),
|
||||||
body: Some(constructor.item.body.clone()),
|
body: Some(constructor.item.body.clone()),
|
||||||
},
|
},
|
||||||
@@ -409,7 +397,7 @@ impl ClassProcessedData {
|
|||||||
for method in &self.methods {
|
for method in &self.methods {
|
||||||
match method.item.visibility {
|
match method.item.visibility {
|
||||||
Visibility::Public => {
|
Visibility::Public => {
|
||||||
if method.item.is_using_self() {
|
if method.item.is_virtual && method.item.self_param.is_some() {
|
||||||
if method.item.is_override.is_none() {
|
if method.item.is_override.is_none() {
|
||||||
gen_method_point(&method.item, ctx, cg);
|
gen_method_point(&method.item, ctx, cg);
|
||||||
}
|
}
|
||||||
@@ -445,7 +433,7 @@ impl ClassProcessedData {
|
|||||||
let generics_expr_str = Generics::from(self.generics.clone()).get_rust();
|
let generics_expr_str = Generics::from(self.generics.clone()).get_rust();
|
||||||
|
|
||||||
cg.add(&format!(
|
cg.add(&format!(
|
||||||
"impl{} std::ops::Deref for {}{}",
|
"impl{} core::ops::Deref for {}{}",
|
||||||
generics_str,
|
generics_str,
|
||||||
self.name.get_rust(),
|
self.name.get_rust(),
|
||||||
generics_expr_str
|
generics_expr_str
|
||||||
@@ -464,7 +452,7 @@ impl ClassProcessedData {
|
|||||||
cg.addln("}");
|
cg.addln("}");
|
||||||
|
|
||||||
cg.add(&format!(
|
cg.add(&format!(
|
||||||
"impl{} std::ops::DerefMut for {}{}",
|
"impl{} core::ops::DerefMut for {}{}",
|
||||||
generics_str,
|
generics_str,
|
||||||
self.name.get_rust(),
|
self.name.get_rust(),
|
||||||
generics_expr_str
|
generics_expr_str
|
||||||
@@ -513,6 +501,7 @@ fn construct_pattern(pat: &Pattern, idx: usize) -> Pattern {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustCodegen) {
|
pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
let mutable_self = if let Some((is_ref, lifetime, is_mut)) = &method.self_param {
|
||||||
cg.add_indented(&format!(
|
cg.add_indented(&format!(
|
||||||
"{}fn {}{}(",
|
"{}fn {}{}(",
|
||||||
method.visibility.get_rust(),
|
method.visibility.get_rust(),
|
||||||
@@ -520,6 +509,25 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
|
|||||||
method.generics.get_rust(),
|
method.generics.get_rust(),
|
||||||
));
|
));
|
||||||
|
|
||||||
|
if *is_ref {
|
||||||
|
cg.add("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(lifetime) = lifetime {
|
||||||
|
cg.add(&format!("'{} ", lifetime.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
if *is_mut {
|
||||||
|
cg.add("mut ");
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add("self,");
|
||||||
|
|
||||||
|
*is_mut
|
||||||
|
} else {
|
||||||
|
panic!();
|
||||||
|
};
|
||||||
|
|
||||||
let params = method
|
let params = method
|
||||||
.params
|
.params
|
||||||
.0
|
.0
|
||||||
@@ -566,17 +574,13 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
|
|||||||
.filter_map(|v| v.type_)
|
.filter_map(|v| v.type_)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let TypeExpr::Ref { mutable, .. } = param_types.remove(0) else {
|
|
||||||
panic!("")
|
|
||||||
};
|
|
||||||
|
|
||||||
param_types.insert(
|
param_types.insert(
|
||||||
0,
|
0,
|
||||||
TypeExpr::UnsafePtr {
|
TypeExpr::UnsafePtr {
|
||||||
mutable,
|
mutable: mutable_self,
|
||||||
ty: Box::new(TypeExpr::Path(
|
ty: Box::new(TypeExpr::Path(
|
||||||
Path(vec![
|
Path(vec![
|
||||||
Identifier(String::from("std")),
|
Identifier(String::from("core")),
|
||||||
Identifier(String::from("ffi")),
|
Identifier(String::from("ffi")),
|
||||||
Identifier(String::from("c_void")),
|
Identifier(String::from("c_void")),
|
||||||
]),
|
]),
|
||||||
@@ -586,20 +590,16 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
|
|||||||
);
|
);
|
||||||
|
|
||||||
cg.add(&TypeExpr::StaticFn(param_types, method.return_type.clone().map(Box::new)).get_rust());
|
cg.add(&TypeExpr::StaticFn(param_types, method.return_type.clone().map(Box::new)).get_rust());
|
||||||
cg.addln(" = std::mem::transmute(func_ptr);");
|
cg.addln(" = core::mem::transmute(func_ptr);");
|
||||||
|
|
||||||
if mutable {
|
if mutable_self {
|
||||||
cg.add_indented("func(self as *mut Self as *const std::ffi::c_void");
|
cg.add_indented("func(self as *mut Self as *mut core::ffi::c_void");
|
||||||
} else {
|
} else {
|
||||||
cg.add_indented("func(self as *const Self as *const std::ffi::c_void");
|
cg.add_indented("func(self as *const Self as *const core::ffi::c_void");
|
||||||
}
|
}
|
||||||
|
|
||||||
for (i, param) in ¶ms {
|
for (_, param) in ¶ms {
|
||||||
if *i == 0 {
|
|
||||||
continue; // self already fulfills it
|
|
||||||
}
|
|
||||||
cg.add(", ");
|
cg.add(", ");
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
param.name.gen_rust(ctx, cg);
|
param.name.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,3 +618,11 @@ pub fn get_type_from_path(path: &ExprPath) -> TypeExpr {
|
|||||||
path.0.last().unwrap().generics.clone(),
|
path.0.last().unwrap().generics.clone(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_virtual_name(name: &Identifier, is_virtual: bool) -> String {
|
||||||
|
if is_virtual {
|
||||||
|
format!("__m_{}", name.get_rust())
|
||||||
|
} else {
|
||||||
|
name.get_rust()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -68,14 +68,6 @@ impl GenRust for Literal {
|
|||||||
|
|
||||||
impl GenRust for Expression {
|
impl GenRust for Expression {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
let ensure_semicolon = if ctx.expr_ensure_semicolon {
|
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
};
|
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Expression::Path(path) => cg.add(&path.get_rust_ctx(ctx)),
|
Expression::Path(path) => cg.add(&path.get_rust_ctx(ctx)),
|
||||||
Expression::Literal(literal) => literal.gen_rust(ctx, cg),
|
Expression::Literal(literal) => literal.gen_rust(ctx, cg),
|
||||||
@@ -152,14 +144,6 @@ impl GenRust for Expression {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ensure_semicolon {
|
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
|
|
||||||
if !self.is_block() {
|
|
||||||
cg.add(";");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,11 +240,6 @@ impl GenRust for Postfix {
|
|||||||
|
|
||||||
Postfix::Try => cg.add("?"),
|
Postfix::Try => cg.add("?"),
|
||||||
|
|
||||||
Postfix::Assign(cmp, expr) => {
|
|
||||||
cg.add(" ");
|
|
||||||
cg.add(cmp);
|
|
||||||
expr.gen_rust(ctx, cg);
|
|
||||||
}
|
|
||||||
Postfix::Increment => cg.add("+=1"),
|
Postfix::Increment => cg.add("+=1"),
|
||||||
Postfix::Decrement => cg.add("-=1"),
|
Postfix::Decrement => cg.add("-=1"),
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-25
@@ -3,7 +3,7 @@ pub mod expr;
|
|||||||
pub mod statement;
|
pub mod statement;
|
||||||
pub mod top_level;
|
pub mod top_level;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::{collections::HashMap, path::PathBuf};
|
||||||
|
|
||||||
use mist_parser::{
|
use mist_parser::{
|
||||||
ast::*,
|
ast::*,
|
||||||
@@ -11,7 +11,6 @@ use mist_parser::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
pub expr_ensure_semicolon: bool,
|
|
||||||
pub expr_super: Option<ExprPath>,
|
pub expr_super: Option<ExprPath>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,9 +26,15 @@ pub trait GetRust {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub enum Include {
|
||||||
|
Glob(Path),
|
||||||
|
Use(Visibility, Path),
|
||||||
|
}
|
||||||
|
|
||||||
pub struct RustCodegen {
|
pub struct RustCodegen {
|
||||||
output: String,
|
output: String,
|
||||||
indent: usize,
|
indent: usize,
|
||||||
|
pub crates: HashMap<Identifier, Vec<Include>>,
|
||||||
pub mapping: Mapping,
|
pub mapping: Mapping,
|
||||||
position: RustMap,
|
position: RustMap,
|
||||||
}
|
}
|
||||||
@@ -39,8 +44,9 @@ impl RustCodegen {
|
|||||||
Self {
|
Self {
|
||||||
output: String::new(),
|
output: String::new(),
|
||||||
indent: 0,
|
indent: 0,
|
||||||
|
crates: HashMap::new(),
|
||||||
mapping: Mapping::new(mist_path),
|
mapping: Mapping::new(mist_path),
|
||||||
position: RustMap(1, 0),
|
position: RustMap(0, 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +54,7 @@ impl RustCodegen {
|
|||||||
" ".repeat(self.indent)
|
" ".repeat(self.indent)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add(&mut self, s: &str) {
|
pub fn add(&mut self, s: &str) {
|
||||||
let newline_count = bytecount::count(s.as_bytes(), b'\n');
|
let newline_count = bytecount::count(s.as_bytes(), b'\n');
|
||||||
|
|
||||||
if newline_count == 0 {
|
if newline_count == 0 {
|
||||||
@@ -63,31 +69,61 @@ impl RustCodegen {
|
|||||||
self.output.push_str(s);
|
self.output.push_str(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn addln(&mut self, s: &str) {
|
pub fn addln(&mut self, s: &str) {
|
||||||
self.add(s);
|
self.add(s);
|
||||||
self.add("\n");
|
self.add("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_indented(&mut self, s: &str) {
|
pub fn add_indented(&mut self, s: &str) {
|
||||||
let line = format!("{}{}", self.indent_str(), s);
|
let line = format!("{}{}", self.indent_str(), s);
|
||||||
self.add(&line);
|
self.add(&line);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_indentedln(&mut self, s: &str) {
|
pub fn add_indentedln(&mut self, s: &str) {
|
||||||
let line = format!("{}{}\n", self.indent_str(), s);
|
let line = format!("{}{}\n", self.indent_str(), s);
|
||||||
self.add(&line);
|
self.add(&line);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
|
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
|
||||||
let mut ctx = Context {
|
let mut ctx = Context { expr_super: None };
|
||||||
expr_ensure_semicolon: true,
|
|
||||||
expr_super: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
for tl in toplevels {
|
for tl in toplevels {
|
||||||
tl.gen_rust(&mut ctx, self);
|
tl.gen_rust(&mut ctx, self);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut crates = HashMap::new();
|
||||||
|
std::mem::swap(&mut self.crates, &mut crates);
|
||||||
|
|
||||||
|
for (c, items) in crates {
|
||||||
|
self.add("mod ");
|
||||||
|
c.gen_rust(&mut ctx, self);
|
||||||
|
self.addln(" {");
|
||||||
|
self.indent += 1;
|
||||||
|
|
||||||
|
self.add_indented("extern crate ");
|
||||||
|
c.gen_rust(&mut ctx, self);
|
||||||
|
self.addln(";");
|
||||||
|
|
||||||
|
for item in items {
|
||||||
|
self.add_indentedln("#[doc(inline)]");
|
||||||
|
self.add_indented("pub use ");
|
||||||
|
match item {
|
||||||
|
Include::Glob(item) => {
|
||||||
|
item.gen_rust(&mut ctx, self);
|
||||||
|
self.add("::*");
|
||||||
|
}
|
||||||
|
Include::Use(vis, item) => {
|
||||||
|
vis.gen_rust(&mut ctx, self);
|
||||||
|
item.gen_rust(&mut ctx, self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.addln(";");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.indent -= 1;
|
||||||
|
self.addln("}");
|
||||||
|
}
|
||||||
|
|
||||||
self.output.clone()
|
self.output.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,7 +186,7 @@ impl<T> GenSpanTranslation for Spanned<T> {
|
|||||||
fn gen_span(&self, cg: &mut RustCodegen) {
|
fn gen_span(&self, cg: &mut RustCodegen) {
|
||||||
cg.mapping
|
cg.mapping
|
||||||
.map
|
.map
|
||||||
.insert((cg.position, MistMap(self.line, self.column)));
|
.insert((cg.position, MistMap(self.line, self.column - 1)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,7 +239,6 @@ impl GetRust for TypeExpr {
|
|||||||
path.get_rust()
|
path.get_rust()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Self::Lifetime(name) => format!("'{}", name.get_rust()),
|
|
||||||
Self::Tuple(types) => format!(
|
Self::Tuple(types) => format!(
|
||||||
"({})",
|
"({})",
|
||||||
types
|
types
|
||||||
@@ -246,23 +281,12 @@ impl GetRust for TypeExpr {
|
|||||||
ty,
|
ty,
|
||||||
} => {
|
} => {
|
||||||
if let Some(lifetime) = lifetime {
|
if let Some(lifetime) = lifetime {
|
||||||
match lifetime {
|
|
||||||
Lifetime::Lifetime(v) => {
|
|
||||||
format!(
|
format!(
|
||||||
"&'{} {}{}",
|
"&'{} {}{}",
|
||||||
v.get_rust(),
|
lifetime.get_rust(),
|
||||||
if *mutable { "mut " } else { "" },
|
if *mutable { "mut " } else { "" },
|
||||||
ty.get_rust()
|
ty.get_rust()
|
||||||
)
|
)
|
||||||
}
|
|
||||||
Lifetime::Unsafe => {
|
|
||||||
format!(
|
|
||||||
"*{} {}",
|
|
||||||
if *mutable { "mut" } else { "const" },
|
|
||||||
ty.get_rust()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
format!("&{}{}", if *mutable { "mut " } else { "" }, ty.get_rust())
|
format!("&{}{}", if *mutable { "mut " } else { "" }, ty.get_rust())
|
||||||
}
|
}
|
||||||
@@ -271,7 +295,44 @@ impl GetRust for TypeExpr {
|
|||||||
Self::Dyn(ty) => {
|
Self::Dyn(ty) => {
|
||||||
format!("dyn {}", ty.get_rust())
|
format!("dyn {}", ty.get_rust())
|
||||||
}
|
}
|
||||||
|
Self::Void => "()".to_string(),
|
||||||
|
Self::Fn {
|
||||||
|
kind,
|
||||||
|
return_type,
|
||||||
|
params,
|
||||||
|
} => {
|
||||||
|
format!(
|
||||||
|
"{}({}) -> {}",
|
||||||
|
kind.get_rust(),
|
||||||
|
params
|
||||||
|
.iter()
|
||||||
|
.map(TypeExpr::get_rust)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
return_type.get_rust(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
Self::Array(ty, count) => {
|
||||||
|
if let Some(count) = count {
|
||||||
|
format!("[{}; {count}]", ty.get_rust())
|
||||||
|
} else {
|
||||||
|
format!("[{}]", ty.get_rust())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GetRust for FnKind {
|
||||||
|
fn get_rust(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::Fn => "fn",
|
||||||
|
Self::UnsafeFn => "unsafe fn",
|
||||||
|
Self::FnClosure => "Fn",
|
||||||
|
Self::FnMut => "FnMut",
|
||||||
|
Self::FnOnce => "FnOnce",
|
||||||
|
}
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,14 +10,15 @@ impl GenRust for Block {
|
|||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
for stmt in &self.statements {
|
for stmt in &self.statements {
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
cg.add_indented("");
|
cg.add_indented("");
|
||||||
stmt.gen_rust(ctx, cg);
|
stmt.gen_rust(ctx, cg);
|
||||||
|
if stmt.item.is_semicolon_required() {
|
||||||
|
cg.add(";");
|
||||||
|
}
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(soft_return) = &self.soft_return {
|
if let Some(soft_return) = &self.soft_return {
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
cg.add_indented("");
|
cg.add_indented("");
|
||||||
soft_return.gen_rust(ctx, cg);
|
soft_return.gen_rust(ctx, cg);
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
@@ -31,13 +32,14 @@ impl GenRust for Block {
|
|||||||
impl GenRust for Statement {
|
impl GenRust for Statement {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
|
Statement::TopLevel(tl) => tl.gen_rust(ctx, cg),
|
||||||
|
Statement::Block(block) => block.gen_rust(ctx, cg),
|
||||||
|
|
||||||
Statement::UnsafeBlock(block) => {
|
Statement::UnsafeBlock(block) => {
|
||||||
cg.add("unsafe ");
|
cg.add("unsafe ");
|
||||||
block.gen_rust(ctx, cg);
|
block.gen_rust(ctx, cg);
|
||||||
}
|
}
|
||||||
|
|
||||||
Statement::Block(block) => block.gen_rust(ctx, cg),
|
|
||||||
|
|
||||||
Statement::VarDecl(VarDeclStmt { decl, init }) => {
|
Statement::VarDecl(VarDeclStmt { decl, init }) => {
|
||||||
cg.add("let ");
|
cg.add("let ");
|
||||||
decl.gen_rust(ctx, cg);
|
decl.gen_rust(ctx, cg);
|
||||||
@@ -85,14 +87,12 @@ impl GenRust for Statement {
|
|||||||
else_branch,
|
else_branch,
|
||||||
} => {
|
} => {
|
||||||
cg.add("if ");
|
cg.add("if ");
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
initial.condition.gen_rust(ctx, cg);
|
initial.condition.gen_rust(ctx, cg);
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
initial.body.gen_rust(ctx, cg);
|
initial.body.gen_rust(ctx, cg);
|
||||||
|
|
||||||
for else_if_branch in else_if {
|
for else_if_branch in else_if {
|
||||||
cg.add(" else if ");
|
cg.add(" else if ");
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
else_if_branch.condition.gen_rust(ctx, cg);
|
else_if_branch.condition.gen_rust(ctx, cg);
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
else_if_branch.body.gen_rust(ctx, cg);
|
else_if_branch.body.gen_rust(ctx, cg);
|
||||||
@@ -125,17 +125,18 @@ impl GenRust for Statement {
|
|||||||
cg.addln("{");
|
cg.addln("{");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
|
|
||||||
cg.add_indented("");
|
cg.add_indented("");
|
||||||
|
|
||||||
init.gen_rust(ctx, cg);
|
init.gen_rust(ctx, cg);
|
||||||
|
|
||||||
|
if init.is_semicolon_required() {
|
||||||
|
cg.add(";");
|
||||||
|
}
|
||||||
|
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
|
|
||||||
cg.add_indented("while ");
|
cg.add_indented("while ");
|
||||||
|
|
||||||
ctx.expr_ensure_semicolon = false;
|
|
||||||
condition.gen_rust(ctx, cg);
|
condition.gen_rust(ctx, cg);
|
||||||
|
|
||||||
cg.add(" ");
|
cg.add(" ");
|
||||||
@@ -143,12 +144,14 @@ impl GenRust for Statement {
|
|||||||
cg.add("{");
|
cg.add("{");
|
||||||
cg.indent += 1;
|
cg.indent += 1;
|
||||||
|
|
||||||
ctx.expr_ensure_semicolon = true;
|
|
||||||
|
|
||||||
body.gen_rust(ctx, cg);
|
body.gen_rust(ctx, cg);
|
||||||
|
|
||||||
update.gen_rust(ctx, cg);
|
update.gen_rust(ctx, cg);
|
||||||
|
|
||||||
|
if update.is_semicolon_required() {
|
||||||
|
cg.add(";");
|
||||||
|
}
|
||||||
|
|
||||||
cg.addln("");
|
cg.addln("");
|
||||||
|
|
||||||
cg.indent -= 1;
|
cg.indent -= 1;
|
||||||
@@ -185,8 +188,19 @@ impl GenRust for Statement {
|
|||||||
|
|
||||||
impl GenRust for VarDecl {
|
impl GenRust for VarDecl {
|
||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
|
if self.tuple_names.is_empty() {
|
||||||
self.name.gen_rust(ctx, cg);
|
self.name.gen_rust(ctx, cg);
|
||||||
|
} else {
|
||||||
|
cg.add("(");
|
||||||
|
self.name.gen_rust(ctx, cg);
|
||||||
|
for name in &self.tuple_names {
|
||||||
|
cg.add(", ");
|
||||||
|
name.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
cg.add(")");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.true_type {
|
||||||
cg.add(
|
cg.add(
|
||||||
&self
|
&self
|
||||||
.type_
|
.type_
|
||||||
@@ -194,5 +208,21 @@ impl GenRust for VarDecl {
|
|||||||
.map(|t| format!(": {}", t.get_rust()))
|
.map(|t| format!(": {}", t.get_rust()))
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
);
|
);
|
||||||
|
} else {
|
||||||
|
cg.add(
|
||||||
|
&self
|
||||||
|
.type_
|
||||||
|
.as_ref()
|
||||||
|
.map(|t| {
|
||||||
|
let t = vec![t.get_rust(); self.tuple_names.len() + 1];
|
||||||
|
if self.tuple_names.is_empty() {
|
||||||
|
format!(": {}", t.join(", "))
|
||||||
|
} else {
|
||||||
|
format!(": ({})", t.join(", "))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,21 @@ impl GetRust for GenericsDecl {
|
|||||||
impl GetRust for GenericDecl {
|
impl GetRust for GenericDecl {
|
||||||
fn get_rust(&self) -> String {
|
fn get_rust(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
GenericDecl::Lifetime(name) => format!("'{}", name.get_rust()),
|
GenericDecl::Lifetime(name, requirements) => {
|
||||||
|
format!("'{}", name.get_rust())
|
||||||
|
+ &(if requirements.len() != 0 {
|
||||||
|
format!(
|
||||||
|
": {}",
|
||||||
|
requirements
|
||||||
|
.into_iter()
|
||||||
|
.map(GetRust::get_rust)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("+")
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
})
|
||||||
|
}
|
||||||
GenericDecl::Type(name, requirements) => {
|
GenericDecl::Type(name, requirements) => {
|
||||||
name.get_rust()
|
name.get_rust()
|
||||||
+ &(if requirements.len() != 0 {
|
+ &(if requirements.len() != 0 {
|
||||||
@@ -32,7 +46,7 @@ impl GetRust for GenericDecl {
|
|||||||
": {}",
|
": {}",
|
||||||
requirements
|
requirements
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(TypeExpr::get_rust)
|
.map(GetRust::get_rust)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("+")
|
.join("+")
|
||||||
)
|
)
|
||||||
@@ -80,6 +94,22 @@ impl GenRust for FunctionDecl {
|
|||||||
self.generics.get_rust(),
|
self.generics.get_rust(),
|
||||||
));
|
));
|
||||||
|
|
||||||
|
if let Some((is_ref, lifetime, is_mut)) = &self.self_param {
|
||||||
|
if *is_ref {
|
||||||
|
cg.add("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(lifetime) = lifetime {
|
||||||
|
cg.add(&format!("'{} ", lifetime.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
if *is_mut {
|
||||||
|
cg.add("mut ");
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.add("self,");
|
||||||
|
}
|
||||||
|
|
||||||
for (i, param) in self.params.0.iter().enumerate() {
|
for (i, param) in self.params.0.iter().enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
cg.add(", ");
|
cg.add(", ");
|
||||||
@@ -175,6 +205,38 @@ impl GenRust for TopLevelKind {
|
|||||||
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||||
match self {
|
match self {
|
||||||
Self::ModAttribute => {}
|
Self::ModAttribute => {}
|
||||||
|
Self::TypeAlias { name, generics, ty } => {
|
||||||
|
cg.add("type ");
|
||||||
|
name.gen_rust(ctx, cg);
|
||||||
|
if let Some(g) = generics {
|
||||||
|
g.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
cg.add(" = ");
|
||||||
|
ty.gen_rust(ctx, cg);
|
||||||
|
cg.addln(";");
|
||||||
|
}
|
||||||
|
Self::ConstDecl(decl) => {
|
||||||
|
cg.add("const ");
|
||||||
|
decl.decl.gen_rust(ctx, cg);
|
||||||
|
|
||||||
|
if let Some(init) = &decl.init {
|
||||||
|
cg.add(" = ");
|
||||||
|
init.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.addln(";");
|
||||||
|
}
|
||||||
|
Self::StaticDecl(decl) => {
|
||||||
|
cg.add("static ");
|
||||||
|
decl.decl.gen_rust(ctx, cg);
|
||||||
|
|
||||||
|
if let Some(init) = &decl.init {
|
||||||
|
cg.add(" = ");
|
||||||
|
init.gen_rust(ctx, cg);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.addln(";");
|
||||||
|
}
|
||||||
Self::Import(vis, path) => {
|
Self::Import(vis, path) => {
|
||||||
cg.addln(&format!("{}use {};", vis.get_rust(), path.get_rust()))
|
cg.addln(&format!("{}use {};", vis.get_rust(), path.get_rust()))
|
||||||
}
|
}
|
||||||
@@ -204,6 +266,33 @@ impl GenRust for TopLevelKind {
|
|||||||
cg.indent -= 1;
|
cg.indent -= 1;
|
||||||
cg.addln("}\n");
|
cg.addln("}\n");
|
||||||
}
|
}
|
||||||
|
Self::StructDeclTupleUnit {
|
||||||
|
visibility,
|
||||||
|
name,
|
||||||
|
generics,
|
||||||
|
unit,
|
||||||
|
} => {
|
||||||
|
cg.addln(&format!(
|
||||||
|
"{}struct {}{}",
|
||||||
|
visibility.get_rust(),
|
||||||
|
name.get_rust(),
|
||||||
|
generics.get_rust()
|
||||||
|
));
|
||||||
|
cg.indent += 1;
|
||||||
|
|
||||||
|
if let Some(unit) = unit {
|
||||||
|
cg.add(" (");
|
||||||
|
for unit in unit {
|
||||||
|
cg.add_indented("");
|
||||||
|
unit.gen_rust(ctx, cg);
|
||||||
|
cg.add(", ");
|
||||||
|
}
|
||||||
|
cg.add(")");
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.indent -= 1;
|
||||||
|
cg.addln(";\n");
|
||||||
|
}
|
||||||
Self::EnumDecl {
|
Self::EnumDecl {
|
||||||
visibility,
|
visibility,
|
||||||
name,
|
name,
|
||||||
@@ -278,6 +367,23 @@ impl GenRust for TopLevelKind {
|
|||||||
constructor,
|
constructor,
|
||||||
items,
|
items,
|
||||||
),
|
),
|
||||||
|
Self::IncludeGlobal(incl) => {
|
||||||
|
cg.crates
|
||||||
|
.entry(incl.0[0].clone())
|
||||||
|
.or_insert(Vec::new())
|
||||||
|
.push(crate::Include::Glob(incl.clone()));
|
||||||
|
}
|
||||||
|
Self::IncludeUse(vis, incl) => {
|
||||||
|
cg.crates
|
||||||
|
.entry(incl.0[0].clone())
|
||||||
|
.or_insert(Vec::new())
|
||||||
|
.push(crate::Include::Use(vis.clone(), incl.clone()));
|
||||||
|
}
|
||||||
|
Self::IncludeLocal(path) => {
|
||||||
|
cg.add("include!(\"");
|
||||||
|
cg.add(&path.replace(".mist", ".rs"));
|
||||||
|
cg.add("\");");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-api"
|
name = "mist-api"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language module system"
|
description = "The Mist programming language module system"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|||||||
@@ -1,80 +1,70 @@
|
|||||||
pub module builder;
|
pub module builder;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use std::process::Stdio;
|
use std::process::Stdio;
|
||||||
|
|
||||||
use cargo_metadata::CompilerMessage;
|
use cargo_metadata::CompilerMessage;
|
||||||
|
|
||||||
use cargo_metadata::Message;
|
use cargo_metadata::Message;
|
||||||
|
|
||||||
use mist_parser::rev_mapper;
|
use mist_parser::rev_mapper;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct MistDiagnosticMessage {
|
pub struct MistDiagnosticMessage
|
||||||
pub message String,
|
{
|
||||||
pub file_path PathBuf,
|
pub String message;
|
||||||
pub file_name String ,
|
pub PathBuf file_path;
|
||||||
pub line usize,
|
pub String file_name;
|
||||||
pub column usize,
|
pub usize line;
|
||||||
|
pub usize column;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum MistDiagnostic {
|
pub enum MistDiagnostic
|
||||||
Error(MistDiagnosticMessage),
|
{
|
||||||
Warning(MistDiagnosticMessage),
|
Error(MistDiagnosticMessage);
|
||||||
Rust(CompilerMessage),
|
Warning(MistDiagnosticMessage);
|
||||||
|
Rust(CompilerMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bool build(mut args Vec<String>, root PathBuf) {
|
pub bool build(Vec<String> mut args, PathBuf root)
|
||||||
|
{
|
||||||
args.remove(0);
|
args.remove(0);
|
||||||
args.insert(1, "--message-format=json".to_string());
|
args.insert(1, "--message-format=json".to_string());
|
||||||
|
let mut command = Command::new("cargo").args(args).stdout(Stdio::piped()).stderr(Stdio::inherit()).stdin(Stdio::inherit()).spawn().expect("Failed to run cargo");
|
||||||
let mut command = Command::new("cargo")
|
|
||||||
.args(args)
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::inherit())
|
|
||||||
.stdin(Stdio::inherit())
|
|
||||||
.spawn()
|
|
||||||
.expect("Failed to run cargo");
|
|
||||||
|
|
||||||
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
|
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
|
||||||
|
|
||||||
let mut diagnostics = Vec::new();
|
let mut diagnostics = Vec::new();
|
||||||
|
|
||||||
let mut mapping = HashMap::new();
|
let mut mapping = HashMap::new();
|
||||||
|
|
||||||
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
||||||
match message {
|
match message {
|
||||||
Ok(Message::CompilerMessage(msg)) => {
|
Ok(Message::CompilerMessage(msg)) => {
|
||||||
for span in &msg.message.spans {
|
for span in &msg.message.spans {
|
||||||
if span.is_primary {
|
if span.is_primary {
|
||||||
let rust_path = root.join(&span.file_name);
|
let rust_path = root.join(&span.file_name);
|
||||||
|
|
||||||
let mapping_path = rust_path.with_extension("map.json");
|
let mapping_path = rust_path.with_extension("map.json");
|
||||||
|
|
||||||
if !fs::exists(&mapping_path).expect("Unable to check if map file exists") {
|
if !fs::exists(&mapping_path).expect("Unable to check if map file exists") {
|
||||||
diagnostics.push(MistDiagnostic::Rust(msg));
|
diagnostics.push(MistDiagnostic::Rust(msg));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
let map = mapping.entry(mapping_path.clone()).or_insert_with(() => {
|
||||||
let map = mapping.entry(mapping_path.clone()).or_insert_with(fn() {
|
|
||||||
let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file");
|
let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file");
|
||||||
|
|
||||||
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
|
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
|
||||||
});
|
});
|
||||||
|
|
||||||
let mist_file = map.mist_path.strip_prefix(&root);
|
let mist_file = map.mist_path.strip_prefix(&root);
|
||||||
|
let rust_lookup = rev_mapper::RustMap(span.line_end - 1, span.column_start - 1);
|
||||||
let (_, rev_mapper::MistMap(line, column)) =
|
match map.find(&rust_lookup) {
|
||||||
map.find(&rev_mapper::RustMap(span.line_end, span.column_start))
|
Some((_, rev_mapper::MistMap(line, column))) => {
|
||||||
.expect("Unable to find mapping");
|
|
||||||
|
|
||||||
let mist_msg = MistDiagnosticMessage {
|
let mist_msg = MistDiagnosticMessage {
|
||||||
message: format!(
|
message: format!("{}: {}",
|
||||||
"{}: {}",
|
|
||||||
msg.message.message,
|
msg.message.message,
|
||||||
span.label.clone().unwrap_or_default()
|
span.label.clone().unwrap_or_default()),
|
||||||
),
|
|
||||||
file_name: if let Ok(mist_file) = mist_file {
|
file_name: if let Ok(mist_file) = mist_file {
|
||||||
mist_file.to_string_lossy().to_string()
|
mist_file.to_string_lossy().to_string()
|
||||||
} else {
|
} else {
|
||||||
@@ -82,97 +72,76 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
|
|||||||
},
|
},
|
||||||
file_path: map.mist_path.clone(),
|
file_path: map.mist_path.clone(),
|
||||||
line: line,
|
line: line,
|
||||||
column: column
|
column: column,
|
||||||
};
|
};
|
||||||
|
|
||||||
match msg.message.level {
|
match msg.message.level {
|
||||||
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
|
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
|
||||||
diagnostics.push(MistDiagnostic::Error(mist_msg))
|
diagnostics.push(MistDiagnostic::Error(mist_msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
|
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
|
||||||
diagnostics.push(MistDiagnostic::Warning(mist_msg))
|
diagnostics.push(MistDiagnostic::Warning(mist_msg))
|
||||||
}
|
}
|
||||||
|
_ => {
|
||||||
_ => {}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
diagnostics.push(MistDiagnostic::Rust(msg));
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Message::BuildFinished(finish)) => {
|
Ok(Message::BuildFinished(finish)) => {
|
||||||
print_diagnostics(&diagnostics);
|
print_diagnostics(&diagnostics);
|
||||||
|
|
||||||
let mut raw_reader = reader.into_inner();
|
let mut raw_reader = reader.into_inner();
|
||||||
let mut stdout = std::io::stdout();
|
let mut stdout = std::io::stdout();
|
||||||
|
std::io::copy(&mut raw_reader, &mut stdout).map_err((v) => v.to_string()).expect("(Mist) Failed to copy IO");
|
||||||
std::io::copy(&mut raw_reader, &mut stdout)
|
|
||||||
.map_err(fn(v) -> v.to_string())
|
|
||||||
.expect("(Mist) Failed to copy IO");
|
|
||||||
|
|
||||||
command.wait().unwrap();
|
command.wait().unwrap();
|
||||||
|
|
||||||
return finish.success;
|
return finish.success;
|
||||||
}
|
}
|
||||||
|
Ok(Message::TextLine(text)) => println!("{text}"),
|
||||||
Ok(Message::TextLine(text)) => println!("{text}");
|
_ => {
|
||||||
_ => {}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void print_diagnostics(diagnostics *Vec<MistDiagnostic>) {
|
pub void print_diagnostics(Vec<MistDiagnostic>& diagnostics)
|
||||||
|
{
|
||||||
let mut files = HashMap::new();
|
let mut files = HashMap::new();
|
||||||
|
|
||||||
for diag in diagnostics {
|
for diag in diagnostics {
|
||||||
match diag {
|
match diag {
|
||||||
MistDiagnostic::Error(msg) => {
|
MistDiagnostic::Error(msg) => {
|
||||||
let line = get_line(&mut files, &msg);
|
let line = get_line(&mut files, &msg);
|
||||||
|
println!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
|
||||||
println!(
|
|
||||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
|
|
||||||
msg.file_name,
|
msg.file_name,
|
||||||
msg.line,
|
msg.line,
|
||||||
msg.column,
|
msg.column,
|
||||||
msg.message,
|
msg.message,
|
||||||
line.unwrap_or_default(),
|
line.unwrap_or_default(),)
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MistDiagnostic::Warning(msg) => {
|
MistDiagnostic::Warning(msg) => {
|
||||||
let line = get_line(&mut files, &msg);
|
let line = get_line(&mut files, &msg);
|
||||||
|
println!("\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
|
||||||
println!(
|
|
||||||
"\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
|
|
||||||
msg.file_name,
|
msg.file_name,
|
||||||
msg.line,
|
msg.line,
|
||||||
msg.column,
|
msg.column,
|
||||||
msg.message,
|
msg.message,
|
||||||
line.unwrap_or_default(),
|
line.unwrap_or_default(),)
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
MistDiagnostic::Rust(rs) => println!("{rs}"),
|
||||||
MistDiagnostic::Rust(rs) => println!("{rs}");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn Option<String> get_line(
|
pub Option<String> get_line(HashMap<PathBuf, Vec<String>> mut& files, MistDiagnosticMessage& msg)
|
||||||
files *mut HashMap<PathBuf, Vec<String>>,
|
{
|
||||||
msg *MistDiagnosticMessage,
|
|
||||||
) {
|
|
||||||
let src_path = msg.file_path.clone();
|
let src_path = msg.file_path.clone();
|
||||||
|
let lines = files.entry(src_path.clone()).or_insert_with(() => {
|
||||||
let lines = files.entry(src_path.clone()).or_insert_with(fn() {
|
fs::read_to_string(src_path).expect("Unable to read mist file").lines().into_iter().map(String::from).collect()
|
||||||
fs::read_to_string(src_path)
|
|
||||||
.expect("Unable to read mist file")
|
|
||||||
.lines()
|
|
||||||
.into_iter()
|
|
||||||
.map(String::from)
|
|
||||||
.collect()
|
|
||||||
});
|
});
|
||||||
|
lines.get(msg.line.saturating_sub(1)).map((v) => v.trim().to_string())
|
||||||
lines.get(msg.line - 1).map(fn(v) -> v.trim().to_string())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,75 +1,72 @@
|
|||||||
pub module modules;
|
pub module modules;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use std::process;
|
use std::process;
|
||||||
|
|
||||||
use crate::transpiler::MistConfig;
|
use crate::transpiler::MistConfig;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub class Module {
|
pub class Module
|
||||||
pub name String;
|
{
|
||||||
pub path PathBuf;
|
pub String name;
|
||||||
pub children Vec<Module>;
|
pub PathBuf path;
|
||||||
|
pub Vec<Module> children;
|
||||||
|
|
||||||
pub constructor(mist_path PathBuf, config *MistConfig) {
|
pub constructor(PathBuf mist_path, MistConfig& config)
|
||||||
|
{
|
||||||
self.children = Vec::new();
|
self.children = Vec::new();
|
||||||
self.name = mist_path.file_stem()
|
self.name = mist_path.file_stem().and_then((s) => s.to_str()).expect("Failed to get module name").to_string();
|
||||||
.and_then(fn(s) -> s.to_str())
|
|
||||||
.expect("Failed to get module name")
|
|
||||||
.to_string();
|
|
||||||
self.path = mist_path;
|
self.path = mist_path;
|
||||||
|
|
||||||
if self.path.is_dir() {
|
if self.path.is_dir() {
|
||||||
let dir = self.path.clone();
|
let dir = self.path.clone();
|
||||||
|
|
||||||
let pkg_gate = self.path.join("package.mist");
|
let pkg_gate = self.path.join("package.mist");
|
||||||
if pkg_gate.exists() {
|
if pkg_gate.exists() {
|
||||||
self.path = pkg_gate;
|
self.path = pkg_gate;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.scan_directory(&dir, config);
|
self.scan_directory(&dir, config);
|
||||||
} else if config.should_ignore(&self.path) {
|
} else if config.should_ignore(&self.path) {
|
||||||
let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf();
|
let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf();
|
||||||
|
|
||||||
self.scan_directory(&dir, config);
|
self.scan_directory(&dir, config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn void scan_directory(*mut self, search_dir *Path, config *MistConfig) {
|
void scan_directory(&mut self, Path& search_dir, MistConfig& config)
|
||||||
|
{
|
||||||
let entries = match fs::read_dir(search_dir) {
|
let entries = match fs::read_dir(search_dir) {
|
||||||
Ok(entries) => entries;
|
Ok(entries) => entries,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e);
|
eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e);
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
let entry = match entry {
|
let entry = match entry {
|
||||||
Ok(entry) => entry;
|
Ok(entry) => entry,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("error: failed to read directory entry\n {}", e);
|
eprintln!("error: failed to read directory entry\n {}", e);
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let child_path = entry.path();
|
let child_path = entry.path();
|
||||||
|
|
||||||
if child_path == self.path || child_path == config.package {
|
if child_path == self.path || child_path == config.package {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.children.push(Module::new(child_path, config));
|
self.children.push(Module::new(child_path, config));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bool is_package(*self) {
|
pub bool is_package(&self)
|
||||||
self.path.file_name().map(fn(v) -> v.to_str()).unwrap_or_default() == Some("package.mist")
|
{
|
||||||
|
self.path.file_name().map((v) => v.to_str()).unwrap_or_default() == Some("package.mist")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn PathBuf output_dir(*self, parent_dir *PathBuf) {
|
pub PathBuf output_dir(&self, PathBuf& parent_dir)
|
||||||
|
{
|
||||||
if self.path.is_dir() || self.is_package() {
|
if self.path.is_dir() || self.is_package() {
|
||||||
parent_dir.join(&self.name)
|
parent_dir.join(&self.name)
|
||||||
} else {
|
} else {
|
||||||
@@ -77,13 +74,15 @@ pub class Module {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn PathBuf output_path(*self, parent_dir *PathBuf, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
pub PathBuf output_path(&self, PathBuf& parent_dir, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
|
||||||
let name = if let Some((_, name)) = curr_mod_decl {
|
{
|
||||||
|
let name = if self.path.is_dir() || self.is_package() {
|
||||||
|
&self.name
|
||||||
|
} else if let Some((_, name)) = curr_mod_decl {
|
||||||
&name.0
|
&name.0
|
||||||
} else {
|
} else {
|
||||||
&self.name
|
&self.name
|
||||||
};
|
};
|
||||||
|
|
||||||
if self.path.is_dir() || self.is_package() {
|
if self.path.is_dir() || self.is_package() {
|
||||||
parent_dir.join(name).join("mod.rs")
|
parent_dir.join(name).join("mod.rs")
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+166
-164
@@ -1,170 +1,194 @@
|
|||||||
pub module transpiler;
|
pub module transpiler;
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use std::process;
|
use std::process;
|
||||||
|
|
||||||
use std::time;
|
use std::time;
|
||||||
use std::env;
|
|
||||||
|
|
||||||
use mist_parser::error;
|
use mist_parser::error;
|
||||||
|
|
||||||
use crate::modules;
|
use crate::modules;
|
||||||
|
|
||||||
use mist_codegen::GetRust;
|
use mist_codegen::GetRust;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct MistConfig {
|
pub struct MistConfig
|
||||||
pub package PathBuf,
|
{
|
||||||
pub packages Vec<PathBuf>,
|
pub PathBuf package;
|
||||||
pub main_mods String
|
pub Vec<PathBuf> packages;
|
||||||
|
pub Vec<PathBuf> include;
|
||||||
|
pub mist_parser::MistFmtConfig fmt;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MistConfig {
|
impl MistConfig
|
||||||
pub fn bool should_ignore(*self, path *Path) {
|
{
|
||||||
|
pub bool should_ignore(&self, Path& path)
|
||||||
|
{
|
||||||
if path == self.package {
|
if path == self.package {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
for pkg in &self.packages {
|
for pkg in &self.packages {
|
||||||
if path.ends_with(pkg) {
|
if path.ends_with(pkg) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Default for MistConfig {
|
|
||||||
fn Self default() {
|
impl Default for MistConfig
|
||||||
|
{
|
||||||
|
Self default()
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
package: PathBuf::from("main.mist"),
|
package: PathBuf::from("main.mist"),
|
||||||
packages: Vec::new(),
|
packages: Vec::new(),
|
||||||
main_mods: String::new(),
|
include: Vec::new(),
|
||||||
|
fmt: mist_parser::MistFmtConfig {
|
||||||
|
allman_bracket_style: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn PathBuf transpile() {
|
pub void transpile(Path& root)
|
||||||
|
{
|
||||||
|
println!("\x1b[32m\nTranspiling\x1b[0m \x1b[94m{:?}\x1b[0m", root.file_name().unwrap_or_default());
|
||||||
let start = time::Instant::now();
|
let start = time::Instant::now();
|
||||||
|
|
||||||
let root = env::current_dir().expect("Unable to find project root");
|
|
||||||
|
|
||||||
let toml_path = root.join("Mist.toml");
|
let toml_path = root.join("Mist.toml");
|
||||||
let src = root.join("src");
|
let src = root.join("src");
|
||||||
let out = root.join(".mist/src");
|
let out = root.join(".mist/src");
|
||||||
|
let toml_content = fs::read_to_string(&toml_path).unwrap_or_else((_) => panic!("Could not read file at {:?}", toml_path));
|
||||||
let toml_content = fs::read_to_string(&toml_path)
|
MistConfig mut config = toml::from_str(&toml_content).unwrap_or_else((_) => panic!("Failed to parse Mist.toml from {:?}", toml_path));
|
||||||
.unwrap_or_else(fn(_) -> panic!("Could not read file at {:?}", toml_path));
|
|
||||||
|
|
||||||
let mut config MistConfig = toml::from_str(&toml_content)
|
|
||||||
.unwrap_or_else(fn(_) -> panic!("Failed to parse Mist.toml from {:?}", toml_path));
|
|
||||||
|
|
||||||
for pkg in &mut config.packages {
|
for pkg in &mut config.packages {
|
||||||
*pkg = src.join(&*pkg);
|
*pkg = src.join(&*pkg);
|
||||||
}
|
}
|
||||||
|
|
||||||
config.package = src.join(&*config.package);
|
config.package = src.join(&*config.package);
|
||||||
|
let master = modules::Module::new(config.package.clone(), &config);
|
||||||
let master = modules::Module::new(
|
master.transpile(&out, &mut config, &mut String::new());
|
||||||
config.package.clone(),
|
|
||||||
&config
|
|
||||||
);
|
|
||||||
|
|
||||||
master.transpile(&out, &mut config);
|
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
let elapsed = start.elapsed();
|
||||||
|
println!("\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m", elapsed);
|
||||||
println!(
|
for incl in &config.include {
|
||||||
"\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m",
|
let incl = if incl.is_relative() { root.join(incl) } else { incl.clone() };
|
||||||
elapsed
|
if ends_with_star(&incl) {
|
||||||
);
|
let sub_crates = incl.parent().expect("Failed to get parent");
|
||||||
|
let entries = match fs::read_dir(sub_crates) {
|
||||||
root
|
Ok(entries) => entries,
|
||||||
}
|
|
||||||
|
|
||||||
impl modules::Module {
|
|
||||||
fn (bool, String) transpile(*self, parent_dir *PathBuf, config *mut MistConfig) {
|
|
||||||
if !self.path.is_dir() && self.path.extension().and_then(fn(v) -> v.to_str()) != Some("mist") {
|
|
||||||
let file_name = self.path.file_name()
|
|
||||||
.and_then(fn(s) -> s.to_str())
|
|
||||||
.expect("Failed to get file name");
|
|
||||||
|
|
||||||
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
|
|
||||||
|
|
||||||
return (true, String::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
let dir = self.output_dir(parent_dir);
|
|
||||||
|
|
||||||
let _ = fs::create_dir_all(&dir);
|
|
||||||
|
|
||||||
let mut output = String::new();
|
|
||||||
|
|
||||||
let mut child_changed = false;
|
|
||||||
|
|
||||||
for child in &self.children {
|
|
||||||
if !config.should_ignore(&child.path) {
|
|
||||||
let out = child.transpile(&dir, config);
|
|
||||||
if out.0 {
|
|
||||||
child_changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
output.push_str(&out.1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.path == config.package {
|
|
||||||
config.main_mods = output.clone();
|
|
||||||
} else if config.should_ignore(&self.path) {
|
|
||||||
output.push_str(&config.main_mods)
|
|
||||||
}
|
|
||||||
|
|
||||||
self.write_transpile(output, parent_dir, child_changed)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn (bool, String) write_transpile(*self, output String, parent_dir *PathBuf, child_changed bool) {
|
|
||||||
if self.path.is_dir() {
|
|
||||||
let output_file = self.output_path(parent_dir, &None);
|
|
||||||
|
|
||||||
if output.len() == 0 {
|
|
||||||
return (true, String::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
let res = fs::write(&output_file, output);
|
|
||||||
|
|
||||||
if res.is_err() {
|
|
||||||
eprintln!(
|
|
||||||
"error: failed to write output {}\n {}",
|
|
||||||
output_file.display(),
|
|
||||||
res.unwrap_err(),
|
|
||||||
);
|
|
||||||
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
(false, format!("pub mod {};\n", self.name))
|
|
||||||
} else {
|
|
||||||
let source = match fs::read_to_string(&self.path) {
|
|
||||||
Ok(s) => s;
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
|
eprintln!("error: failed to read directory {}\n {}", sub_crates.display(), e);
|
||||||
|
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
for sub_crate in entries {
|
||||||
|
if let Ok(sub_crate) = sub_crate {
|
||||||
|
let sub_crate = sub_crate.path();
|
||||||
|
if fs::exists(sub_crate.join("Mist.toml")).unwrap_or_default() {
|
||||||
|
transpile(&sub_crate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
transpile(&incl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ends_with_star(Path& path)
|
||||||
|
{
|
||||||
|
path.file_name().and_then((name) => name.to_str()).is_some_and((name) => name.ends_with("*"))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl modules::Module
|
||||||
|
{
|
||||||
|
(bool, String) transpile(&self, PathBuf& parent_dir, MistConfig mut& config, String mut& main_mods)
|
||||||
|
{
|
||||||
|
if !self.path.is_dir() && self.path.extension().and_then((v) => v.to_str()) != Some("mist") {
|
||||||
|
let file_name = self.path.file_name().and_then((s) => s.to_str()).expect("Failed to get file name");
|
||||||
|
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
|
||||||
|
return (true, String::new());
|
||||||
|
}
|
||||||
|
let dir = self.output_dir(parent_dir);
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
let mut output = String::new();
|
||||||
|
let mut child_changed = false;
|
||||||
|
for child in &self.children {
|
||||||
|
if !config.should_ignore(&child.path) {
|
||||||
|
let out = child.transpile(&dir, config, main_mods);
|
||||||
|
if out.0 {
|
||||||
|
child_changed = true;
|
||||||
|
}
|
||||||
|
output.push_str(&out.1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.path == config.package {
|
||||||
|
*main_mods = output.clone();
|
||||||
|
} else if config.should_ignore(&self.path) {
|
||||||
|
output.push_str(main_mods)
|
||||||
|
}
|
||||||
|
self.write_transpile(output, parent_dir, child_changed)
|
||||||
|
}
|
||||||
|
(bool, String) write_transpile(&self, String output, PathBuf& parent_dir, bool child_changed)
|
||||||
|
{
|
||||||
|
if self.path.is_dir() || self.is_package() {
|
||||||
|
let output_file = self.output_path(parent_dir, &None);
|
||||||
|
let final_output = if self.is_package() {
|
||||||
|
let source = match fs::read_to_string(&self.path) {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
|
||||||
|
let (result_path, gc, rust_code) = match transpile_code(&self.path, &source, output_file.clone(), &output, &curr_mod_decl) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
decode_err(&e, &self.path);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let map_path = result_path.with_extension("map.json");
|
||||||
|
if let Some(parent) = map_path.parent() {
|
||||||
|
let _ = fs::create_dir_all(parent);
|
||||||
|
}
|
||||||
|
fs::write(&map_path, serde_json::to_string(&gc.mapping).unwrap()).expect("Failed to write map file");
|
||||||
|
rust_code
|
||||||
|
} else {
|
||||||
|
if output.len() == 0 {
|
||||||
|
return (true, String::new());
|
||||||
|
}
|
||||||
|
output
|
||||||
|
};
|
||||||
|
let res = fs::write(&output_file, final_output);
|
||||||
|
if res.is_err() {
|
||||||
|
eprintln!("error: failed to write output {}\n {}",
|
||||||
|
output_file.display(),
|
||||||
|
res.unwrap_err(),);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
(false, format!("pub mod {};\n", self.name))
|
||||||
|
} else {
|
||||||
|
let source = match fs::read_to_string(&self.path) {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
|
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
|
||||||
|
|
||||||
let output_file = self.output_path(parent_dir, &curr_mod_decl);
|
let output_file = self.output_path(parent_dir, &curr_mod_decl);
|
||||||
|
|
||||||
let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache");
|
let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache");
|
||||||
|
|
||||||
if should_change || child_changed {
|
if should_change || child_changed {
|
||||||
transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl);
|
transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl);
|
||||||
}
|
}
|
||||||
|
|
||||||
(should_change, if let Some((vis, name)) = &curr_mod_decl {
|
(should_change, if let Some((vis, name)) = &curr_mod_decl {
|
||||||
format!("{}mod {};\n", vis.get_rust(), name.get_rust())
|
format!("{}mod {};\n", vis.get_rust(), name.get_rust())
|
||||||
} else {
|
} else {
|
||||||
@@ -174,126 +198,104 @@ impl modules::Module {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn std::io::Result<bool> is_source_newer(source *Path, output *Path) {
|
std::io::Result<bool> is_source_newer(Path& source, Path& output)
|
||||||
|
{
|
||||||
if !output.exists() {
|
if !output.exists() {
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
let source_time = fs::metadata(source)?.modified()?;
|
let source_time = fs::metadata(source)?.modified()?;
|
||||||
let output_time = fs::metadata(output)?.modified()?;
|
let output_time = fs::metadata(output)?.modified()?;
|
||||||
|
|
||||||
Ok(source_time > output_time)
|
Ok(source_time > output_time)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum TranspileError<'a> {
|
pub enum TranspileError<'a>
|
||||||
Parse(error::ParseError<'a, Vec<mist_parser::ast::TopLevel>>),
|
{
|
||||||
Semantic(Vec<mist_parser::semantics::SemanticError>)
|
Parse(error::ParseError<'a>);
|
||||||
|
Semantic(Vec<mist_parser::semantics::SemanticError>);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>>
|
pub Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>> transpile_code<'a>(PathBuf& path, str 'a& source, PathBuf mut output_file, str& mod_decl, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
|
||||||
transpile_code<'a>(path *PathBuf, source *'a str, mut output_file PathBuf, mod_decl *str, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
{
|
||||||
|
|
||||||
if let Some((_, name)) = &curr_mod_decl {
|
if let Some((_, name)) = &curr_mod_decl {
|
||||||
if output_file.file_name().map(fn(v) -> v.to_str()).unwrap_or_default() != Some("mod.rs") {
|
if output_file.file_name().map((v) => v.to_str()).unwrap_or_default() != Some("mod.rs") {
|
||||||
if let Some(ext) = output_file.extension().map(fn(e) -> e.to_owned()) {
|
if let Some(ext) = output_file.extension().map((e) => e.to_owned()) {
|
||||||
let mut new_name = std::ffi::OsString::from(&name.0);
|
let mut new_name = std::ffi::OsString::from(&name.0);
|
||||||
|
|
||||||
new_name.push(".");
|
new_name.push(".");
|
||||||
new_name.push(ext);
|
new_name.push(ext);
|
||||||
|
|
||||||
output_file.set_file_name(new_name);
|
output_file.set_file_name(new_name);
|
||||||
} else {
|
} else {
|
||||||
output_file.set_file_name(&name.0);
|
output_file.set_file_name(&name.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut gc = mist_codegen::RustCodegen::new(path.clone());
|
let mut gc = mist_codegen::RustCodegen::new(path.clone());
|
||||||
|
|
||||||
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
|
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
|
||||||
|
for i in &parsed.items {
|
||||||
for i in &parsed {
|
|
||||||
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
|
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
|
||||||
}
|
}
|
||||||
|
gc.generate(parsed.mod_attributes);
|
||||||
let output = gc.generate(parsed);
|
gc.add(mod_decl);
|
||||||
|
let output = gc.generate(parsed.items);
|
||||||
gc.mapping.shift_rust(mod_decl.lines().count() as isize, 0);
|
|
||||||
|
|
||||||
Ok((output_file, gc, output))
|
Ok((output_file, gc, output))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void transpile_file(path *PathBuf, source *str, output_file PathBuf, mod_decl *str, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) {
|
pub void transpile_file(PathBuf& path, str& source, PathBuf output_file, str& mod_decl, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
|
||||||
|
{
|
||||||
let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) {
|
let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) {
|
||||||
Ok(output) => output;
|
Ok(output) => output,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
decode_err(&e, path);
|
decode_err(&e, path);
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if let Some(parent) = output_file.parent() {
|
||||||
let res = fs::write(&output_file, format!("{mod_decl}{output}"));
|
let _ = fs::create_dir_all(parent);
|
||||||
|
}
|
||||||
|
let res = fs::write(&output_file, output);
|
||||||
let output_file_map = output_file.with_extension("map.json");
|
let output_file_map = output_file.with_extension("map.json");
|
||||||
|
|
||||||
let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap());
|
let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap());
|
||||||
|
|
||||||
if res_map.is_err() {
|
if res_map.is_err() {
|
||||||
eprintln!(
|
eprintln!("error: failed to write mapping output {}\n {}",
|
||||||
"error: failed to write mapping output {}\n {}",
|
|
||||||
output_file_map.display(),
|
output_file_map.display(),
|
||||||
res.as_ref().unwrap_err(),
|
res_map.as_ref().unwrap_err(),);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if res.is_err() {
|
if res.is_err() {
|
||||||
eprintln!(
|
eprintln!("error: failed to write output {}\n {}",
|
||||||
"error: failed to write output {}\n {}",
|
|
||||||
output_file.display(),
|
output_file.display(),
|
||||||
res.as_ref().unwrap_err(),
|
res.as_ref().unwrap_err(),);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if res_map.is_err() || res.is_err() {
|
if res_map.is_err() || res.is_err() {
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void decode_err<'a>(err *TranspileError<'a>, path *PathBuf) {
|
pub void decode_err<'a>(TranspileError<'a>& err, PathBuf& path)
|
||||||
|
{
|
||||||
let curr_dir = std::env::current_dir().unwrap();
|
let curr_dir = std::env::current_dir().unwrap();
|
||||||
|
|
||||||
match err {
|
match err {
|
||||||
TranspileError::Semantic(e_list) => {
|
TranspileError::Semantic(e_list) => {
|
||||||
for e in e_list {
|
for e in e_list {
|
||||||
eprintln!(
|
eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
|
||||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
|
|
||||||
path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
||||||
e.line,
|
e.line,
|
||||||
e.column,
|
e.column,
|
||||||
e.error_message,
|
e.error_message,);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
TranspileError::Parse(e) => {
|
TranspileError::Parse(e) => {
|
||||||
match e {
|
match e {
|
||||||
error::ParseError::Ast(e) => {
|
error::ParseError::Ast(e) => {
|
||||||
let start_pos = e.span.start_pos().line_col();
|
let start_pos = e.span.start_pos().line_col();
|
||||||
|
|
||||||
let span = e.span.as_str();
|
let span = e.span.as_str();
|
||||||
|
eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
||||||
eprintln!(
|
|
||||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
|
||||||
path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
|
||||||
start_pos.0,
|
start_pos.0,
|
||||||
start_pos.1,
|
start_pos.1,
|
||||||
e.error_message,
|
e.error_message,
|
||||||
span,
|
span,
|
||||||
if span.ends_with("\n") { "" } else { "\n" },
|
if span.ends_with("\n") { "" } else { "\n" },
|
||||||
"^".repeat(span.trim().len()),
|
"^".repeat(span.trim().len()),);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
error::ParseError::PreAst(e) => {
|
error::ParseError::PreAst(e) => {
|
||||||
eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e);
|
eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mist-parser"
|
name = "mist-parser"
|
||||||
version = "0.3.5-alpha.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "The Mist programming language parser"
|
description = "The Mist programming language parser"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ pub enum Postfix {
|
|||||||
delimiter: MacroDelimiter,
|
delimiter: MacroDelimiter,
|
||||||
},
|
},
|
||||||
StructCall(Vec<(Identifier, Option<Expression>)>),
|
StructCall(Vec<(Identifier, Option<Expression>)>),
|
||||||
Assign(String, Box<Expression>),
|
|
||||||
Index(Expression),
|
Index(Expression),
|
||||||
As(TypeExpr),
|
As(TypeExpr),
|
||||||
Increment,
|
Increment,
|
||||||
@@ -97,16 +96,6 @@ pub enum Generic {
|
|||||||
Type(TypeExpr),
|
Type(TypeExpr),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Expression {
|
|
||||||
pub fn is_block(&self) -> bool {
|
|
||||||
if let Expression::Statement(stmt) = self {
|
|
||||||
stmt.is_block()
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Path> for ExprPath {
|
impl From<Path> for ExprPath {
|
||||||
fn from(path: Path) -> Self {
|
fn from(path: Path) -> Self {
|
||||||
Self(
|
Self(
|
||||||
@@ -120,3 +109,23 @@ impl From<Path> for ExprPath {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Expression {
|
||||||
|
pub fn is_semicolon_required(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::Statement(v) => match &**v {
|
||||||
|
Statement::TopLevel(_) => false,
|
||||||
|
stmt => !stmt.is_block(),
|
||||||
|
},
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_block(&self) -> bool {
|
||||||
|
if let Expression::Statement(stmt) = self {
|
||||||
|
stmt.is_block()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,15 +18,18 @@ pub struct Identifier(pub String);
|
|||||||
pub struct ParamList(pub Vec<VarDecl>);
|
pub struct ParamList(pub Vec<VarDecl>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub enum Lifetime {
|
pub enum FnKind {
|
||||||
Lifetime(Identifier),
|
Fn,
|
||||||
Unsafe,
|
UnsafeFn,
|
||||||
|
FnClosure,
|
||||||
|
FnOnce,
|
||||||
|
FnMut,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||||
pub enum TypeExpr {
|
pub enum TypeExpr {
|
||||||
Ref {
|
Ref {
|
||||||
lifetime: Option<Lifetime>,
|
lifetime: Option<Identifier>,
|
||||||
mutable: bool,
|
mutable: bool,
|
||||||
ty: Box<TypeExpr>,
|
ty: Box<TypeExpr>,
|
||||||
},
|
},
|
||||||
@@ -38,7 +41,13 @@ pub enum TypeExpr {
|
|||||||
Path(Path, Option<Generics>),
|
Path(Path, Option<Generics>),
|
||||||
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
|
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
|
||||||
Tuple(Vec<TypeExpr>),
|
Tuple(Vec<TypeExpr>),
|
||||||
Lifetime(Identifier),
|
Void,
|
||||||
|
Fn {
|
||||||
|
kind: FnKind,
|
||||||
|
return_type: Box<TypeExpr>,
|
||||||
|
params: Vec<TypeExpr>,
|
||||||
|
},
|
||||||
|
Array(Box<TypeExpr>, Option<isize>)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
@@ -51,7 +60,7 @@ pub struct Spanned<T> {
|
|||||||
impl From<GenericDecl> for Generic {
|
impl From<GenericDecl> for Generic {
|
||||||
fn from(value: GenericDecl) -> Self {
|
fn from(value: GenericDecl) -> Self {
|
||||||
match value {
|
match value {
|
||||||
GenericDecl::Lifetime(life) => Generic::Lifetime(life),
|
GenericDecl::Lifetime(life, _) => Generic::Lifetime(life),
|
||||||
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
|
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ pub struct Block {
|
|||||||
pub enum Statement {
|
pub enum Statement {
|
||||||
UnsafeBlock(Block),
|
UnsafeBlock(Block),
|
||||||
Block(Block),
|
Block(Block),
|
||||||
|
TopLevel(Box<TopLevel>),
|
||||||
If {
|
If {
|
||||||
initial: StatementBranch,
|
initial: StatementBranch,
|
||||||
else_if: Vec<StatementBranch>,
|
else_if: Vec<StatementBranch>,
|
||||||
@@ -43,8 +44,10 @@ pub struct MatchItem(pub Vec<Pattern>, pub Expression);
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct VarDecl {
|
pub struct VarDecl {
|
||||||
pub name: Pattern,
|
|
||||||
pub type_: Option<TypeExpr>,
|
pub type_: Option<TypeExpr>,
|
||||||
|
pub name: Pattern,
|
||||||
|
pub true_type: bool,
|
||||||
|
pub tuple_names: Vec<Pattern>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
|||||||
@@ -28,8 +28,18 @@ pub struct TopLevel(pub Spanned<TopLevelKind>, pub Vec<Attribute>);
|
|||||||
pub enum TopLevelKind {
|
pub enum TopLevelKind {
|
||||||
ModAttribute,
|
ModAttribute,
|
||||||
Import(Visibility, Path),
|
Import(Visibility, Path),
|
||||||
|
IncludeGlobal(Path),
|
||||||
|
IncludeUse(Visibility, Path),
|
||||||
|
IncludeLocal(String),
|
||||||
DeclareModule(Visibility, Identifier),
|
DeclareModule(Visibility, Identifier),
|
||||||
ImplDecl(ImplDecl),
|
ImplDecl(ImplDecl),
|
||||||
|
StaticDecl(VarDeclStmt),
|
||||||
|
ConstDecl(VarDeclStmt),
|
||||||
|
TypeAlias {
|
||||||
|
name: Identifier,
|
||||||
|
generics: Option<GenericsDecl>,
|
||||||
|
ty: TypeExpr,
|
||||||
|
},
|
||||||
TraitDecl {
|
TraitDecl {
|
||||||
visibility: Visibility,
|
visibility: Visibility,
|
||||||
name: Identifier,
|
name: Identifier,
|
||||||
@@ -49,6 +59,12 @@ pub enum TopLevelKind {
|
|||||||
generics: GenericsDecl,
|
generics: GenericsDecl,
|
||||||
fields: Vec<Spanned<FieldDecl>>,
|
fields: Vec<Spanned<FieldDecl>>,
|
||||||
},
|
},
|
||||||
|
StructDeclTupleUnit {
|
||||||
|
visibility: Visibility,
|
||||||
|
name: Identifier,
|
||||||
|
generics: GenericsDecl,
|
||||||
|
unit: Option<Vec<Spanned<TypeExpr>>>,
|
||||||
|
},
|
||||||
FunctionDecl(FunctionDecl),
|
FunctionDecl(FunctionDecl),
|
||||||
ClassDecl {
|
ClassDecl {
|
||||||
visibility: Visibility,
|
visibility: Visibility,
|
||||||
@@ -72,8 +88,8 @@ pub struct GenericsDecl(pub Vec<GenericDecl>);
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub enum GenericDecl {
|
pub enum GenericDecl {
|
||||||
Lifetime(Identifier),
|
Lifetime(Identifier, Vec<Generic>),
|
||||||
Type(Identifier, Vec<TypeExpr>),
|
Type(Identifier, Vec<Generic>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
@@ -97,11 +113,13 @@ pub struct Override(pub Option<ExprPath>);
|
|||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct FunctionDecl {
|
pub struct FunctionDecl {
|
||||||
pub visibility: Visibility,
|
pub visibility: Visibility,
|
||||||
pub is_override: Option<Override>,
|
pub is_virtual: bool,
|
||||||
|
pub return_type: Option<TypeExpr>,
|
||||||
pub name: Identifier,
|
pub name: Identifier,
|
||||||
pub generics: GenericsDecl,
|
pub generics: GenericsDecl,
|
||||||
|
pub self_param: Option<(bool, Option<Identifier>, bool)>,
|
||||||
pub params: ParamList,
|
pub params: ParamList,
|
||||||
pub return_type: Option<TypeExpr>,
|
pub is_override: Option<Override>,
|
||||||
pub body: Option<Block>,
|
pub body: Option<Block>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,18 +143,3 @@ pub struct FieldDeclStmt {
|
|||||||
pub decl: FieldDecl,
|
pub decl: FieldDecl,
|
||||||
pub init: Option<Expression>,
|
pub init: Option<Expression>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FunctionDecl {
|
|
||||||
pub fn is_using_self(&self) -> bool {
|
|
||||||
match self.params.0.get(0) {
|
|
||||||
Some(VarDecl { name, .. }) => {
|
|
||||||
if let Pattern::Path(_, v) = name {
|
|
||||||
v.0.len() == 1 && v.0[0].0 == "self"
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+17
-74
@@ -4,20 +4,19 @@ use pest::iterators::Pair;
|
|||||||
|
|
||||||
use crate::Rule;
|
use crate::Rule;
|
||||||
|
|
||||||
pub type AstResult<'a, T, ET = T> = Result<T, AstError<'a, ET>>;
|
pub type AstResult<'a, T> = Result<T, AstError<'a>>;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum ParseError<'a, T> {
|
pub enum ParseError<'a> {
|
||||||
PreAst(pest::error::Error<Rule>),
|
PreAst(pest::error::Error<Rule>),
|
||||||
Ast(AstError<'a, T>),
|
Ast(AstError<'a>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AstError<'a, T> {
|
pub struct AstError<'a> {
|
||||||
pub span: pest::Span<'a>,
|
pub span: pest::Span<'a>,
|
||||||
pub error_code: ErrorCode,
|
pub error_code: ErrorCode,
|
||||||
pub error_message: String,
|
pub error_message: String,
|
||||||
pub recovered: Option<T>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -25,32 +24,24 @@ pub enum ErrorCode {
|
|||||||
InvalidStatement,
|
InvalidStatement,
|
||||||
AstGenBug,
|
AstGenBug,
|
||||||
Module,
|
Module,
|
||||||
|
NumberParse,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
|
impl From<pest::error::Error<Rule>> for ParseError<'_> {
|
||||||
fn from(value: pest::error::Error<Rule>) -> Self {
|
fn from(value: pest::error::Error<Rule>) -> Self {
|
||||||
Self::PreAst(value)
|
Self::PreAst(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T> From<AstError<'a, T>> for ParseError<'a, T> {
|
impl<'a> From<AstError<'a>> for ParseError<'a> {
|
||||||
fn from(value: AstError<'a, T>) -> Self {
|
fn from(value: AstError<'a>) -> Self {
|
||||||
Self::Ast(value)
|
Self::Ast(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, F> AstError<'a, F> {
|
impl<'a> AstError<'a> {
|
||||||
pub fn get<T>(self) -> AstError<'a, T> {
|
|
||||||
AstError {
|
|
||||||
span: self.span,
|
|
||||||
error_code: self.error_code,
|
|
||||||
error_message: self.error_message,
|
|
||||||
recovered: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T, F> {
|
pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T> {
|
||||||
let loc = std::panic::Location::caller();
|
let loc = std::panic::Location::caller();
|
||||||
|
|
||||||
Err(Self {
|
Err(Self {
|
||||||
@@ -62,7 +53,6 @@ impl<'a, F> AstError<'a, F> {
|
|||||||
loc.file(),
|
loc.file(),
|
||||||
loc.line(),
|
loc.line(),
|
||||||
),
|
),
|
||||||
recovered: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,21 +62,6 @@ pub trait IntoErr<T, FA, FR> {
|
|||||||
fn get_map(self, m: impl Fn(FA) -> FR) -> 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 {
|
pub trait GetLength {
|
||||||
fn len(&self) -> usize;
|
fn len(&self) -> usize;
|
||||||
}
|
}
|
||||||
@@ -97,24 +72,24 @@ impl<T, E> GetLength for Result<Vec<T>, E> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn collect_recovered<'a, T: Debug, ET>(
|
pub fn collect_recovered<'a, T: Debug>(
|
||||||
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
||||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
) -> AstResult<'a, Vec<T>>
|
||||||
where
|
where
|
||||||
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, ET>>,
|
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a>>,
|
||||||
{
|
{
|
||||||
collect_recovered_map(pairs, T::try_from)
|
collect_recovered_map(pairs, T::try_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn collect_recovered_map<'a, T: Debug, F, ET>(
|
pub fn collect_recovered_map<'a, T: Debug, F>(
|
||||||
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
) -> AstResult<'a, Vec<T>>
|
||||||
where
|
where
|
||||||
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T, ET>,
|
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T>,
|
||||||
{
|
{
|
||||||
let mut items = Vec::new();
|
let mut items = Vec::new();
|
||||||
let mut last_error: Option<AstError<'a, ET>> = None;
|
let mut last_error: Option<AstError<'a>> = None;
|
||||||
|
|
||||||
for pair in pairs {
|
for pair in pairs {
|
||||||
match f(pair) {
|
match f(pair) {
|
||||||
@@ -130,39 +105,7 @@ where
|
|||||||
span: ast_err.span,
|
span: ast_err.span,
|
||||||
error_code: ast_err.error_code,
|
error_code: ast_err.error_code,
|
||||||
error_message: ast_err.error_message,
|
error_message: ast_err.error_message,
|
||||||
recovered: Some(items),
|
|
||||||
}),
|
}),
|
||||||
None => Ok(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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
|
|||||||
keyword = {
|
keyword = {
|
||||||
"if"
|
"if"
|
||||||
| "else"
|
| "else"
|
||||||
|
| "fn"
|
||||||
| "for"
|
| "for"
|
||||||
| "while"
|
| "while"
|
||||||
| "match"
|
| "match"
|
||||||
@@ -23,6 +24,7 @@ keyword = {
|
|||||||
| "class"
|
| "class"
|
||||||
| "trait"
|
| "trait"
|
||||||
| "impl"
|
| "impl"
|
||||||
|
| "use"
|
||||||
| "pub"
|
| "pub"
|
||||||
| "mut"
|
| "mut"
|
||||||
| "let"
|
| "let"
|
||||||
@@ -30,9 +32,11 @@ keyword = {
|
|||||||
| "false"
|
| "false"
|
||||||
| "dyn"
|
| "dyn"
|
||||||
| "loop"
|
| "loop"
|
||||||
| "fn"
|
|
||||||
| "unsafe"
|
| "unsafe"
|
||||||
| "override"
|
| "override"
|
||||||
|
| "const"
|
||||||
|
| "type"
|
||||||
|
| "virtual"
|
||||||
}
|
}
|
||||||
|
|
||||||
identifier = @{
|
identifier = @{
|
||||||
@@ -82,12 +86,11 @@ module_program = {
|
|||||||
|
|
||||||
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
||||||
mutable = { "mut" }
|
mutable = { "mut" }
|
||||||
unsafe_kw = { "unsafe" }
|
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// GENERICS
|
// GENERICS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
generic_decl = { lifetime | (identifier ~ (":" ~ generic ~ ("+" ~ generic)*)?) }
|
generic_decl = { (lifetime | identifier) ~ (":" ~ generic ~ ("+" ~ generic)*)? }
|
||||||
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
|
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
|
||||||
|
|
||||||
generic = { lifetime | type_expr }
|
generic = { lifetime | type_expr }
|
||||||
@@ -105,18 +108,46 @@ path_type = {
|
|||||||
static_path ~ generics?
|
static_path ~ generics?
|
||||||
}
|
}
|
||||||
|
|
||||||
ref_lifetime = { lifetime | unsafe_kw }
|
unsafe_ref_type = {
|
||||||
|
mutable? ~ "unsafe" ~ "*"
|
||||||
|
}
|
||||||
|
|
||||||
ref_type = {
|
ref_type = {
|
||||||
"*" ~ ref_lifetime? ~ mutable? ~ type_expr
|
mutable? ~ lifetime? ~ "&"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn_kind_fn = { "fn" }
|
||||||
|
fn_kind_unsafe = { "unsafe" ~ "fn" }
|
||||||
|
fn_kind_closure = { "Fn" }
|
||||||
|
fn_kind_once = { "FnOnce" }
|
||||||
|
fn_kind_mut = { "FnMut" }
|
||||||
|
|
||||||
|
fn_kind = _{
|
||||||
|
fn_kind_fn
|
||||||
|
| fn_kind_unsafe
|
||||||
|
| fn_kind_once
|
||||||
|
| fn_kind_mut
|
||||||
|
| fn_kind_closure
|
||||||
|
}
|
||||||
|
|
||||||
|
fn_type = {
|
||||||
|
fn_kind ~ "(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
dyn_type = {
|
dyn_type = {
|
||||||
"dyn" ~ type_expr
|
"dyn" ~ type_expr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void_type = {
|
||||||
|
"void"
|
||||||
|
}
|
||||||
|
|
||||||
|
array_type = {
|
||||||
|
"[" ~ integer? ~ "]"
|
||||||
|
}
|
||||||
|
|
||||||
type_expr = {
|
type_expr = {
|
||||||
(path_type | tuple_type | ref_type | dyn_type)
|
(void_type | path_type | tuple_type | dyn_type) ~ (unsafe_ref_type | ref_type | fn_type | array_type)*
|
||||||
}
|
}
|
||||||
|
|
||||||
lifetime = {
|
lifetime = {
|
||||||
@@ -141,7 +172,7 @@ literal = {
|
|||||||
etc_pattern = { ".." }
|
etc_pattern = { ".." }
|
||||||
|
|
||||||
multi_pat_template = _{
|
multi_pat_template = _{
|
||||||
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))*)?
|
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))* ~ ","?)?
|
||||||
}
|
}
|
||||||
|
|
||||||
tuple_pattern = {
|
tuple_pattern = {
|
||||||
@@ -199,20 +230,25 @@ attributes = {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
// DECLARATION HELPERS
|
// DECLARATION HELPERS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
as_kw = { "as" }
|
||||||
|
|
||||||
var_decl = {
|
var_decl = {
|
||||||
"let" ~ pattern ~ type_expr?
|
("let" ~ pattern ~ ("," ~ pattern)*)
|
||||||
|
| (type_expr ~ as_kw ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)+))
|
||||||
|
| (type_expr ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)*))
|
||||||
}
|
}
|
||||||
|
|
||||||
field = {
|
field = {
|
||||||
visibility? ~ identifier ~ type_expr
|
visibility? ~ type_expr ~ identifier
|
||||||
}
|
}
|
||||||
|
|
||||||
param = {
|
param = {
|
||||||
pattern ~ type_expr?
|
(type_expr ~ pattern)
|
||||||
|
| pattern
|
||||||
}
|
}
|
||||||
|
|
||||||
field_list = {
|
field_list = {
|
||||||
(field ~ ("," ~ field)* ~ ","?)?
|
(field ~ ";")*
|
||||||
}
|
}
|
||||||
|
|
||||||
param_list = {
|
param_list = {
|
||||||
@@ -223,6 +259,18 @@ param_list = {
|
|||||||
// IMPORTS / MODULES
|
// IMPORTS / MODULES
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
|
include_global = {
|
||||||
|
"#" ~ "include" ~ "<" ~ identifier ~ ("/" ~ identifier)* ~ ">"
|
||||||
|
}
|
||||||
|
|
||||||
|
include_use_global = {
|
||||||
|
visibility? ~ "#" ~ "use" ~ static_path ~ semicolon
|
||||||
|
}
|
||||||
|
|
||||||
|
include_local = {
|
||||||
|
"#" ~ "include" ~ string_lit
|
||||||
|
}
|
||||||
|
|
||||||
import = {
|
import = {
|
||||||
visibility? ~ "use" ~ static_path ~ semicolon
|
visibility? ~ "use" ~ static_path ~ semicolon
|
||||||
}
|
}
|
||||||
@@ -236,7 +284,11 @@ declare_module = {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
struct_decl = {
|
struct_decl = {
|
||||||
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ "{" ~ field_list? ~ "}"
|
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ "{" ~ field_list ~ "}"
|
||||||
|
}
|
||||||
|
|
||||||
|
tuple_struct_decl = {
|
||||||
|
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ tuple_type? ~ ";"
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -261,12 +313,8 @@ enum_field = _{
|
|||||||
| enum_named
|
| enum_named
|
||||||
}
|
}
|
||||||
|
|
||||||
enum_fields = _{
|
|
||||||
enum_field ~ ("," ~ enum_field)* ~ ","?
|
|
||||||
}
|
|
||||||
|
|
||||||
enum_decl = {
|
enum_decl = {
|
||||||
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields ~ "}"
|
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ (enum_field ~ ";")* ~ "}"
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -286,7 +334,7 @@ class_field = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self_param = {
|
self_param = {
|
||||||
(deref_px ~ lifetime?)? ~ mutable? ~ "self"
|
(ref_px ~ lifetime?)? ~ mutable? ~ "self"
|
||||||
}
|
}
|
||||||
|
|
||||||
method_args = _{
|
method_args = _{
|
||||||
@@ -330,19 +378,32 @@ trait_decl = {
|
|||||||
// FUNCTIONS
|
// FUNCTIONS
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
|
virtual_kw = { "virtual" }
|
||||||
|
|
||||||
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
|
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
|
||||||
|
|
||||||
function_decl = {
|
function_decl = {
|
||||||
visibility? ~ "fn" ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
|
visibility? ~ virtual_kw? ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ======================================================
|
||||||
|
// CONSTANTS / STATIC
|
||||||
|
// ======================================================
|
||||||
|
const_decl = { "const" ~ var_decl_statement ~ ";" }
|
||||||
|
static_decl = { "static" ~ var_decl_statement ~ ";" }
|
||||||
|
|
||||||
|
// ======================================================
|
||||||
|
// Type aliases
|
||||||
|
// ======================================================
|
||||||
|
type_alias = { "type" ~ identifier ~ generics_decl? ~ "=" ~ type_expr ~ ";" }
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
// TOP LEVEL
|
// TOP LEVEL
|
||||||
// ======================================================
|
// ======================================================
|
||||||
|
|
||||||
top_level = {
|
top_level = {
|
||||||
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | declare_module | function_decl))
|
mod_attribute
|
||||||
| mod_attribute
|
| (attributes ~ (include_global | include_local | include_use_global | import | impl_for_decl | impl_decl | trait_decl | struct_decl | tuple_struct_decl | enum_decl | class_decl | declare_module | function_decl | const_decl | static_decl | type_alias))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ======================================================
|
// ======================================================
|
||||||
@@ -363,6 +424,7 @@ statement_list = {
|
|||||||
|
|
||||||
statement = _{
|
statement = _{
|
||||||
control_flow
|
control_flow
|
||||||
|
| top_level
|
||||||
| (expr ~ semicolon)
|
| (expr ~ semicolon)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,7 +511,7 @@ loop_stmt = {
|
|||||||
pattern_list = { pattern ~ ("|" ~ pattern)* }
|
pattern_list = { pattern ~ ("|" ~ pattern)* }
|
||||||
|
|
||||||
match_item = {
|
match_item = {
|
||||||
pattern_list ~ "=>" ~ statement
|
pattern_list ~ "=>" ~ (block | (expr ~ ","))
|
||||||
}
|
}
|
||||||
|
|
||||||
match_stmt = {
|
match_stmt = {
|
||||||
@@ -465,8 +527,8 @@ match_stmt = {
|
|||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
closure = {
|
closure = {
|
||||||
"fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ block
|
("(" ~ param_list ~ ")" ~ "=>" ~ expr)
|
||||||
| "fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ "->" ~ expr
|
| (type_expr ~ "(" ~ param_list ~ ")" ~ "=>" ~ expr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|||||||
+22
-61
@@ -9,42 +9,46 @@ pub mod semantics;
|
|||||||
|
|
||||||
use ast::*;
|
use ast::*;
|
||||||
|
|
||||||
use crate::error::{IntoErr, ParseError};
|
use crate::error::ParseError;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[grammar = "./src/grammar.pest"]
|
#[grammar = "./src/grammar.pest"]
|
||||||
pub struct MistParser;
|
pub struct MistParser;
|
||||||
|
|
||||||
pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<TopLevel>>> {
|
pub struct Program {
|
||||||
|
pub mod_attributes: Vec<TopLevel>,
|
||||||
|
pub items: Vec<TopLevel>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct MistFmtConfig {
|
||||||
|
pub allman_bracket_style: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse<'a>(source: &'a str) -> Result<Program, ParseError<'a>> {
|
||||||
let mut pairs = MistParser::parse(Rule::program, source)?;
|
let mut pairs = MistParser::parse(Rule::program, source)?;
|
||||||
|
|
||||||
let mut statements = vec![];
|
let mut statements = vec![];
|
||||||
|
|
||||||
let mut analyzer = error::AstErrorAnalyzer(None);
|
|
||||||
|
|
||||||
for pair in pairs.next().unwrap().into_inner() {
|
for pair in pairs.next().unwrap().into_inner() {
|
||||||
if pair.as_rule() != Rule::EOI {
|
if pair.as_rule() != Rule::EOI {
|
||||||
statements.push(analyzer.get(TopLevel::try_from(pair)).get()?);
|
statements.push(TopLevel::try_from(pair)?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match analyzer.build(statements) {
|
let (mod_attributes, items): (Vec<_>, Vec<_>) = statements
|
||||||
Ok(v) => Ok(v),
|
.into_iter()
|
||||||
Err(e) => {
|
.partition(|item| matches!(item.0.item, TopLevelKind::ModAttribute));
|
||||||
let rec = e.recovered.clone();
|
|
||||||
|
|
||||||
let mut e2 = e.get();
|
Ok(Program {
|
||||||
|
items,
|
||||||
e2.recovered = rec;
|
mod_attributes,
|
||||||
|
})
|
||||||
Err(ParseError::Ast(e2))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_module<'a>(
|
pub fn parse_module<'a>(
|
||||||
source: &'a str,
|
source: &'a str,
|
||||||
) -> Result<Option<(Visibility, Identifier)>, ParseError<'a, Option<(Visibility, Identifier)>>> {
|
) -> Result<Option<(Visibility, Identifier)>, ParseError<'a>> {
|
||||||
let mut pairs = MistParser::parse(Rule::module_program, source)?;
|
let mut pairs = MistParser::parse(Rule::module_program, source)?;
|
||||||
|
|
||||||
if let Some(v) = pairs
|
if let Some(v) = pairs
|
||||||
@@ -53,8 +57,7 @@ pub fn parse_module<'a>(
|
|||||||
.into_inner()
|
.into_inner()
|
||||||
.next()
|
.next()
|
||||||
.map(TopLevel::try_from)
|
.map(TopLevel::try_from)
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
{
|
{
|
||||||
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
|
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
|
||||||
Ok(Some((vis.clone(), name.clone())))
|
Ok(Some((vis.clone(), name.clone())))
|
||||||
@@ -76,49 +79,7 @@ macro_rules! ast_ensure {
|
|||||||
span: $pair.as_span(),
|
span: $pair.as_span(),
|
||||||
error_code: crate::error::ErrorCode::AstGenBug,
|
error_code: crate::error::ErrorCode::AstGenBug,
|
||||||
error_message: format!("Possible bug: expected {:?}, got {:?}", $rule, $pair.as_rule()),
|
error_message: format!("Possible bug: expected {:?}, got {:?}", $rule, $pair.as_rule()),
|
||||||
recovered: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! ast_expr {
|
|
||||||
(use $r:expr, $($v:expr),* $(,)?) => {{
|
|
||||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
|
||||||
|
|
||||||
$(
|
|
||||||
analyzer.get($v).get()?;
|
|
||||||
)*
|
|
||||||
|
|
||||||
analyzer.build($r)
|
|
||||||
}};
|
|
||||||
|
|
||||||
($($item:ident)::+ { $($k:ident: $v:expr),* $(,)? }) => {{
|
|
||||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
|
||||||
|
|
||||||
let v = $($item)::+ { $($k: analyzer.get($v).get()?),* };
|
|
||||||
|
|
||||||
analyzer.build(v)
|
|
||||||
}};
|
|
||||||
|
|
||||||
($($item:ident)::+ ( $($v:expr),* $(,)? )) => {{
|
|
||||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
|
||||||
|
|
||||||
let v = $($item)::+ ( $(analyzer.get($v).get()?),* );
|
|
||||||
|
|
||||||
analyzer.build(v)
|
|
||||||
}};
|
|
||||||
|
|
||||||
(( $($v:expr),* $(,)? )) => {{
|
|
||||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
|
||||||
|
|
||||||
let v = ( $(analyzer.get($v).get()?),* );
|
|
||||||
|
|
||||||
analyzer.build(v)
|
|
||||||
}};
|
|
||||||
|
|
||||||
($($item:ident)::+) => {
|
|
||||||
$($item)::+
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_expr,
|
error::{AstError, collect_recovered},
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::var_decl_statement => {
|
Rule::var_decl_statement => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
ast_expr!(VarDeclStmt {
|
Ok(VarDeclStmt {
|
||||||
decl: inner.next().unwrap().try_into(),
|
decl: inner.next().unwrap().try_into()?,
|
||||||
init: inner.next().map(Expression::try_from).transpose()
|
init: inner.next().map(Expression::try_from).transpose()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,16 +25,16 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::class_field => {
|
Rule::class_field => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
ast_expr!(FieldDeclStmt {
|
Ok(FieldDeclStmt {
|
||||||
decl: inner.next().unwrap().try_into(),
|
decl: inner.next().unwrap().try_into()?,
|
||||||
init: inner.next().map(Expression::try_from).transpose(),
|
init: inner.next().map(Expression::try_from).transpose()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,16 +44,20 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::var_decl | Rule::param => {
|
Rule::var_decl | Rule::param => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
ast_expr!(VarDecl {
|
Ok(VarDecl {
|
||||||
name: Pattern::try_from(inner.next().unwrap()),
|
type_: consume_rule(&mut inner, Rule::type_expr)
|
||||||
type_: inner.next().map(TypeExpr::try_from).transpose(),
|
.map(TypeExpr::try_from)
|
||||||
|
.transpose()?,
|
||||||
|
true_type: listen_rule(&mut inner, Rule::as_kw),
|
||||||
|
name: Pattern::try_from(inner.next().unwrap())?,
|
||||||
|
tuple_names: collect_recovered(inner)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,17 +67,17 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::field => {
|
Rule::field => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
ast_expr!(FieldDecl {
|
Ok(FieldDecl {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
name: Identifier::try_from(inner.next().unwrap()),
|
type_: TypeExpr::try_from(inner.next().unwrap())?,
|
||||||
type_: TypeExpr::try_from(inner.next().unwrap()),
|
name: Identifier::try_from(inner.next().unwrap())?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,9 +87,9 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
|
Ok(ParamList(collect_recovered(pair.into_inner())?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure,
|
||||||
error::{AstError, AstResult, GetLength, IntoErr, collect_recovered, collect_recovered_map},
|
error::{AstError, collect_recovered, collect_recovered_map},
|
||||||
parser::consume_rule,
|
parser::consume_rule,
|
||||||
};
|
};
|
||||||
use pest::pratt_parser::PrattParser;
|
use pest::pratt_parser::PrattParser;
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -27,10 +27,10 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
pratt
|
pratt
|
||||||
.map_primary(|primary_pair| Expression::try_from(primary_pair))
|
.map_primary(|primary_pair| Expression::try_from(primary_pair))
|
||||||
.map_infix(|expr, op, rhs| {
|
.map_infix(|expr, op, rhs| {
|
||||||
ast_expr!(Expression::Binary {
|
Ok(Expression::Binary {
|
||||||
lhs: expr.map(Box::new).get_map(Box::new),
|
lhs: expr.map(Box::new)?,
|
||||||
op: Ok(op.as_str().to_string()) as AstResult<'_, String>,
|
op: op.as_str().to_string(),
|
||||||
rhs: rhs.map(Box::new).get_map(Box::new),
|
rhs: rhs.map(Box::new)?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.parse(inner)
|
.parse(inner)
|
||||||
@@ -50,59 +50,52 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let prefixes = collect_recovered::<Prefix, Prefix>(prefix_pairs.into_iter());
|
let prefixes = collect_recovered::<Prefix>(prefix_pairs.into_iter())?;
|
||||||
let exp = Expression::try_from(
|
let exp = Expression::try_from(
|
||||||
primary_pair.expect("Term must contain a primary expression"),
|
primary_pair.expect("Term must contain a primary expression"),
|
||||||
);
|
)?;
|
||||||
let postfixes = collect_recovered::<Postfix, Postfix>(postfix_pairs.into_iter());
|
let postfixes = collect_recovered::<Postfix>(postfix_pairs.into_iter())?;
|
||||||
|
|
||||||
if postfixes.len() > 0 || prefixes.len() > 0 {
|
if postfixes.len() > 0 || prefixes.len() > 0 {
|
||||||
ast_expr!(Expression::Fix {
|
Ok(Expression::Fix {
|
||||||
initial: exp.map(Box::new),
|
initial: Box::new(exp),
|
||||||
prefixes: prefixes,
|
prefixes: prefixes,
|
||||||
postfixes: postfixes,
|
postfixes: postfixes,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
ast_expr!(use exp?, prefixes, postfixes)
|
Ok(exp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Rule::tuple => {
|
Rule::tuple => Ok(Expression::Literal(Literal::Tuple(collect_recovered(
|
||||||
ast_expr!(Expression::Literal(
|
pair.into_inner(),
|
||||||
collect_recovered(pair.into_inner())
|
)?))),
|
||||||
.map(Literal::Tuple)
|
|
||||||
.get_map(Literal::Tuple)
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::closure => {
|
Rule::closure => Ok(Expression::Closure {
|
||||||
ast_expr!(Expression::Closure {
|
|
||||||
params: collect_recovered(inner.next().unwrap().into_inner()),
|
|
||||||
return_type: consume_rule(&mut inner, Rule::type_expr)
|
return_type: consume_rule(&mut inner, Rule::type_expr)
|
||||||
.map(TypeExpr::try_from)
|
.map(TypeExpr::try_from)
|
||||||
.transpose(),
|
.transpose()?,
|
||||||
body: Expression::try_from(inner.next().unwrap()).map(Box::new),
|
params: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
})
|
body: Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||||
}
|
}),
|
||||||
|
|
||||||
Rule::array => {
|
Rule::array => Ok(Expression::Array(collect_recovered(inner)?)),
|
||||||
ast_expr!(Expression::Array(collect_recovered(inner)))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::array_repeat => {
|
Rule::array_repeat => Ok(Expression::ArrayRepeat(
|
||||||
ast_expr!(Expression::ArrayRepeat(
|
Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||||
Expression::try_from(inner.next().unwrap()).map(Box::new),
|
Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||||
Expression::try_from(inner.next().unwrap()).map(Box::new)
|
)),
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::primary => pair.into_inner().next().unwrap().try_into(),
|
Rule::primary => pair.into_inner().next().unwrap().try_into(),
|
||||||
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
|
Rule::static_path => Ok(Expression::Path(pair.try_into()?)),
|
||||||
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
|
Rule::literal => Ok(Expression::Literal(pair.try_into()?)),
|
||||||
Rule::expr_path => ast_expr!(Expression::Path(pair.try_into())),
|
Rule::expr_path => Ok(Expression::Path(pair.try_into()?)),
|
||||||
Rule::statement | Rule::basic_stmt | Rule::control_flow | Rule::block | Rule::unsafe_block => ast_expr!(
|
Rule::statement
|
||||||
Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new))
|
| Rule::basic_stmt
|
||||||
),
|
| Rule::control_flow
|
||||||
|
| Rule::block
|
||||||
|
| Rule::unsafe_block
|
||||||
|
| Rule::top_level => Ok(Expression::Statement(Box::new(pair.try_into()?))),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
@@ -110,7 +103,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
Ok(match pair.as_rule() {
|
Ok(match pair.as_rule() {
|
||||||
@@ -127,7 +120,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -136,34 +129,27 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
|||||||
match rule {
|
match rule {
|
||||||
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
|
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
|
||||||
|
|
||||||
Rule::field_px => {
|
Rule::field_px => Ok(Postfix::FieldAccess(
|
||||||
ast_expr!(Postfix::FieldAccess(
|
inner.next().unwrap().try_into()?,
|
||||||
inner.next().unwrap().try_into(),
|
inner.next().map(Generics::try_from).transpose()?,
|
||||||
inner.next().map(Generics::try_from).transpose()
|
)),
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::tuple_field_px => {
|
Rule::tuple_field_px => Ok(Postfix::TupleFieldAccess(
|
||||||
ast_expr!(Postfix::TupleFieldAccess(
|
inner.next().unwrap().as_str().parse().unwrap_or(255_u8),
|
||||||
Ok(inner.next().unwrap().as_str().parse().unwrap_or(255_u8))
|
inner.next().map(Generics::try_from).transpose()?,
|
||||||
as AstResult<'_, u8>,
|
)),
|
||||||
inner.next().map(Generics::try_from).transpose(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
|
Rule::call_px => Ok(Postfix::Call(collect_recovered(inner)?)),
|
||||||
|
|
||||||
Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
|
Rule::struct_px => Ok(Postfix::StructCall(collect_recovered_map(inner, |p| {
|
||||||
let mut pi = p.into_inner();
|
let mut pi = p.into_inner();
|
||||||
Ok((
|
Ok((
|
||||||
Identifier::try_from(pi.next().unwrap())?,
|
Identifier::try_from(pi.next().unwrap())?,
|
||||||
pi.next().map(Expression::try_from).transpose().get()?,
|
pi.next().map(Expression::try_from).transpose()?,
|
||||||
))
|
))
|
||||||
}))),
|
})?)),
|
||||||
|
|
||||||
Rule::index_px => {
|
Rule::index_px => Ok(Postfix::Index(Expression::try_from(inner.next().unwrap())?)),
|
||||||
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::macro_call_paren => Ok(Postfix::MacroCall {
|
Rule::macro_call_paren => Ok(Postfix::MacroCall {
|
||||||
inner: inner.as_str().to_string(),
|
inner: inner.as_str().to_string(),
|
||||||
@@ -178,9 +164,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
|||||||
delimiter: MacroDelimiter::Brace,
|
delimiter: MacroDelimiter::Brace,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::as_px => {
|
Rule::as_px => Ok(Postfix::As(inner.next().unwrap().try_into()?)),
|
||||||
ast_expr!(Postfix::As(inner.next().unwrap().try_into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::try_px => Ok(Postfix::Try),
|
Rule::try_px => Ok(Postfix::Try),
|
||||||
|
|
||||||
@@ -193,25 +177,25 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPath {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPath {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
ast_ensure!(pair, Rule::expr_path => {
|
ast_ensure!(pair, Rule::expr_path => {
|
||||||
ast_expr!(ExprPath(collect_recovered(pair.into_inner())))
|
Ok(ExprPath(collect_recovered(pair.into_inner())?))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPathSegment {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPathSegment {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::expr_path_segment => {
|
ast_ensure!(pair, Rule::expr_path_segment => {
|
||||||
ast_expr!(ExprPathSegment {
|
Ok(ExprPathSegment {
|
||||||
ident: Identifier::try_from(inner.next().unwrap()),
|
ident: Identifier::try_from(inner.next().unwrap())?,
|
||||||
generics: inner.next().map(Generics::try_from).transpose(),
|
generics: inner.next().map(Generics::try_from).transpose()?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ pub mod types;
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure,
|
||||||
error::{AstError, AstResult, IntoErr, collect_recovered, collect_recovered_map},
|
error::{AstError, collect_recovered, collect_recovered_map},
|
||||||
parser::{consume_rule, listen_rule},
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
ast_ensure!(pair, Rule::identifier => {
|
ast_ensure!(pair, Rule::identifier => {
|
||||||
@@ -22,18 +22,18 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Path {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Path {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
|
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner())?)),
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -46,53 +46,52 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
|
|||||||
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
|
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
|
||||||
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
|
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
|
||||||
Rule::string_lit => Literal::String(inner.as_str().to_string()),
|
Rule::string_lit => Literal::String(inner.as_str().to_string()),
|
||||||
Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
|
Rule::tuple => Literal::Tuple(collect_recovered(inner)?),
|
||||||
_ => return AstError::bug_unimplemented(pair),
|
_ => return AstError::bug_unimplemented(pair),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered_map(inner, |v| {
|
Rule::tuple_pattern => Ok(Pattern::Tuple(collect_recovered_map(inner, |v| {
|
||||||
Self::try_from(v).map(Box::new)
|
Self::try_from(v).map(Box::new)
|
||||||
}))),
|
})?)),
|
||||||
|
|
||||||
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
|
Rule::named_tuple_pattern => Ok(Pattern::NamedTuple(
|
||||||
Path::try_from(inner.next().unwrap()),
|
Path::try_from(inner.next().unwrap())?,
|
||||||
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new)),
|
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new))?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::struct_pattern => ast_expr!(Pattern::Struct(
|
Rule::struct_pattern => Ok(Pattern::Struct(
|
||||||
Path::try_from(inner.next().unwrap()),
|
Path::try_from(inner.next().unwrap())?,
|
||||||
collect_recovered_map(inner, |v| {
|
collect_recovered_map(inner, |v| {
|
||||||
if v.as_rule() == Rule::etc_pattern {
|
if v.as_rule() == Rule::etc_pattern {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut inner = v.into_inner();
|
let mut inner = v.into_inner();
|
||||||
Some(ast_expr!((
|
Ok(Some((
|
||||||
Identifier::try_from(inner.next().unwrap()),
|
Identifier::try_from(inner.next().unwrap())?,
|
||||||
inner
|
inner
|
||||||
.next()
|
.next()
|
||||||
.map(|v| Self::try_from(v).map(Box::new).get_map(Box::new))
|
.map(|v| Self::try_from(v).map(Box::new))
|
||||||
.transpose()
|
.transpose()?,
|
||||||
)))
|
)))
|
||||||
.transpose()
|
})?,
|
||||||
}),
|
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
|
Rule::literal => Ok(Pattern::Literal(pair.try_into()?)),
|
||||||
|
|
||||||
Rule::path_pattern => ast_expr!(Pattern::Path(
|
Rule::path_pattern => Ok(Pattern::Path(
|
||||||
Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
|
listen_rule(&mut inner, Rule::mutable),
|
||||||
inner.next().unwrap().try_into()
|
inner.next().unwrap().try_into()?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::etc_pattern => Ok(Pattern::Etc),
|
Rule::etc_pattern => Ok(Pattern::Etc),
|
||||||
@@ -103,13 +102,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility {
|
impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pairs: &mut pest::iterators::Pairs<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pairs: &mut pest::iterators::Pairs<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
Ok(consume_rule(pairs, Rule::visibility)
|
Ok(consume_rule(pairs, Rule::visibility)
|
||||||
.map(|pair| -> Result<Visibility, AstError<'a, Self>> {
|
.map(|pair| -> Result<Visibility, AstError<'a>> {
|
||||||
if let Some(path) = pair.into_inner().next() {
|
if let Some(path) = pair.into_inner().next() {
|
||||||
ast_expr!(Visibility::PublicTarget(Path::try_from(path)))
|
Ok(Visibility::PublicTarget(Path::try_from(path)?))
|
||||||
} else {
|
} else {
|
||||||
Ok(Visibility::Public)
|
Ok(Visibility::Public)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,42 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure,
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
error::{AstError, collect_recovered},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::block => {
|
ast_ensure!(pair, Rule::block => {
|
||||||
ast_expr!(Block {
|
Ok(Block {
|
||||||
statements: collect_recovered(inner.next().unwrap().into_inner()),
|
statements: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
soft_return: inner.next().map(Spanned::try_from).transpose(),
|
soft_return: inner.next().map(Spanned::try_from).transpose()?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::statement_branch => {
|
ast_ensure!(pair, Rule::statement_branch => {
|
||||||
ast_expr!(StatementBranch {
|
Ok(StatementBranch {
|
||||||
condition: inner.next().unwrap().try_into(),
|
condition: inner.next().unwrap().try_into()?,
|
||||||
body: inner.next().unwrap().try_into().map(Box::new),
|
body: Box::new(inner.next().unwrap().try_into()?),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -47,50 +47,48 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
Statement::try_from(inner.next().unwrap())
|
Statement::try_from(inner.next().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
Rule::unsafe_block => ast_expr!(Statement::UnsafeBlock(inner.next().unwrap().try_into())),
|
Rule::unsafe_block => Ok(Statement::UnsafeBlock(inner.next().unwrap().try_into()?)),
|
||||||
|
|
||||||
Rule::block => ast_expr!(Statement::Block(pair.try_into())),
|
Rule::block => Ok(Statement::Block(pair.try_into()?)),
|
||||||
|
|
||||||
Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
|
Rule::top_level => Ok(Statement::TopLevel(Box::new(pair.try_into()?))),
|
||||||
|
|
||||||
Rule::return_stmt => {
|
Rule::var_decl_statement => Ok(Statement::VarDecl(pair.try_into()?)),
|
||||||
ast_expr!(Statement::Return(
|
|
||||||
inner.next().map(Expression::try_from).transpose()
|
Rule::return_stmt => Ok(Statement::Return(
|
||||||
))
|
inner.next().map(Expression::try_from).transpose()?,
|
||||||
}
|
)),
|
||||||
|
|
||||||
Rule::break_stmt => Ok(Statement::Break),
|
Rule::break_stmt => Ok(Statement::Break),
|
||||||
|
|
||||||
Rule::continue_stmt => Ok(Statement::Continue),
|
Rule::continue_stmt => Ok(Statement::Continue),
|
||||||
|
|
||||||
Rule::if_stmt => {
|
Rule::if_stmt => Ok(Statement::If {
|
||||||
ast_expr!(Statement::If {
|
initial: inner.next().unwrap().try_into()?,
|
||||||
initial: inner.next().unwrap().try_into(),
|
else_if: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
else_if: collect_recovered(inner.next().unwrap().into_inner()),
|
else_branch: inner.next().map(Block::try_from).transpose()?,
|
||||||
else_branch: inner.next().map(Block::try_from).transpose(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::while_stmt => ast_expr!(Statement::While(inner.next().unwrap().try_into())),
|
|
||||||
|
|
||||||
Rule::loop_stmt => ast_expr!(Statement::Loop(inner.next().unwrap().try_into())),
|
|
||||||
|
|
||||||
Rule::c_for_stmt => ast_expr!(Statement::CStyleFor {
|
|
||||||
init: inner.next().unwrap().try_into(),
|
|
||||||
condition: inner.next().unwrap().try_into(),
|
|
||||||
update: inner.next().unwrap().try_into(),
|
|
||||||
body: inner.next().unwrap().try_into(),
|
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::for_stmt => ast_expr!(Statement::For {
|
Rule::while_stmt => Ok(Statement::While(inner.next().unwrap().try_into()?)),
|
||||||
pattern: inner.next().unwrap().try_into(),
|
|
||||||
iterator: inner.next().unwrap().try_into(),
|
Rule::loop_stmt => Ok(Statement::Loop(inner.next().unwrap().try_into()?)),
|
||||||
body: inner.next().unwrap().try_into(),
|
|
||||||
|
Rule::c_for_stmt => Ok(Statement::CStyleFor {
|
||||||
|
init: inner.next().unwrap().try_into()?,
|
||||||
|
condition: inner.next().unwrap().try_into()?,
|
||||||
|
update: inner.next().unwrap().try_into()?,
|
||||||
|
body: inner.next().unwrap().try_into()?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::match_stmt => ast_expr!(Statement::Match(
|
Rule::for_stmt => Ok(Statement::For {
|
||||||
inner.next().unwrap().try_into(),
|
pattern: inner.next().unwrap().try_into()?,
|
||||||
collect_recovered(inner),
|
iterator: inner.next().unwrap().try_into()?,
|
||||||
|
body: inner.next().unwrap().try_into()?,
|
||||||
|
}),
|
||||||
|
|
||||||
|
Rule::match_stmt => Ok(Statement::Match(
|
||||||
|
inner.next().unwrap().try_into()?,
|
||||||
|
collect_recovered(inner)?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
@@ -99,14 +97,14 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for MatchItem {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for MatchItem {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut match_inner = pair.into_inner();
|
let mut match_inner = pair.into_inner();
|
||||||
|
|
||||||
Ok(MatchItem(
|
Ok(MatchItem(
|
||||||
collect_recovered(match_inner.next().unwrap().into_inner()).get()?,
|
collect_recovered(match_inner.next().unwrap().into_inner())?,
|
||||||
Expression::try_from(match_inner.next().unwrap()).get()?,
|
Expression::try_from(match_inner.next().unwrap())?,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure,
|
||||||
error::{AstError, AstResult, IntoErr, collect_recovered},
|
error::{AstError, collect_recovered},
|
||||||
parser::{consume_rule, listen_rule},
|
parser::{consume_rule, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -15,32 +15,94 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
|||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::generic => Self::try_from(inner.next().unwrap()),
|
Rule::generic => Self::try_from(inner.next().unwrap()),
|
||||||
Rule::type_expr => inner.next().unwrap().try_into(),
|
Rule::type_expr => {
|
||||||
Rule::lifetime => ast_expr!(TypeExpr::Lifetime(inner.next().unwrap().try_into())),
|
let mut inner = inner;
|
||||||
|
|
||||||
Rule::tuple_type => ast_expr!(TypeExpr::Tuple(collect_recovered(inner))),
|
let mut ty = TypeExpr::try_from(inner.next().unwrap())?;
|
||||||
Rule::path_type => {
|
|
||||||
ast_expr!(TypeExpr::Path(
|
|
||||||
Path::try_from(inner.next().unwrap()),
|
|
||||||
inner.next().map(Generics::try_from).transpose()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
for ref_pair in inner {
|
||||||
|
let mut ref_inner = ref_pair.clone().into_inner();
|
||||||
|
|
||||||
|
match ref_pair.as_rule() {
|
||||||
Rule::ref_type => {
|
Rule::ref_type => {
|
||||||
ast_expr!(TypeExpr::Ref {
|
ty = TypeExpr::Ref {
|
||||||
lifetime: consume_rule(&mut inner, Rule::ref_lifetime)
|
mutable: listen_rule(&mut ref_inner, Rule::mutable),
|
||||||
.map(|v| v.into_inner().next().map(Lifetime::try_from))
|
lifetime: consume_rule(&mut ref_inner, Rule::lifetime)
|
||||||
|
.map(|v| v.into_inner().next().map(Identifier::try_from))
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.transpose(),
|
.transpose()?,
|
||||||
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<bool>,
|
ty: Box::new(ty),
|
||||||
ty: TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::unsafe_ref_type => {
|
||||||
|
ty = TypeExpr::UnsafePtr {
|
||||||
|
mutable: listen_rule(&mut ref_inner, Rule::mutable),
|
||||||
|
ty: Box::new(ty),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::fn_type => {
|
||||||
|
ty = TypeExpr::Fn {
|
||||||
|
return_type: Box::new(ty),
|
||||||
|
kind: ref_inner.next().unwrap().try_into()?,
|
||||||
|
params: collect_recovered(ref_inner)?,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::array_type => {
|
||||||
|
ty = TypeExpr::Array(
|
||||||
|
Box::new(ty),
|
||||||
|
ref_inner
|
||||||
|
.next()
|
||||||
|
.map(|v| {
|
||||||
|
v.as_str().parse().map_err(|_| AstError {
|
||||||
|
span: v.as_span(),
|
||||||
|
error_code: crate::error::ErrorCode::NumberParse,
|
||||||
|
error_message: format!(
|
||||||
|
"Number exceeds isize limits: {}",
|
||||||
|
v.as_str()
|
||||||
|
),
|
||||||
})
|
})
|
||||||
|
})
|
||||||
|
.transpose()?,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
Rule::dyn_type => {
|
|
||||||
ast_expr!(TypeExpr::Dyn(
|
_ => AstError::bug_unimplemented(ref_pair)?,
|
||||||
TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ty)
|
||||||
|
}
|
||||||
|
|
||||||
|
Rule::void_type => Ok(TypeExpr::Void),
|
||||||
|
Rule::tuple_type => Ok(TypeExpr::Tuple(collect_recovered(inner)?)),
|
||||||
|
|
||||||
|
Rule::path_type => Ok(TypeExpr::Path(
|
||||||
|
Path::try_from(inner.next().unwrap())?,
|
||||||
|
inner.next().map(Generics::try_from).transpose()?,
|
||||||
|
)),
|
||||||
|
|
||||||
|
Rule::dyn_type => Ok(TypeExpr::Dyn(
|
||||||
|
TypeExpr::try_from(inner.next().unwrap()).map(Box::new)?,
|
||||||
|
)),
|
||||||
|
|
||||||
|
_ => AstError::bug_unimplemented(pair),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FnKind {
|
||||||
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
|
match pair.as_rule() {
|
||||||
|
Rule::fn_kind_fn => Ok(FnKind::Fn),
|
||||||
|
Rule::fn_kind_unsafe => Ok(FnKind::UnsafeFn),
|
||||||
|
Rule::fn_kind_closure => Ok(FnKind::FnClosure),
|
||||||
|
Rule::fn_kind_once => Ok(FnKind::FnOnce),
|
||||||
|
Rule::fn_kind_mut => Ok(FnKind::FnMut),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
@@ -48,32 +110,33 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericsDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericsDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let inner = pair.clone().into_inner();
|
let inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::generics_decl => {
|
ast_ensure!(pair, Rule::generics_decl => {
|
||||||
ast_expr!(GenericsDecl(collect_recovered(inner)))
|
Ok(GenericsDecl(collect_recovered(inner)?))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::generic_decl => {
|
ast_ensure!(pair, Rule::generic_decl => {
|
||||||
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
||||||
ast_expr!(GenericDecl::Lifetime(
|
Ok(GenericDecl::Lifetime(
|
||||||
pair.into_inner().next().unwrap().try_into(),
|
pair.into_inner().next().unwrap().try_into()?,
|
||||||
|
collect_recovered(inner)?,
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
ast_expr!(GenericDecl::Type(
|
Ok(GenericDecl::Type(
|
||||||
inner.next().unwrap().try_into(),
|
inner.next().unwrap().try_into()?,
|
||||||
collect_recovered(inner),
|
collect_recovered(inner)?,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -81,31 +144,31 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericDecl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let inner = pair.clone().into_inner();
|
let inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::generics => {
|
ast_ensure!(pair, Rule::generics => {
|
||||||
ast_expr!(Generics(collect_recovered(inner)))
|
Ok(Generics(collect_recovered(inner)?))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
ast_ensure!(pair, Rule::generic => {
|
ast_ensure!(pair, Rule::generic => {
|
||||||
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
||||||
ast_expr!(Generic::Lifetime(
|
Ok(Generic::Lifetime(
|
||||||
pair.into_inner().next().unwrap().try_into(),
|
pair.into_inner().next().unwrap().try_into()?,
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
ast_expr!(Generic::Type(
|
Ok(Generic::Type(
|
||||||
inner.next().unwrap().try_into()
|
inner.next().unwrap().try_into()?
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
error::{AstError, collect_recovered},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
match pair.as_rule() {
|
match pair.as_rule() {
|
||||||
@@ -18,7 +18,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
|||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
// first item is always the path
|
// first item is always the path
|
||||||
let path = inner.next().unwrap().try_into().get()?;
|
let path = inner.next().unwrap().try_into()?;
|
||||||
|
|
||||||
// check what comes next
|
// check what comes next
|
||||||
match inner.next() {
|
match inner.next() {
|
||||||
@@ -32,7 +32,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
|||||||
// #[path = literal]
|
// #[path = literal]
|
||||||
Ok(Attribute::NameValue {
|
Ok(Attribute::NameValue {
|
||||||
path,
|
path,
|
||||||
value: next.try_into().get()?,
|
value: next.try_into()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
|||||||
// #[path(...)]
|
// #[path(...)]
|
||||||
Ok(Attribute::List {
|
Ok(Attribute::List {
|
||||||
path,
|
path,
|
||||||
items: collect_recovered(next.into_inner()).get()?,
|
items: collect_recovered(next.into_inner())?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,48 +1,39 @@
|
|||||||
use crate::{
|
use crate::{Rule, ast::*, error::AstError, parser::consume_rule};
|
||||||
Rule,
|
|
||||||
ast::*,
|
|
||||||
error::{AstError, IntoErr},
|
|
||||||
parser::consume_rule,
|
|
||||||
};
|
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassConstructor {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassConstructor {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
visibility: Visibility::try_from(&mut inner).get()?,
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
|
|
||||||
params: consume_rule(&mut inner, Rule::param_list)
|
params: consume_rule(&mut inner, Rule::param_list)
|
||||||
.map(ParamList::try_from)
|
.map(ParamList::try_from)
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
|
|
||||||
body: inner.next().unwrap().try_into().get()?,
|
body: inner.next().unwrap().try_into()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::impl_decl | Rule::impl_for_decl => {
|
Rule::impl_decl | Rule::impl_for_decl => Ok(ClassItem::ImplDecl(pair.try_into()?)),
|
||||||
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::function_decl => Ok(ClassItem::Method(pair.try_into().get()?)),
|
Rule::function_decl => Ok(ClassItem::Method(pair.try_into()?)),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,30 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
error::{AstError, collect_recovered},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into().get()?)),
|
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into()?)),
|
||||||
|
|
||||||
Rule::enum_tuple => Ok(EnumItem::Tuple(
|
Rule::enum_tuple => Ok(EnumItem::Tuple(
|
||||||
inner.next().unwrap().try_into().get()?,
|
inner.next().unwrap().try_into()?,
|
||||||
collect_recovered(inner.next().unwrap().into_inner()).get()?,
|
collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::enum_struct => Ok(EnumItem::Struct(
|
Rule::enum_struct => Ok(EnumItem::Struct(
|
||||||
inner.next().unwrap().try_into().get()?,
|
inner.next().unwrap().try_into()?,
|
||||||
inner
|
inner
|
||||||
.next()
|
.next()
|
||||||
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
|
.map(|pair| collect_recovered::<FieldDecl>(pair.into_inner()))
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
)),
|
)),
|
||||||
|
|
||||||
|
|||||||
@@ -1,79 +1,59 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_ensure, ast_expr,
|
ast_ensure,
|
||||||
error::{self, AstError, AstResult, IntoErr},
|
error::{AstError, AstResult},
|
||||||
parser::{consume_rule, listen_rule},
|
parser::{consume_rule, consume_rule_map, listen_rule},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
ast_ensure!(pair, Rule::function_decl => {
|
ast_ensure!(pair, Rule::function_decl => {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.into_inner();
|
||||||
let visibility = Visibility::try_from(&mut inner);
|
let visibility = Visibility::try_from(&mut inner)?;
|
||||||
|
|
||||||
|
let is_virtual = listen_rule(&mut inner, Rule::virtual_kw);
|
||||||
|
|
||||||
let return_type = consume_rule(&mut inner, Rule::type_expr)
|
let return_type = consume_rule(&mut inner, Rule::type_expr)
|
||||||
.map(TypeExpr::try_from)
|
.map(TypeExpr::try_from)
|
||||||
.transpose();
|
.transpose()?;
|
||||||
|
|
||||||
let name = Identifier::try_from(inner.next().unwrap());
|
let name = Identifier::try_from(inner.next().unwrap())?;
|
||||||
|
|
||||||
let generics = consume_rule(&mut inner, Rule::generics_decl)
|
let generics = consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default());
|
.map(|v| v.unwrap_or_default())?;
|
||||||
|
|
||||||
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
|
let self_param = consume_rule_map(&mut inner, Rule::self_param, |param| {
|
||||||
let mut param_inner = param.into_inner();
|
let mut param_inner = param.into_inner();
|
||||||
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
|
|
||||||
|
let is_ref = listen_rule(&mut param_inner, Rule::ref_px);
|
||||||
let lifetime = consume_rule(&mut param_inner, Rule::lifetime);
|
let lifetime = consume_rule(&mut param_inner, Rule::lifetime);
|
||||||
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
let mutable = listen_rule(&mut param_inner, Rule::mutable);
|
||||||
let name = Pattern::Path(mutable && !is_ref, Path(vec![Identifier(String::from("self"))]));
|
|
||||||
let self_ty = TypeExpr::Path(Path(vec![Identifier(String::from("Self"))]), None);
|
|
||||||
|
|
||||||
VarDecl {
|
Ok((is_ref, lifetime.map(|v| -> AstResult<Identifier> {
|
||||||
name: name.clone(),
|
Identifier::try_from(v.into_inner().next().unwrap())
|
||||||
type_: Some(if is_ref {
|
}).transpose()?, mutable))
|
||||||
TypeExpr::Ref {
|
})?;
|
||||||
lifetime:
|
|
||||||
lifetime.map(|v| Lifetime::try_from(v.into_inner().next().unwrap()))
|
|
||||||
.transpose()
|
|
||||||
.expect("Failed to get lifetime identifier"),
|
|
||||||
mutable,
|
|
||||||
ty: Box::new(self_ty)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self_ty
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let params = consume_rule(&mut inner, Rule::param_list)
|
let params = consume_rule(&mut inner, Rule::param_list).map(ParamList::try_from).transpose()?.unwrap_or_default();
|
||||||
.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 is_override = consume_rule(&mut inner, Rule::override_kw).map(Override::try_from).transpose();
|
let is_override = consume_rule(&mut inner, Rule::override_kw).map(Override::try_from).transpose()?;
|
||||||
|
|
||||||
let body = inner.next().map(Block::try_from).transpose();
|
let body = inner.next().map(Block::try_from).transpose()?;
|
||||||
|
|
||||||
ast_expr!(Self {
|
Ok(Self {
|
||||||
visibility: visibility,
|
visibility: visibility,
|
||||||
is_override: is_override,
|
is_virtual: is_virtual,
|
||||||
return_type: return_type,
|
return_type: return_type,
|
||||||
name: name,
|
name: name,
|
||||||
generics: generics,
|
generics: generics,
|
||||||
|
self_param: self_param,
|
||||||
params: params,
|
params: params,
|
||||||
|
is_override: is_override,
|
||||||
body: body,
|
body: body,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -81,26 +61,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Override {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Override {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
ast_ensure!(pair, Rule::override_kw => {
|
ast_ensure!(pair, Rule::override_kw => {
|
||||||
ast_expr!(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()))
|
Ok(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()?))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Lifetime {
|
|
||||||
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();
|
|
||||||
|
|
||||||
match pair.as_rule() {
|
|
||||||
Rule::ref_lifetime => inner.next().unwrap().try_into(),
|
|
||||||
Rule::lifetime => ast_expr!(Lifetime::Lifetime(inner.next().unwrap().try_into())),
|
|
||||||
Rule::unsafe_kw => Ok(Lifetime::Unsafe),
|
|
||||||
_ => error::AstError::bug_unimplemented(pair),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
error::{AstError, collect_recovered},
|
||||||
parser::consume_rule,
|
parser::consume_rule,
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
@@ -16,23 +16,21 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
|
|||||||
Rule::impl_for_decl => Ok(ImplDecl {
|
Rule::impl_for_decl => Ok(ImplDecl {
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
trait_: Some(inner.next().unwrap().try_into().get()?),
|
trait_: Some(inner.next().unwrap().try_into()?),
|
||||||
target: inner.next().unwrap().try_into().get()?,
|
target: inner.next().unwrap().try_into()?,
|
||||||
methods: collect_recovered(inner).get()?,
|
methods: collect_recovered(inner)?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::impl_decl => Ok(ImplDecl {
|
Rule::impl_decl => Ok(ImplDecl {
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()?
|
||||||
.get()?
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
trait_: None,
|
trait_: None,
|
||||||
target: inner.next().unwrap().try_into().get()?,
|
target: inner.next().unwrap().try_into()?,
|
||||||
methods: collect_recovered(inner).get()?,
|
methods: collect_recovered(inner)?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
|
|||||||
@@ -7,121 +7,161 @@ pub mod impl_decl;
|
|||||||
use crate::{
|
use crate::{
|
||||||
Rule,
|
Rule,
|
||||||
ast::*,
|
ast::*,
|
||||||
ast_expr,
|
error::{AstError, collect_recovered},
|
||||||
error::{AstError, IntoErr, collect_recovered},
|
|
||||||
parser::consume_rule,
|
parser::consume_rule,
|
||||||
};
|
};
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let mut inner = pair.into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
let attributes = collect_recovered(inner.next().unwrap().into_inner());
|
let attributes = collect_recovered(inner.next().unwrap().into_inner())?;
|
||||||
|
|
||||||
ast_expr!(TopLevel(
|
Ok(TopLevel(
|
||||||
inner.next().map(Spanned::try_from).unwrap(),
|
inner
|
||||||
|
.next()
|
||||||
|
.map(Spanned::try_from)
|
||||||
|
.unwrap_or_else(move || Ok(Spanned::new_pair(pair, TopLevelKind::ModAttribute)))?,
|
||||||
attributes,
|
attributes,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
|
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let rule = pair.as_rule();
|
let rule = pair.as_rule();
|
||||||
let mut inner = pair.clone().into_inner();
|
let mut inner = pair.clone().into_inner();
|
||||||
|
|
||||||
match rule {
|
match rule {
|
||||||
Rule::import => ast_expr!(TopLevelKind::Import(
|
Rule::import => Ok(TopLevelKind::Import(
|
||||||
Visibility::try_from(&mut inner),
|
Visibility::try_from(&mut inner)?,
|
||||||
Path::try_from(inner.next().unwrap()),
|
Path::try_from(inner.next().unwrap())?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::function_decl => ast_expr!(TopLevelKind::FunctionDecl(pair.try_into())),
|
Rule::function_decl => Ok(TopLevelKind::FunctionDecl(pair.try_into()?)),
|
||||||
|
|
||||||
Rule::struct_decl => ast_expr!(TopLevelKind::StructDecl {
|
Rule::struct_decl => Ok(TopLevelKind::StructDecl {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
name: inner.next().unwrap().try_into(),
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
fields: inner
|
fields: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
.next()
|
|
||||||
.map(|pair| collect_recovered(pair.into_inner()))
|
|
||||||
.transpose()
|
|
||||||
.map(|v| v.unwrap_or_default()),
|
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl {
|
Rule::tuple_struct_decl => Ok(TopLevelKind::StructDeclTupleUnit {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
name: inner.next().unwrap().try_into(),
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
|
unit: consume_rule(&mut inner, Rule::tuple_type)
|
||||||
|
.map(|v| collect_recovered(v.into_inner()))
|
||||||
|
.transpose()?,
|
||||||
|
}),
|
||||||
|
|
||||||
|
Rule::class_decl => Ok(TopLevelKind::ClassDecl {
|
||||||
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
|
||||||
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
|
.map(GenericsDecl::try_from)
|
||||||
|
.transpose()
|
||||||
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
inherits: consume_rule(&mut inner, Rule::expr_path)
|
inherits: consume_rule(&mut inner, Rule::expr_path)
|
||||||
.map(ExprPath::try_from)
|
.map(ExprPath::try_from)
|
||||||
.transpose(),
|
.transpose()?,
|
||||||
|
|
||||||
fields: collect_recovered(inner.next().unwrap().into_inner()),
|
fields: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||||
|
|
||||||
constructor: consume_rule(&mut inner, Rule::class_constructor)
|
constructor: consume_rule(&mut inner, Rule::class_constructor)
|
||||||
.map(Spanned::try_from)
|
.map(Spanned::try_from)
|
||||||
.transpose(),
|
.transpose()?,
|
||||||
|
|
||||||
items: collect_recovered(inner),
|
items: collect_recovered(inner)?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::enum_decl => ast_expr!(TopLevelKind::EnumDecl {
|
Rule::enum_decl => Ok(TopLevelKind::EnumDecl {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
name: inner.next().unwrap().try_into(),
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
fields: collect_recovered(inner),
|
fields: collect_recovered(inner)?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
Rule::declare_module => ast_expr!(TopLevelKind::DeclareModule(
|
Rule::declare_module => Ok(TopLevelKind::DeclareModule(
|
||||||
Visibility::try_from(&mut inner),
|
Visibility::try_from(&mut inner)?,
|
||||||
inner.next().unwrap().try_into(),
|
inner.next().unwrap().try_into()?,
|
||||||
)),
|
)),
|
||||||
|
|
||||||
Rule::impl_for_decl | Rule::impl_decl => {
|
Rule::impl_for_decl | Rule::impl_decl => Ok(TopLevelKind::ImplDecl(pair.try_into()?)),
|
||||||
ast_expr!(TopLevelKind::ImplDecl(pair.try_into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
Rule::trait_decl => ast_expr!(TopLevelKind::TraitDecl {
|
Rule::trait_decl => Ok(TopLevelKind::TraitDecl {
|
||||||
visibility: Visibility::try_from(&mut inner),
|
visibility: Visibility::try_from(&mut inner)?,
|
||||||
|
|
||||||
name: inner.next().unwrap().try_into(),
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
|
||||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
.map(GenericsDecl::try_from)
|
.map(GenericsDecl::try_from)
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
requirements: consume_rule(&mut inner, Rule::trait_requirements)
|
requirements: consume_rule(&mut inner, Rule::trait_requirements)
|
||||||
.map(|pair| collect_recovered(pair.into_inner()))
|
.map(|pair| collect_recovered(pair.into_inner()))
|
||||||
.transpose()
|
.transpose()
|
||||||
.map(|v| v.unwrap_or_default()),
|
.map(|v| v.unwrap_or_default())?,
|
||||||
|
|
||||||
items: collect_recovered(&mut inner),
|
items: collect_recovered(&mut inner)?,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
Rule::const_decl => Ok(TopLevelKind::ConstDecl(inner.next().unwrap().try_into()?)),
|
||||||
|
Rule::static_decl => Ok(TopLevelKind::StaticDecl(inner.next().unwrap().try_into()?)),
|
||||||
|
|
||||||
|
Rule::type_alias => Ok(TopLevelKind::TypeAlias {
|
||||||
|
name: inner.next().unwrap().try_into()?,
|
||||||
|
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||||
|
.map(GenericsDecl::try_from)
|
||||||
|
.transpose()?,
|
||||||
|
ty: inner.next().unwrap().try_into()?,
|
||||||
|
}),
|
||||||
|
|
||||||
|
Rule::include_global => Ok(TopLevelKind::IncludeGlobal(Path(collect_recovered(
|
||||||
|
&mut inner,
|
||||||
|
)?))),
|
||||||
|
|
||||||
|
Rule::include_use_global => Ok(TopLevelKind::IncludeUse(
|
||||||
|
Visibility::try_from(&mut inner)?,
|
||||||
|
Path::try_from(inner.next().unwrap())?,
|
||||||
|
)),
|
||||||
|
|
||||||
|
Rule::include_local => Ok(TopLevelKind::IncludeLocal(
|
||||||
|
inner
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.into_inner()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.to_string(),
|
||||||
|
)),
|
||||||
_ => AstError::bug_unimplemented(pair),
|
_ => AstError::bug_unimplemented(pair),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
pub mod common;
|
pub mod common;
|
||||||
pub mod items;
|
pub mod items;
|
||||||
|
|
||||||
use crate::{Rule, ast::Spanned, error::AstError};
|
use crate::{
|
||||||
|
Rule,
|
||||||
|
ast::Spanned,
|
||||||
|
error::{AstError, AstResult},
|
||||||
|
};
|
||||||
|
|
||||||
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
|
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
|
||||||
let consumed = pairs
|
let consumed = pairs
|
||||||
@@ -28,10 +32,36 @@ pub fn consume_rule<'a>(
|
|||||||
if consumed { pairs.next() } else { None }
|
if consumed { pairs.next() } else { None }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, T>>>
|
pub fn consume_rule_map<'a, T>(
|
||||||
|
pairs: &mut pest::iterators::Pairs<'a, Rule>,
|
||||||
|
rule: Rule,
|
||||||
|
map: impl Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T>,
|
||||||
|
) -> AstResult<'a, Option<T>> {
|
||||||
|
let pair = consume_rule(pairs, rule);
|
||||||
|
|
||||||
|
if let Some(pair) = pair {
|
||||||
|
Some(map(pair)).transpose()
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Spanned<T> {
|
||||||
|
fn new_pair(pair: pest::iterators::Pair<'_, Rule>, item: T) -> Self {
|
||||||
|
let span = pair.as_span().start_pos().line_col();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
line: span.0,
|
||||||
|
column: span.1,
|
||||||
|
item,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a>>>
|
||||||
TryFrom<pest::iterators::Pair<'a, Rule>> for Spanned<T>
|
TryFrom<pest::iterators::Pair<'a, Rule>> for Spanned<T>
|
||||||
{
|
{
|
||||||
type Error = AstError<'a, Self>;
|
type Error = AstError<'a>;
|
||||||
|
|
||||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||||
let span = pair.as_span().start_pos().line_col();
|
let span = pair.as_span().start_pos().line_col();
|
||||||
@@ -39,16 +69,7 @@ impl<'a, T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, T>>>
|
|||||||
Ok(Self {
|
Ok(Self {
|
||||||
line: span.0,
|
line: span.0,
|
||||||
column: span.1,
|
column: span.1,
|
||||||
item: pair.try_into().map_err(|err: AstError<'_, T>| AstError {
|
item: pair.try_into()?,
|
||||||
span: err.span,
|
|
||||||
error_code: err.error_code,
|
|
||||||
error_message: err.error_message,
|
|
||||||
recovered: err.recovered.map(|v| Spanned {
|
|
||||||
line: span.0,
|
|
||||||
column: span.1,
|
|
||||||
item: v,
|
|
||||||
}),
|
|
||||||
})?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ use std::{collections::HashSet, path::PathBuf};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(
|
#[derive(
|
||||||
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
||||||
)]
|
)]
|
||||||
pub struct MistMap(pub usize, pub usize);
|
pub struct MistMap(pub usize, pub usize);
|
||||||
|
|
||||||
#[derive(
|
#[derive(
|
||||||
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
|
||||||
)]
|
)]
|
||||||
pub struct RustMap(pub usize, pub usize);
|
pub struct RustMap(pub usize, pub usize);
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ pub fn find_function_call<'a>(
|
|||||||
) -> Option<&'a Spanned<FunctionDecl>> {
|
) -> Option<&'a Spanned<FunctionDecl>> {
|
||||||
items.iter().find_map(|v| {
|
items.iter().find_map(|v| {
|
||||||
if let ClassItem::Method(m) = v {
|
if let ClassItem::Method(m) = v {
|
||||||
if m.item.is_using_self() && &m.item.name == name {
|
if m.item.self_param.is_some() && &m.item.name == name {
|
||||||
Some(m)
|
Some(m)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -46,10 +46,13 @@ pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<Semanti
|
|||||||
if let Some(constructor) = constructor {
|
if let Some(constructor) = constructor {
|
||||||
let mut fields = fields
|
let mut fields = fields
|
||||||
.iter()
|
.iter()
|
||||||
.map(|field| Spanned {
|
.filter_map(|field| match field.item.init {
|
||||||
|
Some(_) => None,
|
||||||
|
None => Some(Spanned {
|
||||||
item: field.item.decl.name.clone(),
|
item: field.item.decl.name.clone(),
|
||||||
line: field.line,
|
line: field.line,
|
||||||
column: field.column,
|
column: field.column,
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
@@ -99,6 +102,28 @@ pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<Semanti
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
} else if let TopLevelKind::FunctionDecl(decl) = &top_level.0.item {
|
||||||
|
if decl.is_virtual && decl.is_override.is_some() {
|
||||||
|
Err(vec![SemanticError {
|
||||||
|
line: top_level.0.line,
|
||||||
|
column: top_level.0.column,
|
||||||
|
error_message: "virtual and override are only used in classes".to_string(),
|
||||||
|
}])
|
||||||
|
} else if decl.is_virtual {
|
||||||
|
Err(vec![SemanticError {
|
||||||
|
line: top_level.0.line,
|
||||||
|
column: top_level.0.column,
|
||||||
|
error_message: "virtual is only used in classes".to_string(),
|
||||||
|
}])
|
||||||
|
} else if decl.is_override.is_some() {
|
||||||
|
Err(vec![SemanticError {
|
||||||
|
line: top_level.0.line,
|
||||||
|
column: top_level.0.column,
|
||||||
|
error_message: "override is only used in classes".to_string(),
|
||||||
|
}])
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -129,6 +154,7 @@ impl GetMutability for Block {
|
|||||||
impl GetMutability for Statement {
|
impl GetMutability for Statement {
|
||||||
fn get_mutability(&self) -> Vec<Identifier> {
|
fn get_mutability(&self) -> Vec<Identifier> {
|
||||||
match self {
|
match self {
|
||||||
|
Statement::TopLevel(_) => Vec::new(),
|
||||||
Statement::Block(body) | Statement::UnsafeBlock(body) => body.get_mutability(),
|
Statement::Block(body) | Statement::UnsafeBlock(body) => body.get_mutability(),
|
||||||
Statement::If {
|
Statement::If {
|
||||||
initial,
|
initial,
|
||||||
@@ -317,12 +343,6 @@ impl GetMutability for Expression {
|
|||||||
// Recurse into all postfix sub-expressions
|
// Recurse into all postfix sub-expressions
|
||||||
for postfix in postfixes {
|
for postfix in postfixes {
|
||||||
match postfix {
|
match postfix {
|
||||||
Postfix::Assign(_, rhs) => {
|
|
||||||
if let Some(self_ref) = get_self_ref(initial, postfixes) {
|
|
||||||
result.push(self_ref);
|
|
||||||
}
|
|
||||||
result.append(&mut rhs.get_mutability());
|
|
||||||
}
|
|
||||||
Postfix::Call(args) => {
|
Postfix::Call(args) => {
|
||||||
for arg in args {
|
for arg in args {
|
||||||
result.append(&mut arg.get_mutability());
|
result.append(&mut arg.get_mutability());
|
||||||
|
|||||||
@@ -1,44 +1,77 @@
|
|||||||
pub module decl_test;
|
pub module decl_test;
|
||||||
|
|
||||||
pub fn void test_let_basic() {
|
pub void test_let_basic()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
assert_eq!(x, 42);
|
assert_eq!(x, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_typed() {
|
pub void test_let_repeat()
|
||||||
let x i32 = 42;
|
{
|
||||||
|
let x, y = (42, 67);
|
||||||
assert_eq!(x, 42);
|
assert_eq!(x, 42);
|
||||||
|
assert_eq!(y, 67);
|
||||||
|
}
|
||||||
|
|
||||||
let s *str = "hello";
|
pub void test_let_typed()
|
||||||
|
{
|
||||||
|
i32 x = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
str& s = "hello";
|
||||||
assert_eq!(s, "hello");
|
assert_eq!(s, "hello");
|
||||||
|
bool b = true;
|
||||||
let b bool = true;
|
|
||||||
assert_eq!(b, true);
|
assert_eq!(b, true);
|
||||||
|
f64 f = 3.14;
|
||||||
let f f64 = 3.14;
|
|
||||||
assert_eq!(f, 3.14);
|
assert_eq!(f, 3.14);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_mut() {
|
pub void test_let_repeat_typed()
|
||||||
|
{
|
||||||
|
i32 x, x1 = (42, 67);
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
assert_eq!(x1, 67);
|
||||||
|
|
||||||
|
str& s, s1 = ("hello", "world");
|
||||||
|
assert_eq!(s, "hello");
|
||||||
|
assert_eq!(s1, "world");
|
||||||
|
|
||||||
|
bool b, b1 = (true, false);
|
||||||
|
assert_eq!(b, true);
|
||||||
|
assert_eq!(b1, false);
|
||||||
|
|
||||||
|
f64 f, f1 = (3.14, 5.5);
|
||||||
|
assert_eq!(f, 3.14);
|
||||||
|
assert_eq!(f1, 5.5);
|
||||||
|
|
||||||
|
(i32, f64) as a, b = (70, 1.4);
|
||||||
|
assert_eq!(a, 70);
|
||||||
|
assert_eq!(b, 1.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_let_mut()
|
||||||
|
{
|
||||||
let mut _x = 42;
|
let mut _x = 42;
|
||||||
_x = 100;
|
_x = 100;
|
||||||
assert_eq!(_x, 100);
|
assert_eq!(_x, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_tuple_destructure() {
|
pub void test_let_tuple_destructure()
|
||||||
|
{
|
||||||
let (a, b) = (10, "hello");
|
let (a, b) = (10, "hello");
|
||||||
assert_eq!(a, 10);
|
assert_eq!(a, 10);
|
||||||
assert_eq!(b, "hello");
|
assert_eq!(b, "hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_nested_tuple() {
|
pub void test_let_nested_tuple()
|
||||||
|
{
|
||||||
let (a, (b, c)) = (1, (2, 3));
|
let (a, (b, c)) = (1, (2, 3));
|
||||||
assert_eq!(a, 1);
|
assert_eq!(a, 1);
|
||||||
assert_eq!(b, 2);
|
assert_eq!(b, 2);
|
||||||
assert_eq!(c, 3);
|
assert_eq!(c, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_pattern_irrefutable() {
|
pub void test_let_pattern_irrefutable()
|
||||||
|
{
|
||||||
let x = 5;
|
let x = 5;
|
||||||
let (y, z) = (1, 2);
|
let (y, z) = (1, 2);
|
||||||
assert_eq!(x, 5);
|
assert_eq!(x, 5);
|
||||||
@@ -46,32 +79,60 @@ pub fn void test_let_pattern_irrefutable() {
|
|||||||
assert_eq!(z, 2);
|
assert_eq!(z, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_multiple_decls() {
|
pub void test_multiple_decls()
|
||||||
|
{
|
||||||
let a = 1;
|
let a = 1;
|
||||||
let b = 2;
|
let b = 2;
|
||||||
let c = 3;
|
let c = 3;
|
||||||
assert_eq!(a + b + c, 6);
|
assert_eq!(a + b + c, 6);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_with_type_and_init() {
|
pub void test_let_with_type_and_init()
|
||||||
let x f64 = 10.0;
|
{
|
||||||
|
f64 x = 10.0;
|
||||||
assert_eq!(x, 10.0);
|
assert_eq!(x, 10.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_string_literal() {
|
pub void test_string_literal()
|
||||||
|
{
|
||||||
let s = "hello, world!";
|
let s = "hello, world!";
|
||||||
assert_eq!(s.len(), 13);
|
assert_eq!(s.len(), 13);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_let_bool() {
|
pub void test_let_bool()
|
||||||
|
{
|
||||||
let t = true;
|
let t = true;
|
||||||
let f = false;
|
let f = false;
|
||||||
assert_eq!(t, !f);
|
assert_eq!(t, !f);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub void test_let_decl_only()
|
||||||
|
{
|
||||||
|
let x;
|
||||||
|
x = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_let_typed_decl_only()
|
||||||
|
{
|
||||||
|
i32 x;
|
||||||
|
x = 100;
|
||||||
|
assert_eq!(x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_let_decl_mut_no_init()
|
||||||
|
{
|
||||||
|
let mut x;
|
||||||
|
x = 5;
|
||||||
|
assert_eq!(x, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_let_basic();
|
test_let_basic();
|
||||||
|
test_let_repeat();
|
||||||
test_let_typed();
|
test_let_typed();
|
||||||
|
test_let_repeat_typed();
|
||||||
test_let_mut();
|
test_let_mut();
|
||||||
test_let_tuple_destructure();
|
test_let_tuple_destructure();
|
||||||
test_let_nested_tuple();
|
test_let_nested_tuple();
|
||||||
@@ -80,4 +141,7 @@ pub fn void run_tests() {
|
|||||||
test_let_with_type_and_init();
|
test_let_with_type_and_init();
|
||||||
test_string_literal();
|
test_string_literal();
|
||||||
test_let_bool();
|
test_let_bool();
|
||||||
|
test_let_decl_only();
|
||||||
|
test_let_typed_decl_only();
|
||||||
|
test_let_decl_mut_no_init();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub module expr_test;
|
pub module expr_test;
|
||||||
|
|
||||||
pub fn void test_literals() {
|
pub void test_literals()
|
||||||
|
{
|
||||||
assert_eq!(42, 42);
|
assert_eq!(42, 42);
|
||||||
assert_eq!(3.14, 3.14);
|
assert_eq!(3.14, 3.14);
|
||||||
assert_eq!(true, true);
|
assert_eq!(true, true);
|
||||||
@@ -8,28 +9,32 @@ pub fn void test_literals() {
|
|||||||
assert_eq!("hello", "hello");
|
assert_eq!("hello", "hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_tuples() {
|
pub void test_tuples()
|
||||||
|
{
|
||||||
let t = (1, true, "three");
|
let t = (1, true, "three");
|
||||||
assert_eq!(t.0, 1);
|
assert_eq!(t.0, 1);
|
||||||
assert_eq!(t.1, true);
|
assert_eq!(t.1, true);
|
||||||
assert_eq!(t.2, "three");
|
assert_eq!(t.2, "three");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_arrays() {
|
pub void test_arrays()
|
||||||
|
{
|
||||||
let arr = [1, 2, 3];
|
let arr = [1, 2, 3];
|
||||||
assert_eq!(arr[0], 1);
|
assert_eq!(arr[0], 1);
|
||||||
assert_eq!(arr[1], 2);
|
assert_eq!(arr[1], 2);
|
||||||
assert_eq!(arr[2], 3);
|
assert_eq!(arr[2], 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_array_repeat() {
|
pub void test_array_repeat()
|
||||||
|
{
|
||||||
let arr = [0; 5];
|
let arr = [0; 5];
|
||||||
assert_eq!(arr[0], 0);
|
assert_eq!(arr[0], 0);
|
||||||
assert_eq!(arr[4], 0);
|
assert_eq!(arr[4], 0);
|
||||||
assert_eq!(arr.len(), 5);
|
assert_eq!(arr.len(), 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_binary_arith() {
|
pub void test_binary_arith()
|
||||||
|
{
|
||||||
assert_eq!(10 + 5, 15);
|
assert_eq!(10 + 5, 15);
|
||||||
assert_eq!(10 - 5, 5);
|
assert_eq!(10 - 5, 5);
|
||||||
assert_eq!(10 * 5, 50);
|
assert_eq!(10 * 5, 50);
|
||||||
@@ -37,7 +42,8 @@ pub fn void test_binary_arith() {
|
|||||||
assert_eq!(10 % 3, 1);
|
assert_eq!(10 % 3, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_binary_cmp() {
|
pub void test_binary_cmp()
|
||||||
|
{
|
||||||
assert_eq!(5 < 10, true);
|
assert_eq!(5 < 10, true);
|
||||||
assert_eq!(10 <= 10, true);
|
assert_eq!(10 <= 10, true);
|
||||||
assert_eq!(10 > 5, true);
|
assert_eq!(10 > 5, true);
|
||||||
@@ -46,14 +52,16 @@ pub fn void test_binary_cmp() {
|
|||||||
assert_eq!(5 != 10, true);
|
assert_eq!(5 != 10, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_binary_logic() {
|
pub void test_binary_logic()
|
||||||
|
{
|
||||||
assert_eq!(true && true, true);
|
assert_eq!(true && true, true);
|
||||||
assert_eq!(true && false, false);
|
assert_eq!(true && false, false);
|
||||||
assert_eq!(true || false, true);
|
assert_eq!(true || false, true);
|
||||||
assert_eq!(false || false, false);
|
assert_eq!(false || false, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_binary_bit() {
|
pub void test_binary_bit()
|
||||||
|
{
|
||||||
assert_eq!(5 & 3, 1);
|
assert_eq!(5 & 3, 1);
|
||||||
assert_eq!(5 | 3, 7);
|
assert_eq!(5 | 3, 7);
|
||||||
assert_eq!(5 ^ 3, 6);
|
assert_eq!(5 ^ 3, 6);
|
||||||
@@ -61,20 +69,23 @@ pub fn void test_binary_bit() {
|
|||||||
assert_eq!(4 >> 1, 2);
|
assert_eq!(4 >> 1, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_prefix() {
|
pub void test_prefix()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
assert_eq!(-x, -42);
|
assert_eq!(-x, -42);
|
||||||
assert_eq!(!true, false);
|
assert_eq!(!true, false);
|
||||||
assert_eq!(!false, true);
|
assert_eq!(!false, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_ref_deref() {
|
pub void test_ref_deref()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
let r = &x;
|
let r = &x;
|
||||||
assert_eq!(*r, 42);
|
assert_eq!(*r, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_postfix_inc_dec() {
|
pub void test_postfix_inc_dec()
|
||||||
|
{
|
||||||
let mut x = 5;
|
let mut x = 5;
|
||||||
x++;
|
x++;
|
||||||
assert_eq!(x, 6);
|
assert_eq!(x, 6);
|
||||||
@@ -82,17 +93,20 @@ pub fn void test_postfix_inc_dec() {
|
|||||||
assert_eq!(x, 5);
|
assert_eq!(x, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_as_cast() {
|
pub void test_as_cast()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
assert_eq!(x as f64, 42.0);
|
assert_eq!(x as f64, 42.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_closure() {
|
pub void test_closure()
|
||||||
let add = fn(a, b) -> a + b;
|
{
|
||||||
|
let add = (a, b) => a + b;
|
||||||
assert_eq!(add(2, 3), 5);
|
assert_eq!(add(2, 3), 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_block_expr() {
|
pub void test_block_expr()
|
||||||
|
{
|
||||||
let x = {
|
let x = {
|
||||||
let y = 10;
|
let y = 10;
|
||||||
y + 5
|
y + 5
|
||||||
@@ -100,15 +114,24 @@ pub fn void test_block_expr() {
|
|||||||
assert_eq!(x, 15);
|
assert_eq!(x, 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_if_expr() {
|
pub void test_if_expr()
|
||||||
let x = if true { 1 } else { 2 };
|
{
|
||||||
|
let x = if true {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
2
|
||||||
|
};
|
||||||
assert_eq!(x, 1);
|
assert_eq!(x, 1);
|
||||||
|
let y = if false {
|
||||||
let y = if false { 1 } else { 2 };
|
1
|
||||||
|
} else {
|
||||||
|
2
|
||||||
|
};
|
||||||
assert_eq!(y, 2);
|
assert_eq!(y, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_range_expr() {
|
pub void test_range_expr()
|
||||||
|
{
|
||||||
let r = 0 .. 5;
|
let r = 0 .. 5;
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
for i in r {
|
for i in r {
|
||||||
@@ -117,7 +140,8 @@ pub fn void test_range_expr() {
|
|||||||
assert_eq!(count, 5);
|
assert_eq!(count, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_binary_assign() {
|
pub void test_binary_assign()
|
||||||
|
{
|
||||||
let mut x = 10;
|
let mut x = 10;
|
||||||
x += 5;
|
x += 5;
|
||||||
assert_eq!(x, 15);
|
assert_eq!(x, 15);
|
||||||
@@ -131,7 +155,65 @@ pub fn void test_binary_assign() {
|
|||||||
assert_eq!(x, 2);
|
assert_eq!(x, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub void test_binary_assign_bit()
|
||||||
|
{
|
||||||
|
let mut x = 10;
|
||||||
|
x &= 12;
|
||||||
|
assert_eq!(x, 8);
|
||||||
|
x |= 1;
|
||||||
|
assert_eq!(x, 9);
|
||||||
|
x ^= 3;
|
||||||
|
assert_eq!(x, 10);
|
||||||
|
let mut y = 8;
|
||||||
|
y <<= 2;
|
||||||
|
assert_eq!(y, 32);
|
||||||
|
y >>= 1;
|
||||||
|
assert_eq!(y, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_empty_tuple()
|
||||||
|
{
|
||||||
|
let t = ();
|
||||||
|
assert_eq!(t, ());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_empty_array()
|
||||||
|
{
|
||||||
|
let arr = [0; 0];
|
||||||
|
assert_eq!(arr.len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_range_inclusive()
|
||||||
|
{
|
||||||
|
let mut sum = 0;
|
||||||
|
for i in 1 ..= 3 {
|
||||||
|
sum += i;
|
||||||
|
}
|
||||||
|
assert_eq!(sum, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_closure_no_args()
|
||||||
|
{
|
||||||
|
let f = () => 42;
|
||||||
|
assert_eq!(f(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_closure_with_typed_params()
|
||||||
|
{
|
||||||
|
let add = (i32 a, i32 b) => a + b;
|
||||||
|
assert_eq!(add(3, 4), 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_mut_ref()
|
||||||
|
{
|
||||||
|
let mut x = 42;
|
||||||
|
let r = &mut x;
|
||||||
|
*r = 100;
|
||||||
|
assert_eq!(x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_literals();
|
test_literals();
|
||||||
test_tuples();
|
test_tuples();
|
||||||
test_arrays();
|
test_arrays();
|
||||||
@@ -149,4 +231,11 @@ pub fn void run_tests() {
|
|||||||
test_if_expr();
|
test_if_expr();
|
||||||
test_range_expr();
|
test_range_expr();
|
||||||
test_binary_assign();
|
test_binary_assign();
|
||||||
|
test_binary_assign_bit();
|
||||||
|
test_empty_tuple();
|
||||||
|
test_empty_array();
|
||||||
|
test_range_inclusive();
|
||||||
|
test_closure_no_args();
|
||||||
|
test_closure_with_typed_params();
|
||||||
|
test_mut_ref();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pub module common;
|
pub module common;
|
||||||
|
|
||||||
pub fn void test_package() {}
|
pub void test_package() {}
|
||||||
|
|||||||
@@ -1,30 +1,29 @@
|
|||||||
pub module statement_test;
|
pub module statement_test;
|
||||||
|
|
||||||
pub fn void test_var_decl() {
|
pub void test_var_decl()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
assert_eq!(x, 42);
|
assert_eq!(x, 42);
|
||||||
|
i32 y = 10;
|
||||||
let y i32 = 10;
|
|
||||||
assert_eq!(y, 10);
|
assert_eq!(y, 10);
|
||||||
|
str& name = "mist";
|
||||||
let name *str = "mist";
|
|
||||||
assert_eq!(name, "mist");
|
assert_eq!(name, "mist");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_var_decl_with_init() {
|
pub void test_var_decl_with_init()
|
||||||
|
{
|
||||||
let mut x = 0;
|
let mut x = 0;
|
||||||
x = 5;
|
x = 5;
|
||||||
assert_eq!(x, 5);
|
assert_eq!(x, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_if_statement() {
|
pub void test_if_statement()
|
||||||
|
{
|
||||||
let mut x = 0;
|
let mut x = 0;
|
||||||
|
|
||||||
if true {
|
if true {
|
||||||
x = 1;
|
x = 1;
|
||||||
}
|
}
|
||||||
assert_eq!(x, 1);
|
assert_eq!(x, 1);
|
||||||
|
|
||||||
if false {
|
if false {
|
||||||
x = 2;
|
x = 2;
|
||||||
} else {
|
} else {
|
||||||
@@ -33,9 +32,9 @@ pub fn void test_if_statement() {
|
|||||||
assert_eq!(x, 3);
|
assert_eq!(x, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_if_else_if() {
|
pub void test_if_else_if()
|
||||||
|
{
|
||||||
let mut x = 0;
|
let mut x = 0;
|
||||||
|
|
||||||
if x == 1 {
|
if x == 1 {
|
||||||
x = 10;
|
x = 10;
|
||||||
} else if x == 0 {
|
} else if x == 0 {
|
||||||
@@ -46,27 +45,27 @@ pub fn void test_if_else_if() {
|
|||||||
assert_eq!(x, 20);
|
assert_eq!(x, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_while_loop() {
|
pub void test_while_loop()
|
||||||
|
{
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
|
|
||||||
while count < 5 {
|
while count < 5 {
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
assert_eq!(count, 5);
|
assert_eq!(count, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_for_loop() {
|
pub void test_for_loop()
|
||||||
|
{
|
||||||
let mut sum = 0;
|
let mut sum = 0;
|
||||||
|
|
||||||
for i in 0 .. 4 {
|
for i in 0 .. 4 {
|
||||||
sum += i;
|
sum += i;
|
||||||
}
|
}
|
||||||
assert_eq!(sum, 6);
|
assert_eq!(sum, 6);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_loop_stmt() {
|
pub void test_loop_stmt()
|
||||||
|
{
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
count++;
|
count++;
|
||||||
if count >= 3 {
|
if count >= 3 {
|
||||||
@@ -76,9 +75,9 @@ pub fn void test_loop_stmt() {
|
|||||||
assert_eq!(count, 3);
|
assert_eq!(count, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_break_continue() {
|
pub void test_break_continue()
|
||||||
|
{
|
||||||
let mut sum = 0;
|
let mut sum = 0;
|
||||||
|
|
||||||
for i in 0 .. 10 {
|
for i in 0 .. 10 {
|
||||||
if i % 2 == 0 {
|
if i % 2 == 0 {
|
||||||
continue;
|
continue;
|
||||||
@@ -91,11 +90,13 @@ pub fn void test_break_continue() {
|
|||||||
assert_eq!(sum, 1 + 3 + 5);
|
assert_eq!(sum, 1 + 3 + 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn i32 test_return() {
|
pub i32 test_return()
|
||||||
|
{
|
||||||
return 42;
|
return 42;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_block_scope() {
|
pub void test_block_scope()
|
||||||
|
{
|
||||||
let x = {
|
let x = {
|
||||||
let inner = 10;
|
let inner = 10;
|
||||||
inner + 5
|
inner + 5
|
||||||
@@ -103,53 +104,126 @@ pub fn void test_block_scope() {
|
|||||||
assert_eq!(x, 15);
|
assert_eq!(x, 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_match_literal() {
|
pub void test_match_literal()
|
||||||
|
{
|
||||||
let x = 2;
|
let x = 2;
|
||||||
let result;
|
let result;
|
||||||
|
|
||||||
match x {
|
match x {
|
||||||
1 => { result = 10; }
|
1 => {
|
||||||
2 => { result = 20; }
|
result = 10;
|
||||||
3 => { result = 30; }
|
}
|
||||||
_ => panic!();
|
2 => result = 20,
|
||||||
|
3 => result = 30,
|
||||||
|
_ => panic!(),
|
||||||
}
|
}
|
||||||
assert_eq!(result, 20);
|
assert_eq!(result, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_match_or_pattern() {
|
pub void test_match_or_pattern()
|
||||||
|
{
|
||||||
let x = 1;
|
let x = 1;
|
||||||
let result i32;
|
i32 result;
|
||||||
|
|
||||||
match x {
|
match x {
|
||||||
1 | 2 => { result = 100; }
|
1 | 2 => {
|
||||||
3 => { result = 200; }
|
result = 100;
|
||||||
_ => panic!();
|
}
|
||||||
|
3 => {
|
||||||
|
result = 200;
|
||||||
|
}
|
||||||
|
_ => panic!(),
|
||||||
}
|
}
|
||||||
assert_eq!(result, 100);
|
assert_eq!(result, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_match_default() {
|
pub void test_match_default()
|
||||||
|
{
|
||||||
let x = 99;
|
let x = 99;
|
||||||
let result;
|
let result;
|
||||||
|
|
||||||
match x {
|
match x {
|
||||||
1 => { result = 10; }
|
1 => {
|
||||||
y => { result = y; }
|
result = 10;
|
||||||
|
}
|
||||||
|
y => {
|
||||||
|
result = y;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
assert_eq!(result, 99);
|
assert_eq!(result, 99);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_for_with_pattern_destructure() {
|
pub void test_for_with_pattern_destructure()
|
||||||
|
{
|
||||||
let pairs = [(1, "a"), (2, "b")];
|
let pairs = [(1, "a"), (2, "b")];
|
||||||
let mut keys = 0;
|
let mut keys = 0;
|
||||||
|
|
||||||
for (k, _) in pairs {
|
for (k, _) in pairs {
|
||||||
keys += k;
|
keys += k;
|
||||||
}
|
}
|
||||||
assert_eq!(keys, 3);
|
assert_eq!(keys, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub void test_c_for_loop()
|
||||||
|
{
|
||||||
|
let mut sum = 0;
|
||||||
|
for (let mut i = 0; i < 4; i++) {
|
||||||
|
sum += i;
|
||||||
|
}
|
||||||
|
assert_eq!(sum, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_unsafe_block()
|
||||||
|
{
|
||||||
|
let mut x = 42;
|
||||||
|
unsafe {
|
||||||
|
let r = &mut x;
|
||||||
|
*r = 100;
|
||||||
|
}
|
||||||
|
assert_eq!(x, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_match_parenthesized()
|
||||||
|
{
|
||||||
|
let result;
|
||||||
|
match (2) {
|
||||||
|
1 => result = 10,
|
||||||
|
2 => result = 20,
|
||||||
|
_ => panic!(),
|
||||||
|
}
|
||||||
|
assert_eq!(result, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_if_parenthesized()
|
||||||
|
{
|
||||||
|
let mut x = 0;
|
||||||
|
if (true) {
|
||||||
|
x = 1;
|
||||||
|
}
|
||||||
|
assert_eq!(x, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_while_parenthesized()
|
||||||
|
{
|
||||||
|
let mut count = 0;
|
||||||
|
while (count < 3) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
assert_eq!(count, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_loop_with_break_value()
|
||||||
|
{
|
||||||
|
let mut x = 0;
|
||||||
|
let result;
|
||||||
|
loop {
|
||||||
|
if x >= 3 {
|
||||||
|
result = x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
x++;
|
||||||
|
}
|
||||||
|
assert_eq!(result, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_var_decl();
|
test_var_decl();
|
||||||
test_var_decl_with_init();
|
test_var_decl_with_init();
|
||||||
test_if_statement();
|
test_if_statement();
|
||||||
@@ -164,4 +238,10 @@ pub fn void run_tests() {
|
|||||||
test_match_or_pattern();
|
test_match_or_pattern();
|
||||||
test_match_default();
|
test_match_default();
|
||||||
test_for_with_pattern_destructure();
|
test_for_with_pattern_destructure();
|
||||||
|
test_c_for_loop();
|
||||||
|
test_unsafe_block();
|
||||||
|
test_match_parenthesized();
|
||||||
|
test_if_parenthesized();
|
||||||
|
test_while_parenthesized();
|
||||||
|
test_loop_with_break_value();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +1,82 @@
|
|||||||
pub module types_test;
|
pub module types_test;
|
||||||
|
|
||||||
pub fn void test_integer_type() {
|
pub void test_integer_type() {
|
||||||
let x i32 = 42;
|
i32 x = 42;
|
||||||
assert_eq!(x, 42);
|
assert_eq!(x, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_float_type() {
|
pub void test_float_type() {
|
||||||
let x f64 = 3.14;
|
f64 x = 3.14;
|
||||||
assert_eq!(x, 3.14);
|
assert_eq!(x, 3.14);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_bool_type() {
|
pub void test_bool_type() {
|
||||||
let x bool = true;
|
bool x = true;
|
||||||
assert_eq!(x, true);
|
assert_eq!(x, true);
|
||||||
|
bool y = false;
|
||||||
let y bool = false;
|
|
||||||
assert_eq!(y, false);
|
assert_eq!(y, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_string_type() {
|
pub void test_string_type() {
|
||||||
let s *str = "hello";
|
str& s = "hello";
|
||||||
assert_eq!(s, "hello");
|
assert_eq!(s, "hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_tuple_type() {
|
pub void test_tuple_type() {
|
||||||
let t (i32, *str) = (42, "answer");
|
(i32, str&) t = (42, "answer");
|
||||||
assert_eq!(t.0, 42);
|
assert_eq!(t.0, 42);
|
||||||
assert_eq!(t.1, "answer");
|
assert_eq!(t.1, "answer");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_ref_type() {
|
pub void test_ref_type() {
|
||||||
let x i32 = 42;
|
i32 x = 42;
|
||||||
let r *i32 = &x;
|
i32& r = &x;
|
||||||
assert_eq!(*r, 42);
|
assert_eq!(*r, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_mut_ref_type() {
|
pub void test_mut_ref_type() {
|
||||||
let mut x = 42;
|
let mut x = 42;
|
||||||
let r *mut i32 = &mut x;
|
i32 mut& r = &mut x;
|
||||||
*r = 100;
|
*r = 100;
|
||||||
assert_eq!(x, 100);
|
assert_eq!(x, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_void_type() {}
|
pub void test_void_type() {
|
||||||
|
}
|
||||||
|
|
||||||
fn i32 add(a i32, b i32) {
|
i32 add(i32 a, i32 b) {
|
||||||
a + b
|
a + b
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_fn_return_type() {
|
pub void test_fn_return_type() {
|
||||||
assert_eq!(add(3, 4), 7);
|
assert_eq!(add(3, 4), 7);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub void test_generic_type() {
|
||||||
|
Option<i32> x = Option::Some(42);
|
||||||
|
assert_eq!(x.is_some(), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MyInt = i32;
|
||||||
|
|
||||||
|
pub void test_type_alias() {
|
||||||
|
MyInt x = 42;
|
||||||
|
assert_eq!(x, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
const i32 MY_CONST = 100;
|
||||||
|
|
||||||
|
pub void test_const_decl() {
|
||||||
|
assert_eq!(MY_CONST, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
static i32 my_static = 200;
|
||||||
|
|
||||||
|
pub void test_static_decl() {
|
||||||
|
assert_eq!(my_static, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests() {
|
||||||
test_integer_type();
|
test_integer_type();
|
||||||
test_float_type();
|
test_float_type();
|
||||||
test_bool_type();
|
test_bool_type();
|
||||||
@@ -62,4 +86,8 @@ pub fn void run_tests() {
|
|||||||
test_mut_ref_type();
|
test_mut_ref_type();
|
||||||
test_void_type();
|
test_void_type();
|
||||||
test_fn_return_type();
|
test_fn_return_type();
|
||||||
|
test_generic_type();
|
||||||
|
test_type_alias();
|
||||||
|
test_const_decl();
|
||||||
|
test_static_decl();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,42 @@
|
|||||||
pub module attribute_test;
|
pub module attribute_test;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Debuggable {
|
pub struct Debuggable
|
||||||
value i32,
|
{
|
||||||
|
i32 value;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_derive_attribute() {
|
pub void test_derive_attribute()
|
||||||
let d = Debuggable { value: 42 };
|
{
|
||||||
|
let d = Debuggable {
|
||||||
|
value: 42,
|
||||||
|
};
|
||||||
assert_eq!(d.value, 42);
|
assert_eq!(d.value, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
pub fn void test_allow_attribute() {
|
pub void test_allow_attribute()
|
||||||
|
{
|
||||||
let x = 42;
|
let x = 42;
|
||||||
let y = "unused";
|
let y = "unused";
|
||||||
assert_eq!(x, 42);
|
assert_eq!(x, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
#[allow(dead_code)]
|
||||||
|
pub struct Tagged
|
||||||
|
{
|
||||||
|
i32 id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_attribute_with_args()
|
||||||
|
{
|
||||||
|
Tagged t = Tagged { id: 1 };
|
||||||
|
assert_eq!(t.id, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_derive_attribute();
|
test_derive_attribute();
|
||||||
test_allow_attribute();
|
test_allow_attribute();
|
||||||
|
test_attribute_with_args();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,56 +1,147 @@
|
|||||||
pub module class_test;
|
pub module class_test;
|
||||||
|
|
||||||
pub class Animal {
|
pub enum AnimalType {
|
||||||
pub name String;
|
Mammal;
|
||||||
|
}
|
||||||
|
|
||||||
constructor() {
|
pub class Animal
|
||||||
|
{
|
||||||
|
pub String name;
|
||||||
|
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
self.name = "Rex".to_string();
|
self.name = "Rex".to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn String speak(*self) {
|
pub virtual AnimalType get_animal_type(&self) {
|
||||||
|
panic!()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub virtual String speak(&self)
|
||||||
|
{
|
||||||
"Unknown".to_string()
|
"Unknown".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_speak(*self) {
|
pub virtual void speak_mut(&mut self){}
|
||||||
|
|
||||||
|
pub void test_speak<'a>(&'a self)
|
||||||
|
{
|
||||||
assert_eq!(self.speak(), "Woof!");
|
assert_eq!(self.speak(), "Woof!");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void static_method() {}
|
pub void static_method()
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub class Mammal : Animal {
|
pub class Mammal : Animal
|
||||||
constructor() {
|
{
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
super = Super::new();
|
super = Super::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void args_test(*self, x i32, y *str) {
|
// override without a target assumes current super
|
||||||
|
pub AnimalType get_animal_type(&self) override {
|
||||||
|
AnimalType::Mammal
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void args_test(&self, i32 x, str& y)
|
||||||
|
{
|
||||||
assert_eq!(x, 10);
|
assert_eq!(x, 10);
|
||||||
assert_eq!(y, "hello");
|
assert_eq!(y, "hello");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub class Dog : Mammal {
|
pub class Dog : Mammal
|
||||||
constructor() {
|
{
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
super = Super::new();
|
super = Super::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn String speak(*self) override(Animal) {
|
pub String speak(&self) override(Animal)
|
||||||
|
{
|
||||||
"Woof!".to_string()
|
"Woof!".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display {
|
impl std::fmt::Display
|
||||||
fn Result<(), std::fmt::Error> fmt(*self, f *mut std::fmt::Formatter<'_>) {
|
{
|
||||||
|
Result<(), std::fmt::Error> fmt(&self, std::fmt::Formatter<'_> mut& f)
|
||||||
|
{
|
||||||
write!(f, "🐾 {}", self.name)
|
write!(f, "🐾 {}", self.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub class Counter
|
||||||
let dawg = Dog::new();
|
{
|
||||||
|
pub i32 count;
|
||||||
|
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
|
self.count = 42;
|
||||||
|
}
|
||||||
|
|
||||||
|
i32 get_count(&self)
|
||||||
|
{
|
||||||
|
self.count
|
||||||
|
}
|
||||||
|
|
||||||
|
pub i32 static_fn()
|
||||||
|
{
|
||||||
|
99
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_class_no_inheritance()
|
||||||
|
{
|
||||||
|
Counter c = Counter::new();
|
||||||
|
assert_eq!(c.get_count(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub class WithDefault
|
||||||
|
{
|
||||||
|
pub String name = "default".to_string();
|
||||||
|
pub i32 value = 42;
|
||||||
|
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
pub String get_name(&self)
|
||||||
|
{
|
||||||
|
self.name.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_class_field_default()
|
||||||
|
{
|
||||||
|
WithDefault w = WithDefault::new();
|
||||||
|
assert_eq!(w.get_name(), "default");
|
||||||
|
assert_eq!(w.value, 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub class EmptyClass
|
||||||
|
{
|
||||||
|
constructor()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_class_empty()
|
||||||
|
{
|
||||||
|
EmptyClass e = EmptyClass::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
|
let dawg = Dog::new();
|
||||||
dawg.args_test(10, "hello");
|
dawg.args_test(10, "hello");
|
||||||
|
|
||||||
dawg.test_speak();
|
dawg.test_speak();
|
||||||
|
dawg.get_animal_type();
|
||||||
assert_eq!(format!("{dawg}"), "🐾 Rex");
|
assert_eq!(format!("{dawg}"), "🐾 Rex");
|
||||||
|
test_class_no_inheritance();
|
||||||
|
test_class_field_default();
|
||||||
|
test_class_empty();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +1,129 @@
|
|||||||
pub module enum_test;
|
pub module enum_test;
|
||||||
|
|
||||||
enum OptionInt {
|
enum OptionInt
|
||||||
None,
|
{
|
||||||
Some(i32),
|
None;
|
||||||
|
Some(i32);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_enum_named() {
|
pub void test_enum_named()
|
||||||
|
{
|
||||||
let x = OptionInt::None;
|
let x = OptionInt::None;
|
||||||
match x {
|
match x {
|
||||||
OptionInt::None => { assert_eq!(1, 1); }
|
OptionInt::None => {
|
||||||
OptionInt::Some(_) => { assert_eq!(0, 1); }
|
assert_eq!(1, 1);
|
||||||
|
}
|
||||||
|
OptionInt::Some(_) => {
|
||||||
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_enum_tuple() {
|
pub void test_enum_tuple()
|
||||||
|
{
|
||||||
let x = OptionInt::Some(42);
|
let x = OptionInt::Some(42);
|
||||||
match x {
|
match x {
|
||||||
OptionInt::None => { assert_eq!(0, 1); }
|
OptionInt::None => {
|
||||||
OptionInt::Some(v) => { assert_eq!(v, 42); }
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
|
OptionInt::Some(v) => {
|
||||||
|
assert_eq!(v, 42);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Shape {
|
enum Shape
|
||||||
Circle { radius i32 },
|
{
|
||||||
Rect { w i32, h i32 },
|
Circle {
|
||||||
|
i32 radius;
|
||||||
|
};
|
||||||
|
Rect {
|
||||||
|
i32 w;
|
||||||
|
i32 h;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_enum_struct() {
|
pub void test_enum_struct()
|
||||||
let c = Shape::Circle { radius: 5 };
|
{
|
||||||
|
let c = Shape::Circle {
|
||||||
|
radius: 5,
|
||||||
|
};
|
||||||
match c {
|
match c {
|
||||||
Shape::Circle { radius } => { assert_eq!(radius, 5); }
|
Shape::Circle {radius} => {
|
||||||
Shape::Rect { .. } => { assert_eq!(0, 1); }
|
assert_eq!(radius, 5);
|
||||||
}
|
}
|
||||||
|
Shape::Rect {..} => {
|
||||||
let r = Shape::Rect { w: 3, h: 4 };
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let r = Shape::Rect {
|
||||||
|
w: 3,
|
||||||
|
h: 4,
|
||||||
|
};
|
||||||
match r {
|
match r {
|
||||||
Shape::Circle { .. } => { assert_eq!(0, 1); }
|
Shape::Circle {..} => {
|
||||||
Shape::Rect { w, h } => { assert_eq!(w * h, 12); }
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
|
Shape::Rect {w, h} => {
|
||||||
|
assert_eq!(w * h, 12);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Color {
|
enum Color
|
||||||
Red,
|
{
|
||||||
Green,
|
Red;
|
||||||
Blue,
|
Green;
|
||||||
|
Blue;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_enum_eq() {
|
pub void test_enum_eq()
|
||||||
|
{
|
||||||
let c = Color::Red;
|
let c = Color::Red;
|
||||||
match c {
|
match c {
|
||||||
Color::Red => { assert_eq!(1, 1); }
|
Color::Red => {
|
||||||
_ => { assert_eq!(0, 1); }
|
assert_eq!(1, 1);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
enum Option<T>
|
||||||
|
{
|
||||||
|
None;
|
||||||
|
Some(T);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_generic_enum()
|
||||||
|
{
|
||||||
|
Option<i32> x = Option::Some(42);
|
||||||
|
match x {
|
||||||
|
Option::Some(v) => {
|
||||||
|
assert_eq!(v, 42);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Option<bool> y = Option::None;
|
||||||
|
match y {
|
||||||
|
Option::None => {
|
||||||
|
assert_eq!(1, 1);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
assert_eq!(0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_enum_named();
|
test_enum_named();
|
||||||
test_enum_tuple();
|
test_enum_tuple();
|
||||||
test_enum_struct();
|
test_enum_struct();
|
||||||
test_enum_eq();
|
test_enum_eq();
|
||||||
|
test_generic_enum();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +1,87 @@
|
|||||||
pub module function_test;
|
pub module function_test;
|
||||||
|
|
||||||
fn void greet() {
|
void greet()
|
||||||
|
{
|
||||||
let mut x = 1;
|
let mut x = 1;
|
||||||
x++;
|
x++;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_basic_function() {
|
pub void test_basic_function()
|
||||||
|
{
|
||||||
greet();
|
greet();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn i32 add(a i32, b i32) {
|
i32 add(i32 a, i32 b)
|
||||||
|
{
|
||||||
a + b
|
a + b
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_fn_params() {
|
pub void test_fn_params()
|
||||||
|
{
|
||||||
assert_eq!(add(2, 3), 5);
|
assert_eq!(add(2, 3), 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn i32 test_fn_return() {
|
pub i32 test_fn_return()
|
||||||
|
{
|
||||||
42
|
42
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn i32 test_fn_early_return() {
|
pub i32 test_fn_early_return()
|
||||||
|
{
|
||||||
return 100;
|
return 100;
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn i32 test_fn_mut_param(mut x i32) {
|
pub i32 test_fn_mut_param(i32 mut x)
|
||||||
|
{
|
||||||
x = x + 10;
|
x = x + 10;
|
||||||
x
|
x
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_method_call() {
|
pub void test_method_call()
|
||||||
|
{
|
||||||
let s = "hello";
|
let s = "hello";
|
||||||
assert_eq!(s.len(), 5);
|
assert_eq!(s.len(), 5);
|
||||||
assert_eq!(s.to_uppercase(), "HELLO");
|
assert_eq!(s.to_uppercase(), "HELLO");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn i32 triple(x i32) {
|
i32 triple(i32 x)
|
||||||
|
{
|
||||||
add(x, add(x, x))
|
add(x, add(x, x))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_nested_fn_calls() {
|
pub void test_nested_fn_calls()
|
||||||
|
{
|
||||||
assert_eq!(triple(5), 15);
|
assert_eq!(triple(5), 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn i32 factorial(n i32) {
|
i32 factorial(i32 n)
|
||||||
if n <= 1 { 1 }
|
{
|
||||||
else { n * factorial(n - 1) }
|
if n <= 1 {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
n * factorial(n - 1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_recursive_fn() {
|
pub void test_recursive_fn()
|
||||||
|
{
|
||||||
assert_eq!(factorial(5), 120);
|
assert_eq!(factorial(5), 120);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
T identity<T>(T x)
|
||||||
|
{
|
||||||
|
x
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_fn_generic()
|
||||||
|
{
|
||||||
|
assert_eq!(identity(42), 42);
|
||||||
|
assert_eq!(identity("hello"), "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_basic_function();
|
test_basic_function();
|
||||||
test_fn_params();
|
test_fn_params();
|
||||||
assert_eq!(test_fn_return(), 42);
|
assert_eq!(test_fn_return(), 42);
|
||||||
@@ -63,4 +90,5 @@ pub fn void run_tests() {
|
|||||||
test_method_call();
|
test_method_call();
|
||||||
test_nested_fn_calls();
|
test_nested_fn_calls();
|
||||||
test_recursive_fn();
|
test_recursive_fn();
|
||||||
|
test_fn_generic();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,39 +1,55 @@
|
|||||||
pub module impl_test;
|
pub module impl_test;
|
||||||
|
|
||||||
struct Vector2 {
|
struct Vector2
|
||||||
x i32,
|
{
|
||||||
y i32,
|
i32 x;
|
||||||
|
i32 y;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Vector2 {
|
impl Vector2
|
||||||
pub fn i32 magnitude(*self) {
|
{
|
||||||
|
pub i32 magnitude(&self)
|
||||||
|
{
|
||||||
self.x * self.x + self.y * self.y
|
self.x * self.x + self.y * self.y
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_inherent_impl() {
|
pub void test_inherent_impl()
|
||||||
let v = Vector2 { x: 3, y: 4 };
|
{
|
||||||
|
let v = Vector2 {
|
||||||
|
x: 3,
|
||||||
|
y: 4,
|
||||||
|
};
|
||||||
assert_eq!(v.magnitude(), 25);
|
assert_eq!(v.magnitude(), 25);
|
||||||
}
|
}
|
||||||
|
|
||||||
trait Display {
|
trait Display
|
||||||
fn String display(*self);
|
{
|
||||||
|
String display(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for Vector2 {
|
impl Display for Vector2
|
||||||
fn String display(*self) {
|
{
|
||||||
|
String display(&self)
|
||||||
|
{
|
||||||
format!("({}, {})", self.x, self.y)
|
format!("({}, {})", self.x, self.y)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_trait_impl_block() {
|
pub void test_trait_impl_block()
|
||||||
let v = Vector2 { x: 1, y: 2 };
|
{
|
||||||
|
let v = Vector2 {
|
||||||
|
x: 1,
|
||||||
|
y: 2,
|
||||||
|
};
|
||||||
let s = v.display();
|
let s = v.display();
|
||||||
assert_eq!(s.len() > 0, true);
|
assert_eq!(s.len() > 0, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Vector2 {
|
impl Vector2
|
||||||
pub fn Vector2 add(*self, other Vector2) {
|
{
|
||||||
|
pub Vector2 add(&self, Vector2 other)
|
||||||
|
{
|
||||||
Vector2 {
|
Vector2 {
|
||||||
x: self.x + other.x,
|
x: self.x + other.x,
|
||||||
y: self.y + other.y,
|
y: self.y + other.y,
|
||||||
@@ -41,16 +57,44 @@ impl Vector2 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_multiple_impls() {
|
pub void test_multiple_impls()
|
||||||
let a = Vector2 { x: 1, y: 2 };
|
{
|
||||||
let b = Vector2 { x: 3, y: 4 };
|
let a = Vector2 {
|
||||||
|
x: 1,
|
||||||
|
y: 2,
|
||||||
|
};
|
||||||
|
let b = Vector2 {
|
||||||
|
x: 3,
|
||||||
|
y: 4,
|
||||||
|
};
|
||||||
let c = a.add(b);
|
let c = a.add(b);
|
||||||
assert_eq!(c.x, 4);
|
assert_eq!(c.x, 4);
|
||||||
assert_eq!(c.y, 6);
|
assert_eq!(c.y, 6);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
struct Wrapper<T>
|
||||||
|
{
|
||||||
|
T value;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Copy> Wrapper<T>
|
||||||
|
{
|
||||||
|
pub T get(&self)
|
||||||
|
{
|
||||||
|
self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_impl_generic()
|
||||||
|
{
|
||||||
|
Wrapper<i32> w = Wrapper { value: 42 };
|
||||||
|
assert_eq!(w.get(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_inherent_impl();
|
test_inherent_impl();
|
||||||
test_trait_impl_block();
|
test_trait_impl_block();
|
||||||
test_multiple_impls();
|
test_multiple_impls();
|
||||||
|
test_impl_generic();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +1,116 @@
|
|||||||
pub module struct_test;
|
pub module struct_test;
|
||||||
|
|
||||||
struct Point {
|
struct Point
|
||||||
x i32,
|
{
|
||||||
y i32,
|
i32 x;
|
||||||
|
i32 y;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_struct_create_access() {
|
pub void test_struct_create_access()
|
||||||
let p = Point { x: 10, y: 20 };
|
{
|
||||||
|
let p = Point {
|
||||||
|
x: 10,
|
||||||
|
y: 20,
|
||||||
|
};
|
||||||
assert_eq!(p.x, 10);
|
assert_eq!(p.x, 10);
|
||||||
assert_eq!(p.y, 20);
|
assert_eq!(p.y, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_struct_mut_field() {
|
pub void test_struct_mut_field()
|
||||||
let mut p = Point { x: 1, y: 2 };
|
{
|
||||||
|
let mut p = Point {
|
||||||
|
x: 1,
|
||||||
|
y: 2,
|
||||||
|
};
|
||||||
p.x = 100;
|
p.x = 100;
|
||||||
assert_eq!(p.x, 100);
|
assert_eq!(p.x, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_struct_destructure() {
|
pub void test_struct_destructure()
|
||||||
let p = Point { x: 3, y: 4 };
|
{
|
||||||
|
let p = Point {
|
||||||
|
x: 3,
|
||||||
|
y: 4,
|
||||||
|
};
|
||||||
let Point {x, y} = p;
|
let Point {x, y} = p;
|
||||||
assert_eq!(x, 3);
|
assert_eq!(x, 3);
|
||||||
assert_eq!(y, 4);
|
assert_eq!(y, 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Line {
|
struct Line
|
||||||
start Point,
|
{
|
||||||
end Point,
|
Point start;
|
||||||
|
Point end;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_struct_nested() {
|
pub void test_struct_nested()
|
||||||
|
{
|
||||||
let l = Line {
|
let l = Line {
|
||||||
start: Point { x: 0, y: 0 },
|
start: Point {
|
||||||
end: Point { x: 5, y: 10 },
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
},
|
||||||
|
end: Point {
|
||||||
|
x: 5,
|
||||||
|
y: 10,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
assert_eq!(l.start.x, 0);
|
assert_eq!(l.start.x, 0);
|
||||||
assert_eq!(l.end.y, 10);
|
assert_eq!(l.end.y, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
struct Empty {}
|
||||||
|
|
||||||
|
pub void test_empty_struct()
|
||||||
|
{
|
||||||
|
let e = Empty {};
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Pair<T>
|
||||||
|
{
|
||||||
|
T first;
|
||||||
|
T second;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_generic_struct()
|
||||||
|
{
|
||||||
|
Pair<i32> p = Pair<i32> { first: 1, second: 2 };
|
||||||
|
assert_eq!(p.first, 1);
|
||||||
|
assert_eq!(p.second, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_struct_partial_destructure()
|
||||||
|
{
|
||||||
|
let p = Point {
|
||||||
|
x: 10,
|
||||||
|
y: 20,
|
||||||
|
};
|
||||||
|
let Point {x, ..} = p;
|
||||||
|
assert_eq!(x, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub void test_struct_destructure_rename()
|
||||||
|
{
|
||||||
|
let p = Point {
|
||||||
|
x: 5,
|
||||||
|
y: 15,
|
||||||
|
};
|
||||||
|
let Point {x: a, y: b} = p;
|
||||||
|
assert_eq!(a, 5);
|
||||||
|
assert_eq!(b, 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TuplePoint(i32, i32);
|
||||||
|
struct Unit;
|
||||||
|
|
||||||
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_struct_create_access();
|
test_struct_create_access();
|
||||||
test_struct_mut_field();
|
test_struct_mut_field();
|
||||||
test_struct_destructure();
|
test_struct_destructure();
|
||||||
test_struct_nested();
|
test_struct_nested();
|
||||||
|
test_empty_struct();
|
||||||
|
test_generic_struct();
|
||||||
|
test_struct_partial_destructure();
|
||||||
|
test_struct_destructure_rename();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,41 +1,55 @@
|
|||||||
pub module trait_test;
|
pub module trait_test;
|
||||||
|
|
||||||
trait Speak {
|
trait Speak
|
||||||
fn String speak(*self);
|
{
|
||||||
|
String speak(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
trait Greet : Speak {
|
trait Greet : Speak
|
||||||
fn String greet(*self);
|
{
|
||||||
|
String greet(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Dog {
|
struct Dog
|
||||||
name String,
|
{
|
||||||
|
String name;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Speak for Dog {
|
impl Speak for Dog
|
||||||
fn String speak(*self) {
|
{
|
||||||
|
String speak(&self)
|
||||||
|
{
|
||||||
"woof".to_string()
|
"woof".to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Greet for Dog {
|
impl Greet for Dog
|
||||||
fn String greet(*self) {
|
{
|
||||||
|
String greet(&self)
|
||||||
|
{
|
||||||
"hello".to_string()
|
"hello".to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_trait_impl() {
|
pub void test_trait_impl()
|
||||||
let d = Dog { name: "Rex".to_string() };
|
{
|
||||||
|
let d = Dog {
|
||||||
|
name: "Rex".to_string(),
|
||||||
|
};
|
||||||
assert_eq!(d.speak(), "woof");
|
assert_eq!(d.speak(), "woof");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void test_trait_with_requirement() {
|
pub void test_trait_with_requirement()
|
||||||
let d = Dog { name: "Buddy".to_string() };
|
{
|
||||||
|
let d = Dog {
|
||||||
|
name: "Buddy".to_string(),
|
||||||
|
};
|
||||||
assert_eq!(d.speak(), "woof");
|
assert_eq!(d.speak(), "woof");
|
||||||
assert_eq!(d.greet(), "hello");
|
assert_eq!(d.greet(), "hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn void run_tests() {
|
pub void run_tests()
|
||||||
|
{
|
||||||
test_trait_impl();
|
test_trait_impl();
|
||||||
test_trait_with_requirement();
|
test_trait_with_requirement();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
fn void main() {
|
void main()
|
||||||
|
{
|
||||||
println!("running common tests...");
|
println!("running common tests...");
|
||||||
common::test_package();
|
common::test_package();
|
||||||
common::expr_test::run_tests();
|
common::expr_test::run_tests();
|
||||||
common::statement_test::run_tests();
|
common::statement_test::run_tests();
|
||||||
common::decl_test::run_tests();
|
common::decl_test::run_tests();
|
||||||
common::types_test::run_tests();
|
common::types_test::run_tests();
|
||||||
|
|
||||||
println!("running items tests...");
|
println!("running items tests...");
|
||||||
items::function_test::run_tests();
|
items::function_test::run_tests();
|
||||||
items::struct_test::run_tests();
|
items::struct_test::run_tests();
|
||||||
@@ -14,6 +14,5 @@ fn void main() {
|
|||||||
items::trait_test::run_tests();
|
items::trait_test::run_tests();
|
||||||
items::impl_test::run_tests();
|
items::impl_test::run_tests();
|
||||||
items::attribute_test::run_tests();
|
items::attribute_test::run_tests();
|
||||||
|
|
||||||
println!("\x1b[32m\nAll tests passed!\x1b[0m");
|
println!("\x1b[32m\nAll tests passed!\x1b[0m");
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -1,3 +1,4 @@
|
|||||||
fn void main() {
|
void main()
|
||||||
|
{
|
||||||
mist_analyzer::start();
|
mist_analyzer::start();
|
||||||
}
|
}
|
||||||
|
|||||||
+142
-52
@@ -1,35 +1,64 @@
|
|||||||
use std::process;
|
use std::process;
|
||||||
|
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use mist_api::builder;
|
use mist_api::builder;
|
||||||
|
|
||||||
use mist_api::transpiler;
|
use mist_api::transpiler;
|
||||||
|
|
||||||
fn void main() {
|
void main()
|
||||||
let args Vec<String> = env::args().collect();
|
{
|
||||||
|
Vec<String> mut args = env::args().collect();
|
||||||
if args.len() < 2 {
|
if args.len() < 2 {
|
||||||
print_usage();
|
print_usage();
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
match args[1].as_str() {
|
match args[1].as_str() {
|
||||||
"run" | "build" | "check" | "r" | "b" | "c" => {
|
"run" | "build" | "check" | "test" | "bench" | "doc" | "fix" | "clippy" | "r" | "b" | "c" => {
|
||||||
let root = transpiler::transpile();
|
let mut root = env::current_dir().expect("Unable to find project root");
|
||||||
|
modify_args(&mut args, &mut root);
|
||||||
|
transpiler::transpile(&root);
|
||||||
|
|
||||||
println!("");
|
println!("");
|
||||||
|
|
||||||
if builder::build(args, root) {
|
if builder::build(args, root) {
|
||||||
println!("\x1b[32m\nBuild successful\x1b[0m");
|
println!("\x1b[32m\nBuild successful\x1b[0m");
|
||||||
} else {
|
} else {
|
||||||
println!("\x1b[31m\nBuild failed\x1b[0m");
|
println!("\x1b[31m\nBuild failed\x1b[0m");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"publish" => {
|
||||||
|
let mut root = env::current_dir().expect("Unable to find project root");
|
||||||
|
modify_args(&mut args, &mut root);
|
||||||
|
transpiler::transpile(&root);
|
||||||
|
|
||||||
|
let status = std::process::Command::new("cargo")
|
||||||
|
.args(args)
|
||||||
|
.status()
|
||||||
|
.expect("Failed to run cargo");
|
||||||
|
|
||||||
|
if status.success() {
|
||||||
|
println!("\x1b[32m\nPublished successfully\x1b[0m");
|
||||||
|
} else {
|
||||||
|
println!("\x1b[31m\nFailed to publish\x1b[0m");
|
||||||
|
}
|
||||||
|
}
|
||||||
"transpile" | "t" => {
|
"transpile" | "t" => {
|
||||||
transpiler::transpile();
|
let mut root = env::current_dir().expect("Unable to find project root");
|
||||||
|
modify_args(&mut args, &mut root);
|
||||||
|
transpiler::transpile(&root);
|
||||||
|
}
|
||||||
|
"clean" => {
|
||||||
|
args.remove(0);
|
||||||
|
process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
|
||||||
}
|
}
|
||||||
"init" => {
|
"init" => {
|
||||||
init_project(args);
|
init_project(args);
|
||||||
}
|
}
|
||||||
|
"new" => {
|
||||||
|
new_project(args);
|
||||||
|
}
|
||||||
"version" | "--version" | "-v" => {
|
"version" | "--version" | "-v" => {
|
||||||
println!("mist {}", env!("CARGO_PKG_VERSION"));
|
println!("mist {}", env!("CARGO_PKG_VERSION"));
|
||||||
}
|
}
|
||||||
@@ -44,62 +73,123 @@ fn void main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn void print_usage() {
|
void modify_args(Vec<String> mut& args, std::path::PathBuf mut& root)
|
||||||
println!("Mist - the mist compiler\n");
|
{
|
||||||
println!(" View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
|
if let Some(path_arg) = args.get(2) {
|
||||||
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
|
if path_arg == "--path" {
|
||||||
println!("usage:");
|
if args.len() > 3 {
|
||||||
println!(" \x1b[36m mist run\x1b[0m,\x1b[36m r\x1b[0m run the project in the current directory\n");
|
let path_arg = args[3].clone();
|
||||||
println!(
|
*root = root.join(&path_arg);
|
||||||
" \x1b[36m mist build\x1b[0m,\x1b[36m b\x1b[0m build the project in the current directory\n"
|
args.remove(2);
|
||||||
);
|
args.remove(2);
|
||||||
println!(
|
args.push(format!("--manifest-path={}/Cargo.toml", root.display()));
|
||||||
" \x1b[36m mist transpile\x1b[0m,\x1b[36m t\x1b[0m transpile the project in the current directory\n"
|
}
|
||||||
);
|
}
|
||||||
println!(
|
}
|
||||||
" \x1b[36m mist check\x1b[0m,\x1b[36m c\x1b[0m check the project in the current directory\n"
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" \x1b[36m mist init\x1b[0m initialize a project in the current folder\n"
|
|
||||||
);
|
|
||||||
println!(" \x1b[36m mist version \x1b[0m print the compiler version\n");
|
|
||||||
println!(" \x1b[36m mist help\x1b[0m print this message\n");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn void init_project(mut args Vec<String>) {
|
void print_usage()
|
||||||
|
{
|
||||||
|
println!("Mist - the mist compiler\n");
|
||||||
|
println!(" View our documentation! \x1b[95mhttps://mist.selimaj.dev\x1b[0m");
|
||||||
|
println!(" Follow us on github! \x1b[95mhttps://github.com/mist-go\x1b[0m\n");
|
||||||
|
println!("usage:");
|
||||||
|
println!(" \x1b[96m mist run\x1b[0m,\x1b[96m r\x1b[0m run the project\n");
|
||||||
|
println!(" \x1b[96m mist build\x1b[0m,\x1b[96m b\x1b[0m build the project\n");
|
||||||
|
println!(" \x1b[96m mist test\x1b[0m test the project\n");
|
||||||
|
println!(" \x1b[96m mist publish\x1b[0m publish the project\n");
|
||||||
|
println!(" \x1b[96m mist bench\x1b[0m benchmark the project\n");
|
||||||
|
println!(" \x1b[96m mist doc\x1b[0m build documentation\n");
|
||||||
|
println!(" \x1b[96m mist fix\x1b[0m automatically fix warnings\n");
|
||||||
|
println!(" \x1b[96m mist clippy\x1b[0m lint the project\n");
|
||||||
|
println!(" \x1b[96m mist check\x1b[0m,\x1b[96m c\x1b[0m check the project\n");
|
||||||
|
println!(" \x1b[96m mist clean\x1b[0m clean build artifacts\n");
|
||||||
|
println!(" \x1b[96m mist transpile\x1b[0m,\x1b[96m t\x1b[0m transpile the project\n");
|
||||||
|
println!(" \x1b[96m mist init\x1b[0m initialize a project in the current folder\n");
|
||||||
|
println!(" \x1b[96m mist new\x1b[0m create a new project\n");
|
||||||
|
println!(" \x1b[96m mist version \x1b[0m print the compiler version\n");
|
||||||
|
println!(" \x1b[96m mist help\x1b[0m print this message\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void init_project(Vec<String> mut args)
|
||||||
|
{
|
||||||
args.remove(0);
|
args.remove(0);
|
||||||
|
let status = process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
|
||||||
process::Command::new("cargo")
|
if !status.success() {
|
||||||
.args(args)
|
return;
|
||||||
.stdout(process::Stdio::inherit())
|
}
|
||||||
.stderr(process::Stdio::inherit())
|
bool is_lib = fs::metadata("src/lib.rs").is_ok();
|
||||||
.stdin(process::Stdio::inherit())
|
|
||||||
.spawn()
|
|
||||||
.expect("Failed to run cargo").wait().expect("Unable to wait");
|
|
||||||
|
|
||||||
let is_lib bool = fs::metadata("src/lib.rs").is_ok();
|
|
||||||
|
|
||||||
if is_lib {
|
if is_lib {
|
||||||
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
|
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
|
||||||
fs::write("src/lib.mist", "fn test() {\n}").expect("Failed to create src/lib.mist");
|
fs::write("src/lib.mist", "void test() {\n}").expect("Failed to create src/lib.mist");
|
||||||
} else {
|
} else {
|
||||||
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
|
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
|
||||||
fs::write("src/main.mist", "fn main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
|
fs::write("src/main.mist", "void main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
|
||||||
}
|
}
|
||||||
|
|
||||||
inject_mist_target(is_lib);
|
inject_mist_target(is_lib);
|
||||||
|
add_mist_toml(is_lib);
|
||||||
println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n");
|
add_gitignore();
|
||||||
|
println!("Thank you for using Mist!\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn void inject_mist_target(is_lib bool) {
|
void new_project(Vec<String> mut args)
|
||||||
let toml_content String = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
|
{
|
||||||
|
args.remove(0);
|
||||||
let inject *str = if is_lib {
|
if args.len() < 2 {
|
||||||
"\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n"
|
eprintln!("error: missing project name\n");
|
||||||
|
print_usage();
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
String project_name = args[1].clone();
|
||||||
|
let status = process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
|
||||||
|
if !status.success() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::path::PathBuf project_path = env::current_dir().expect("Unable to find project root").join(&project_name);
|
||||||
|
env::set_current_dir(&project_path).expect("Failed to change to project directory");
|
||||||
|
bool is_lib = fs::metadata("src/lib.rs").is_ok();
|
||||||
|
if is_lib {
|
||||||
|
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
|
||||||
|
fs::write("src/lib.mist", "void test() {\n}").expect("Failed to create src/lib.mist");
|
||||||
} else {
|
} else {
|
||||||
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"
|
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
|
||||||
|
fs::write("src/main.mist", "void main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
|
||||||
|
}
|
||||||
|
inject_mist_target(is_lib);
|
||||||
|
add_mist_toml(is_lib);
|
||||||
|
add_gitignore();
|
||||||
|
println!("Thank you for using Mist!\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void inject_mist_target(bool is_lib)
|
||||||
|
{
|
||||||
|
String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
|
||||||
|
toml::Value parsed = toml::from_str(&toml_content).expect("Failed to parse Cargo.toml");
|
||||||
|
String name = parsed["package"]["name"].as_str().expect("Missing package.name in Cargo.toml").to_string();
|
||||||
|
String inject = if is_lib {
|
||||||
|
format!("\n[lib]\nname = \"{name}\"\npath = \".mist/src/lib.rs\"\n")
|
||||||
|
} else {
|
||||||
|
format!("\n[[bin]]\nname = \"{name}\"\npath = \".mist/src/main.rs\"\n")
|
||||||
|
};
|
||||||
|
fs::write("Cargo.toml", toml_content + &inject).expect("Failed to inject to Cargo.toml");
|
||||||
|
}
|
||||||
|
|
||||||
|
void add_mist_toml(bool is_lib)
|
||||||
|
{
|
||||||
|
str& content = if is_lib {
|
||||||
|
"package = \"lib.mist\"\npackages = []\ninclude = []\n"
|
||||||
|
} else {
|
||||||
|
"package = \"main.mist\"\npackages = []\ninclude = []\n"
|
||||||
};
|
};
|
||||||
|
fs::write("Mist.toml", content).expect("Failed to add Mist.toml");
|
||||||
|
}
|
||||||
|
|
||||||
fs::write("Cargo.toml", toml_content+inject).expect("Failed to inject to Cargo.toml");
|
void add_gitignore()
|
||||||
|
{
|
||||||
|
if fs::metadata(".gitignore").is_ok() {
|
||||||
|
String content = fs::read_to_string(".gitignore").expect("Failed to read .gitignore");
|
||||||
|
if !content.contains(".mist") {
|
||||||
|
fs::write(".gitignore", content + "\n.mist\n").expect("Failed to write .gitignore");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user