Compare commits

...
Author SHA1 Message Date
selimaj-dev d8fd8cf999 Bump version 2026-06-28 16:01:01 +02:00
selimaj-dev 3ce8fe5278 Merge pull request #98 from mist-go/mist-fmt-style
Mist fmt style
2026-06-28 15:59:22 +02:00
selimaj-dev 2426e585d6 Fix constructor and non allman 2026-06-28 15:57:00 +02:00
selimaj-dev 2174b99a3f Fmt config 2026-06-28 15:52:02 +02:00
selimaj-dev 31eebb4baa Modularized bracket style 2026-06-28 15:16:33 +02:00
selimaj-dev 41f8b94c82 Merge pull request #97 from mist-go/tidy-grammar
VC: Tidy up the grammar/parser #94
2026-06-28 07:31:26 +02:00
selimaj-dev 64081bc494 Tidy up the grammar #94 2026-06-28 07:30:49 +02:00
selimaj-dev 3c6ebb66c6 Merge pull request #96 from mist-go/function-types
Function types
2026-06-28 06:06:50 +02:00
selimaj-dev a867dbc797 Fixed codegen for function type 2026-06-28 06:04:39 +02:00
selimaj-dev a2fc8a4922 AST gen for function type 2026-06-28 06:00:11 +02:00
selimaj-dev dbfcaa9b0d Void type 2026-06-28 05:49:35 +02:00
selimaj-dev 76541040c9 Function types 2026-06-28 05:45:13 +02:00
selimaj-dev 3ddb1bc601 Unsafe pointer 2026-06-28 05:24:30 +02:00
selimaj-dev bf5d243036 Merge pull request #92 from mist-go/small-analyzer-patches
Small analyzer patches
2026-06-27 04:31:02 +02:00
selimaj-dev b6b5214684 Fixed proc macro server error 2026-06-26 17:06:53 +02:00
selimaj-dev a37dffb94b On creation 2026-06-26 05:01:15 +02:00
selimaj-dev 84c75c290f Merge pull request #91 from mist-go/mist-fmt
Mist fmt
2026-06-26 02:36:03 +02:00
selimaj-dev 46e9783257 Fixed bugs 2026-06-26 02:04:33 +02:00
selimaj-dev 9b7de09b0a Fmt Allman style 2026-06-26 01:49:00 +02:00
selimaj-dev 6c9c0e03d2 Fix formatter bugs 2026-06-26 01:29:51 +02:00
selimaj-dev e5509e89a4 Working formatter #90 2026-06-26 01:02:01 +02:00
selimaj-dev fda193b8ff Mist fmt 2026-06-26 00:37:41 +02:00
selimaj-dev c78c9985f4 Mist fmt 2026-06-26 00:37:33 +02:00
selimaj-dev d0341deef9 Merge pull request #89 from mist-go/analyzer-patches
Analyzer(LSP) patches: Major Dev Exp improvements
2026-06-26 00:09:44 +02:00
selimaj-dev 26c0fb34e0 Improved keywords 2026-06-26 00:07:09 +02:00
selimaj-dev 75dd2e4af2 Fix a few snippets 2026-06-26 00:05:25 +02:00
selimaj-dev c47beae67d Contextual snippets (massive DX improvement) 2026-06-25 23:49:05 +02:00
selimaj-dev c6c33bf83b Improved completions 2026-06-25 23:28:11 +02:00
selimaj-dev 065dc575a5 Improved scope checking 2026-06-25 23:00:13 +02:00
selimaj-dev a1a3ce1a29 Removed analyzer debug file 2026-06-25 22:44:00 +02:00
selimaj-dev a63199a41d Removed fn from keywords 2026-06-25 22:24:25 +02:00
selimaj-dev 33430f9541 Merge pull request #88 from mist-go/separate-self-param
Separate self param
2026-06-25 20:08:38 +02:00
selimaj-dev 2549535e4b Updated codegen for class decl 2026-06-25 19:47:07 +02:00
selimaj-dev 243b4ba5d0 Updated codegen 2026-06-25 19:16:07 +02:00
selimaj-dev 4ab7827955 Added separate self param 2026-06-25 19:08:52 +02:00
selimaj-dev 2c11131e1a Merge pull request #87 from mist-go/rm-err-recovery
Remove: Error recovery
2026-06-25 04:21:24 +02:00
selimaj-dev 93e7a0fdef Updated api and analyzer with error recovery 2026-06-25 04:15:47 +02:00
selimaj-dev 0dd9e2fb37 Removed error recovery from items 2026-06-25 04:13:57 +02:00
selimaj-dev ae60aee85c Removed error recovery from common 2026-06-25 04:08:31 +02:00
selimaj-dev 6cc46751f9 Removed error recovery 2026-06-24 23:38:05 +02:00
selimaj-dev 2ef2232b84 Bump version 2026-06-24 14:40:39 +02:00
selimaj-dev 0cbfa10281 Merge pull request #85 from mist-go/improved-analyzer
Improved analyzer
2026-06-24 14:34:00 +02:00
selimaj-dev 9ce6d44eb4 Improved errors 2026-06-24 14:33:11 +02:00
selimaj-dev 1f2e989522 Fixed bugs #83 2026-06-24 14:11:57 +02:00
selimaj-dev ca11866328 Improved LSP completion ordering 2026-06-24 03:44:32 +02:00
selimaj-dev 055d50edd5 Bump version 2026-06-24 02:47:49 +02:00
selimaj-dev c8d7f05e67 Merge pull request #84 from mist-go/syntax-philosphy-update
Syntax philosphy update
2026-06-23 19:23:11 +02:00
selimaj-dev 9b1519b068 Updated code and readme 2026-06-23 19:19:22 +02:00
selimaj-dev dc8acdc2bd Improved match statements 2026-06-23 19:03:47 +02:00
selimaj-dev 97de75252d Updated api bootstrap 2026-06-23 18:33:05 +02:00
selimaj-dev 2f12f5ac53 Updated closure syntax 2026-06-23 17:41:49 +02:00
selimaj-dev e4b7b4abf9 Updated api bootstrap 2026-06-23 17:25:26 +02:00
selimaj-dev 208e4dac6b Updated main bootstrap 2026-06-23 16:41:56 +02:00
selimaj-dev b73396afb7 Fixed mod attribute generation 2026-06-23 13:24:46 +02:00
selimaj-dev 7f7c1e2000 Fixed mod attributes 2026-06-23 12:47:38 +02:00
selimaj-dev 2f6303ba30 Updated tests and fixed grammar 2026-06-23 03:44:54 +02:00
selimaj-dev 2ae4ca510d Using & for refrences, and switched to type name 2026-06-23 03:26:30 +02:00
58 changed files with 3028 additions and 1125 deletions
+3
View File
@@ -29,3 +29,6 @@ target
**/build **/build
.mist/ .mist/
analyzer.bat
analyzer.sh
Generated
+13 -5
View File
@@ -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,11 @@ dependencies = [
[[package]] [[package]]
name = "mist-analyzer" name = "mist-analyzer"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.0"
dependencies = [ dependencies = [
"cargo_metadata", "cargo_metadata",
"dashmap 6.1.0", "dashmap 6.1.0",
"heck",
"mist-codegen", "mist-codegen",
"mist-parser", "mist-parser",
"pest", "pest",
@@ -481,12 +488,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.3.7-alpha.0"
dependencies = [ dependencies = [
"cargo_metadata", "cargo_metadata",
"mist-codegen", "mist-codegen",
@@ -498,7 +506,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-codegen" name = "mist-codegen"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.0"
dependencies = [ dependencies = [
"bytecount", "bytecount",
"mist-parser", "mist-parser",
@@ -506,7 +514,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-lang" name = "mist-lang"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.0"
dependencies = [ dependencies = [
"mist-analyzer", "mist-analyzer",
"mist-api", "mist-api",
@@ -514,7 +522,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-parser" name = "mist-parser"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.0"
dependencies = [ dependencies = [
"pest", "pest",
"pest_derive", "pest_derive",
+5 -5
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-lang" name = "mist-lang"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.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"
@@ -32,10 +32,10 @@ exclude = [
] ]
[workspace.dependencies] [workspace.dependencies]
mist-parser = { path = "crates/parser", version = "0.3.5-alpha.0" } mist-parser = { path = "crates/parser", version = "0.3.7-alpha.0" }
mist-analyzer = { path = "crates/analyzer", version = "0.3.5-alpha.0" } mist-analyzer = { path = "crates/analyzer", version = "0.3.7-alpha.0" }
mist-codegen = { path = "crates/codegen", version = "0.3.5-alpha.0" } mist-codegen = { path = "crates/codegen", version = "0.3.7-alpha.0" }
mist-api = { path = "crates/mist-api", version = "0.3.5-alpha.0" } mist-api = { path = "crates/mist-api", version = "0.3.7-alpha.0" }
[[bin]] [[bin]]
name = "mist" name = "mist"
+1 -1
View File
@@ -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
-9
View File
@@ -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
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 55 KiB

+3 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-analyzer" name = "mist-analyzer"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.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"
@@ -21,3 +21,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"
+795 -195
View File
File diff suppressed because it is too large Load Diff
+8 -7
View File
@@ -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,11 +327,8 @@ 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, .await?;
InitializedParams {},
)
.await?;
Ok(()) Ok(())
} }
} }
+61 -10
View File
@@ -1,8 +1,9 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use mist_codegen::RustCodegen; use mist_codegen::RustCodegen;
use mist_codegen::fmt::MistCodegen;
use mist_parser::rev_mapper::Mapping; use mist_parser::rev_mapper::Mapping;
use mist_parser::parse; use mist_parser::{MistFmtConfig, parse};
pub struct TranspiledFile { pub struct TranspiledFile {
pub mist_path: PathBuf, pub mist_path: PathBuf,
@@ -11,7 +12,49 @@ pub struct TranspiledFile {
pub mapping: Mapping, pub mapping: Mapping,
} }
pub fn transpile_mist( #[derive(Debug)]
pub enum TranspileError<'a> {
Parse(mist_parser::error::ParseError<'a>),
Semantic(Vec<mist_parser::semantics::SemanticError>),
}
pub fn transpile_mist<'a>(
mist_path: &Path,
source: &'a str,
extra_mod_decl: &str,
) -> Result<TranspiledFile, TranspileError<'a>> {
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(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());
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,
})
}
/// No Semantics
pub fn transpile_mist_no_sem(
mist_path: &Path, mist_path: &Path,
source: &str, source: &str,
extra_mod_decl: &str, extra_mod_decl: &str,
@@ -26,20 +69,28 @@ pub fn transpile_mist(
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?; let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
for item in &parsed {
mist_parser::semantics::check_class_semantics(item)
.map_err(|e| format!("semantic error: {}", e[0].error_message))?;
}
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,
}) })
} }
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)
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-codegen" name = "mist-codegen"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.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"
+35 -35
View File
@@ -51,7 +51,7 @@ impl ClassProcessedData {
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.self_param.is_some() {
v_table.push(method.item.name.clone()); v_table.push(method.item.name.clone());
} }
} }
@@ -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)),
}, },
); );
@@ -375,20 +375,6 @@ 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,
@@ -397,7 +383,8 @@ impl ClassProcessedData {
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 +396,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.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);
} }
@@ -513,12 +500,32 @@ 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) {
cg.add_indented(&format!( let mutable_self = if let Some((is_ref, lifetime, is_mut)) = &method.self_param {
"{}fn {}{}(", cg.add_indented(&format!(
method.visibility.get_rust(), "{}fn {}{}(",
method.name.get_rust(), method.visibility.get_rust(),
method.generics.get_rust(), method.name.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
@@ -566,14 +573,10 @@ 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("std")),
@@ -588,16 +591,13 @@ 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(" = std::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 *const std::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 std::ffi::c_void");
} }
for (i, param) in &params { for (_, param) in &params {
if *i == 0 {
continue; // self already fulfills it
}
cg.add(", "); cg.add(", ");
ctx.expr_ensure_semicolon = false; ctx.expr_ensure_semicolon = false;
param.name.gen_rust(ctx, cg); param.name.gen_rust(ctx, cg);
-5
View File
@@ -256,11 +256,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"),
} }
+171
View File
@@ -0,0 +1,171 @@
use mist_parser::ast::*;
use crate::fmt::{Context, GenMist, GetMist, MistCodegen};
impl GenMist for Expression {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
let ensure_semicolon = if ctx.expr_ensure_semicolon {
ctx.expr_ensure_semicolon = false;
true
} else {
false
};
match self {
Expression::Path(path) => cg.add(&path.get_mist()),
Expression::Literal(literal) => literal.gen_mist(ctx, cg),
Expression::Statement(stmt) => stmt.gen_mist(ctx, cg),
Expression::Array(values) => {
cg.add("[");
for (i, val) in values.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
val.gen_mist(ctx, cg);
}
cg.add("]");
}
Expression::ArrayRepeat(value, repeat) => {
cg.add("[");
value.gen_mist(ctx, cg);
cg.add("; ");
repeat.gen_mist(ctx, cg);
cg.add("]");
}
Expression::Fix {
initial,
prefixes,
postfixes,
} => {
for prefix in prefixes {
prefix.gen_mist(ctx, cg);
}
initial.gen_mist(ctx, cg);
for postfix in postfixes {
postfix.gen_mist(ctx, cg);
}
}
Expression::Binary { lhs, op, rhs } => {
lhs.gen_mist(ctx, cg);
cg.add(" ");
cg.add(op);
cg.add(" ");
rhs.gen_mist(ctx, cg);
}
Expression::Closure {
return_type,
params,
body,
} => {
cg.add("(");
for (i, arg) in params.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
arg.gen_mist(ctx, cg);
}
cg.add(") => ");
if let Some(ty) = return_type {
cg.add(&ty.get_mist());
cg.add(" ");
cg.ensure_brackets_expr(ctx, body);
} else {
body.gen_mist(ctx, cg);
}
}
}
if ensure_semicolon {
ctx.expr_ensure_semicolon = true;
if !self.is_block() {
cg.add(";");
}
}
}
}
impl GenMist for Prefix {
fn gen_mist(&self, _ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Self::Deref => cg.add("*"),
Self::Ref => cg.add("&"),
Self::RefMut => cg.add("&mut "),
Self::Not => cg.add("!"),
Self::Neg => cg.add("-"),
}
}
}
impl GenMist for Postfix {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Postfix::TupleFieldAccess(field, generics) => {
cg.add(&format!(
".{}{}",
field,
generics
.iter()
.map(|v| format!("::{}", v.get_mist()))
.collect::<String>()
));
}
Postfix::FieldAccess(field, generics) => {
cg.add(&format!(
".{}{}",
field.get_mist(),
generics
.iter()
.map(|v| format!("::{}", v.get_mist()))
.collect::<String>()
));
}
Postfix::Call(args) => {
cg.add("(");
for (i, arg) in args.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
arg.gen_mist(ctx, cg);
}
cg.add(")");
}
Postfix::MacroCall { inner, delimiter } => {
let (open, close) = match delimiter {
MacroDelimiter::Paren => ("!(", ")"),
MacroDelimiter::Bracket => ("![", "]"),
MacroDelimiter::Brace => ("!{", "}"),
};
cg.add(open);
cg.add(inner);
cg.add(close);
}
Postfix::StructCall(fields) => {
cg.addln(" {");
cg.indent += 1;
for (name, expr) in fields {
cg.add_indented(&name.get_mist());
if let Some(expr) = expr {
cg.add(": ");
expr.gen_mist(ctx, cg);
}
cg.addln(",");
}
cg.indent -= 1;
cg.add_indented("}");
}
Postfix::Index(idx) => {
cg.add("[");
idx.gen_mist(ctx, cg);
cg.add("]");
}
Postfix::As(ty) => {
cg.add(" as ");
cg.add(&ty.get_mist());
}
Postfix::Try => cg.add("?"),
Postfix::Increment => cg.add("++"),
Postfix::Decrement => cg.add("--"),
}
}
}
+450
View File
@@ -0,0 +1,450 @@
pub mod expr;
pub mod statement;
pub mod top_level;
use mist_parser::{MistFmtConfig, ast::*};
pub struct Context {
pub expr_ensure_semicolon: bool,
}
pub struct MistCodegen {
config: MistFmtConfig,
indent_amount: u8,
output: String,
indent: usize,
}
impl MistCodegen {
pub fn new(config: MistFmtConfig) -> Self {
Self {
config,
output: String::new(),
indent: 0,
indent_amount: 4,
}
}
fn indent_str(&self) -> String {
" ".repeat(self.indent_amount as usize).repeat(self.indent)
}
pub fn add(&mut self, s: &str) {
self.output.push_str(s);
}
pub fn addln(&mut self, s: &str) {
self.add(s);
self.add("\n");
}
pub fn add_indented(&mut self, s: &str) {
let line = format!("{}{}", self.indent_str(), s);
self.add(&line);
}
pub fn add_indentedln(&mut self, s: &str) {
let line = format!("{}{}\n", self.indent_str(), s);
self.add(&line);
}
pub fn start_indent(&mut self) {
if self.config.allman_bracket_style {
self.addln("");
self.add_indented("");
} else {
self.add(" ");
}
}
pub fn start_bracket(&mut self) {
if self.config.allman_bracket_style {
self.addln("");
self.add_indentedln("{");
} else {
self.addln(" {");
}
self.indent += 1;
}
pub fn into_output(self) -> String {
self.output
}
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
let mut ctx = Context {
expr_ensure_semicolon: true,
};
for (i, tl) in toplevels.iter().enumerate() {
if i > 0 {
self.add("\n");
}
tl.gen_mist(&mut ctx, self);
}
self.output.clone()
}
pub fn ensure_brackets(&mut self, ctx: &mut Context, stmt: &Box<Statement>) {
match &**stmt {
Statement::Block(_) => stmt.gen_mist(ctx, self),
_ => {
self.add("{");
self.indent += 1;
stmt.gen_mist(ctx, self);
self.indent -= 1;
self.add_indented("}");
}
}
}
pub fn ensure_brackets_expr(&mut self, ctx: &mut Context, expr: &Expression) {
match expr {
Expression::Statement(stmt) => self.ensure_brackets(ctx, stmt),
_ => {
self.add("{");
self.indent += 1;
expr.gen_mist(ctx, self);
self.indent -= 1;
self.add_indented("}");
}
}
}
}
pub trait GenMist {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen);
}
pub trait GetMist {
fn get_mist(&self) -> String;
}
impl GetMist for Path {
fn get_mist(&self) -> String {
self.0
.iter()
.map(Identifier::get_mist)
.collect::<Vec<String>>()
.join("::")
}
}
impl GetMist for Identifier {
fn get_mist(&self) -> String {
self.0.clone()
}
}
impl GetMist for Visibility {
fn get_mist(&self) -> String {
match self {
Visibility::Public => "pub ".to_string(),
Visibility::PublicTarget(path) => format!("pub({}) ", path.get_mist()),
Visibility::Private => "".to_string(),
}
}
}
impl GetMist for TypeExpr {
fn get_mist(&self) -> String {
match self {
Self::Path(path, generics) => {
if let Some(generics) = generics {
format!("{}{}", path.get_mist(), generics.get_mist())
} else {
path.get_mist()
}
}
Self::Lifetime(name) => format!("'{}", name.get_mist()),
Self::Tuple(types) => format!(
"({})",
types
.iter()
.map(|t| t.get_mist())
.collect::<Vec<_>>()
.join(", ")
),
Self::StaticFn(types, return_type) => {
if let Some(return_type) = return_type {
format!(
"fn({}) -> {}",
types
.iter()
.map(|t| t.get_mist())
.collect::<Vec<_>>()
.join(", "),
return_type.get_mist()
)
} else {
format!(
"fn({})",
types
.iter()
.map(|t| t.get_mist())
.collect::<Vec<_>>()
.join(", "),
)
}
}
Self::UnsafePtr { mutable, ty } => {
let mutable = if *mutable { "mut " } else { "const " };
format!("{} {mutable} unsafe&", ty.get_mist())
}
Self::Ref {
lifetime,
mutable,
ty,
} => {
let base = ty.get_mist();
if let Some(lifetime) = lifetime {
format!(
"{} {} '{}&",
base,
if *mutable { "mut" } else { "" },
lifetime.get_mist()
)
} else if *mutable {
format!("{} mut&", base)
} else {
format!("{}&", base)
}
}
Self::Dyn(ty) => {
format!("dyn {}", ty.get_mist())
}
Self::Void => "void".to_string(),
Self::Fn {
kind,
return_type,
params,
} => {
format!(
"{} {}({})",
return_type.get_mist(),
kind.get_mist(),
params
.iter()
.map(TypeExpr::get_mist)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
}
impl GetMist for FnKind {
fn get_mist(&self) -> String {
match self {
Self::Fn => "fn",
Self::UnsafeFn => "unsafe fn",
Self::FnClosure => "Fn",
Self::FnMut => "FnMut",
Self::FnOnce => "FnOnce",
}
.to_string()
}
}
impl GetMist for ExprPath {
fn get_mist(&self) -> String {
self.0
.iter()
.map(ExprPathSegment::get_mist)
.collect::<Vec<_>>()
.join("::")
}
}
impl GetMist for ExprPathSegment {
fn get_mist(&self) -> String {
format!(
"{}{}",
self.ident.get_mist(),
self.generics
.as_ref()
.map(|v| format!("::{}", v.get_mist()))
.unwrap_or_default()
)
}
}
impl GetMist for Generics {
fn get_mist(&self) -> String {
if self.0.is_empty() {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(Generic::get_mist)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetMist for Generic {
fn get_mist(&self) -> String {
match self {
Self::Lifetime(name) => format!("'{}", name.get_mist()),
Self::Type(ty) => ty.get_mist(),
}
}
}
impl GetMist for GenericsDecl {
fn get_mist(&self) -> String {
if self.0.is_empty() {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(|v| v.get_mist())
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetMist for GenericDecl {
fn get_mist(&self) -> String {
match self {
GenericDecl::Lifetime(name) => format!("'{}", name.get_mist()),
GenericDecl::Type(name, requirements) => {
name.get_mist()
+ &(if !requirements.is_empty() {
format!(
": {}",
requirements
.iter()
.map(TypeExpr::get_mist)
.collect::<Vec<_>>()
.join(" + ")
)
} else {
String::new()
})
}
}
}
}
impl<T: GetMist> GenMist for T {
fn gen_mist(&self, _: &mut Context, cg: &mut MistCodegen) {
cg.add(&self.get_mist());
}
}
impl<T: GenMist> GenMist for Spanned<T> {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
self.item.gen_mist(ctx, cg);
}
}
impl GenMist for Attribute {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Self::Path(path) => cg.add(&path.get_mist()),
Self::NameValue { path, value } => {
cg.add(&format!("{} = ", path.get_mist()));
value.gen_mist(ctx, cg);
}
Self::List { path, items } => {
cg.add(&path.get_mist());
cg.add("(");
for (i, item) in items.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
item.gen_mist(ctx, cg);
}
cg.add(")");
}
}
}
}
impl GenMist for Pattern {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Self::Etc => cg.add(".."),
Self::Literal(lit) => lit.gen_mist(ctx, cg),
Self::Path(mutable, path) => {
if *mutable {
cg.add("mut ");
}
cg.add(&path.get_mist())
}
Self::Struct(path, inner) => {
cg.add(&path.get_mist());
cg.add(" {");
for (idx, i) in inner.iter().enumerate() {
if idx > 0 {
cg.add(", ");
}
if let Some((name, pat)) = i {
cg.add(&name.get_mist());
if let Some(pat) = pat {
cg.add(": ");
pat.gen_mist(ctx, cg);
}
} else {
cg.add("..");
}
}
cg.add("}");
}
Self::NamedTuple(path, inner) => {
cg.add(&path.get_mist());
cg.add("(");
for (i, pat) in inner.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
pat.gen_mist(ctx, cg);
}
cg.add(")");
}
Self::Tuple(inner) => {
cg.add("(");
for (i, pat) in inner.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
pat.gen_mist(ctx, cg);
}
cg.add(")");
}
}
}
}
impl GenMist for Literal {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Self::Int(n) => cg.add(&n.to_string()),
Self::Float(n) => cg.add(&format!("{n:?}")),
Self::Bool(b) => cg.add(&b.to_string()),
Self::String(s) => cg.add(&format!("\"{s}\"")),
Self::Tuple(values) => {
cg.add("(");
for (i, val) in values.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
val.gen_mist(ctx, cg);
}
cg.add(")");
}
}
}
}
+157
View File
@@ -0,0 +1,157 @@
use mist_parser::ast::*;
use crate::fmt::{Context, GenMist, GetMist, MistCodegen};
impl GenMist for Block {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
cg.addln("{");
cg.indent += 1;
for stmt in &self.statements {
ctx.expr_ensure_semicolon = true;
cg.add_indented("");
stmt.gen_mist(ctx, cg);
cg.addln("");
}
if let Some(soft_return) = &self.soft_return {
ctx.expr_ensure_semicolon = false;
cg.add_indented("");
soft_return.gen_mist(ctx, cg);
cg.addln("");
}
cg.indent -= 1;
cg.add_indented("}");
}
}
impl GenMist for Statement {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Statement::UnsafeBlock(block) => {
cg.add("unsafe ");
block.gen_mist(ctx, cg);
}
Statement::Block(block) => block.gen_mist(ctx, cg),
Statement::VarDecl(VarDeclStmt { decl, init }) => {
if decl.type_.is_some() {
cg.add(&decl.type_.as_ref().unwrap().get_mist());
cg.add(" ");
decl.name.gen_mist(ctx, cg);
} else {
cg.add("let ");
decl.name.gen_mist(ctx, cg);
}
if let Some(init) = init {
cg.add(" = ");
init.gen_mist(ctx, cg);
}
}
Statement::Match(expr, match_items) => {
cg.add("match ");
expr.gen_mist(ctx, cg);
cg.add(" {");
if !match_items.is_empty() {
cg.addln("");
cg.indent += 1;
for match_item in match_items {
let MatchItem(pat, body) = &match_item.item;
cg.add_indented("");
for (i, p) in pat.iter().enumerate() {
if i > 0 {
cg.add(" | ");
}
p.gen_mist(ctx, cg);
}
cg.add(" => ");
if body.is_block() {
body.gen_mist(ctx, cg);
cg.addln("");
} else {
ctx.expr_ensure_semicolon = false;
body.gen_mist(ctx, cg);
cg.addln(",");
}
}
cg.indent -= 1;
cg.add_indented("}");
} else {
cg.add("}");
}
}
Statement::If {
initial,
else_if,
else_branch,
} => {
cg.add("if ");
ctx.expr_ensure_semicolon = false;
initial.condition.gen_mist(ctx, cg);
cg.add(" ");
initial.body.gen_mist(ctx, cg);
for else_if_branch in else_if {
cg.add(" else if ");
ctx.expr_ensure_semicolon = false;
else_if_branch.condition.gen_mist(ctx, cg);
cg.add(" ");
else_if_branch.body.gen_mist(ctx, cg);
}
if let Some(else_br) = else_branch {
cg.add(" else ");
else_br.gen_mist(ctx, cg);
}
}
Statement::While(StatementBranch { condition, body }) => {
cg.add("while ");
condition.gen_mist(ctx, cg);
cg.add(" ");
body.gen_mist(ctx, cg);
}
Statement::Loop(body) => {
cg.add("loop ");
body.gen_mist(ctx, cg);
}
Statement::CStyleFor {
init,
condition,
update,
body,
} => {
cg.add("for (");
ctx.expr_ensure_semicolon = true;
init.gen_mist(ctx, cg);
cg.add(" ");
ctx.expr_ensure_semicolon = false;
condition.gen_mist(ctx, cg);
cg.add(" ");
update.gen_mist(ctx, cg);
cg.add(") ");
body.gen_mist(ctx, cg);
}
Statement::For {
pattern,
iterator,
body,
} => {
cg.add("for ");
pattern.gen_mist(ctx, cg);
cg.add(" in ");
iterator.gen_mist(ctx, cg);
cg.add(" ");
body.gen_mist(ctx, cg);
}
Statement::Return(expr) => {
cg.add("return");
if let Some(expr) = expr {
cg.add(" ");
expr.gen_mist(ctx, cg);
}
}
Statement::Break => cg.add("break"),
Statement::Continue => cg.add("continue"),
}
}
}
+336
View File
@@ -0,0 +1,336 @@
use mist_parser::ast::*;
use crate::fmt::{Context, GenMist, GetMist, MistCodegen};
impl GenMist for ImplDecl {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
cg.add_indented("impl ");
let generics = self.generics.get_mist();
if !generics.is_empty() {
cg.add(&generics);
cg.add(" ");
}
if let Some(trait_) = &self.trait_ {
cg.add(&trait_.get_mist());
cg.add(" for ");
}
cg.add(&self.target.get_mist());
cg.start_bracket();
for method in &self.methods {
method.gen_mist(ctx, cg);
}
cg.indent -= 1;
cg.add_indentedln("}");
}
}
impl GenMist for FunctionDecl {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
cg.add_indented(&self.visibility.get_mist());
if self.return_type.is_none() {
cg.add("void ");
} else {
cg.add(&self.return_type.as_ref().unwrap().get_mist());
cg.add(" ");
}
cg.add(&self.name.get_mist());
cg.add(&self.generics.get_mist());
cg.add("(");
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");
if !self.params.0.is_empty() {
cg.add(", ");
}
}
for (i, param) in self.params.0.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
param.gen_mist(ctx, cg);
}
cg.add(")");
if let Some(override_spec) = &self.is_override {
cg.add(" override");
if let Some(path) = &override_spec.0 {
cg.add("(");
cg.add(&path.get_mist());
cg.add(")");
}
}
if let Some(body) = &self.body {
cg.start_indent();
body.gen_mist(ctx, cg);
cg.addln("");
} else {
cg.addln(";");
}
}
}
impl GenMist for ParamList {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
for (i, param) in self.0.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
param.gen_mist(ctx, cg);
}
}
}
impl GenMist for VarDecl {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
if let Some(type_) = &self.type_ {
cg.add(&type_.get_mist());
cg.add(" ");
}
self.name.gen_mist(ctx, cg);
}
}
impl GetMist for FieldDecl {
fn get_mist(&self) -> String {
format!(
"{}{} {}",
self.visibility.get_mist(),
self.type_.get_mist(),
self.name.get_mist(),
)
}
}
impl GetMist for EnumItem {
fn get_mist(&self) -> String {
match self {
Self::Named(id) => id.get_mist(),
Self::Struct(id, s) => format!(
"{} {{{}}}",
id.get_mist(),
s.iter()
.map(FieldDecl::get_mist)
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(id, t) => format!(
"{}({})",
id.get_mist(),
t.iter()
.map(TypeExpr::get_mist)
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GenMist for TopLevel {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
if let TopLevelKind::ModAttribute = self.0.item {
for attr in &self.1 {
cg.add("#![");
attr.gen_mist(ctx, cg);
cg.addln("]");
}
} else {
for attr in &self.1 {
cg.add("#[");
attr.gen_mist(ctx, cg);
cg.addln("]");
}
}
self.0.gen_mist(ctx, cg);
}
}
impl GenMist for TopLevelKind {
fn gen_mist(&self, ctx: &mut Context, cg: &mut MistCodegen) {
match self {
Self::ModAttribute => {}
Self::Import(vis, path) => {
cg.addln(&format!("{}use {};", vis.get_mist(), path.get_mist()))
}
Self::DeclareModule(vis, name) => {
cg.addln(&format!("{}module {};", vis.get_mist(), name.get_mist()))
}
Self::FunctionDecl(decl) => decl.gen_mist(ctx, cg),
Self::ImplDecl(impl_) => impl_.gen_mist(ctx, cg),
Self::StructDecl {
visibility,
name,
generics,
fields,
} => {
cg.add(&format!(
"{}struct {}{}",
visibility.get_mist(),
name.get_mist(),
generics.get_mist()
));
if fields.is_empty() {
cg.add(" {}");
} else {
cg.start_bracket();
for field in fields {
cg.add_indentedln(&format!("{},", field.item.get_mist()));
}
cg.indent -= 1;
cg.add_indented("}");
}
cg.addln("");
}
Self::EnumDecl {
visibility,
name,
generics,
fields,
} => {
cg.add(&format!(
"{}enum {}{}",
visibility.get_mist(),
name.get_mist(),
generics.get_mist()
));
if fields.is_empty() {
cg.add(" {}");
} else {
cg.start_bracket();
for field in fields {
cg.add_indentedln(&format!("{},", field.item.get_mist()));
}
cg.indent -= 1;
cg.add_indented("}");
}
cg.addln("");
}
Self::TraitDecl {
visibility,
name,
generics,
requirements,
items,
} => {
cg.add(&format!(
"{}trait {}{}",
visibility.get_mist(),
name.get_mist(),
generics.get_mist()
));
if !requirements.is_empty() {
cg.add(" : ");
cg.add(
&requirements
.iter()
.map(TypeExpr::get_mist)
.collect::<Vec<_>>()
.join(" + "),
);
}
cg.start_bracket();
for item in items {
item.gen_mist(ctx, cg);
}
cg.indent -= 1;
cg.add_indentedln("}");
}
Self::ClassDecl {
visibility,
name,
generics,
inherits,
fields,
constructor,
items,
} => {
cg.add(&format!(
"{}class {}{}",
visibility.get_mist(),
name.get_mist(),
generics.get_mist()
));
if let Some(inherits) = inherits {
cg.add(" : ");
cg.add(&inherits.get_mist());
}
cg.start_bracket();
for field in fields {
cg.add_indented(&field.item.decl.get_mist());
if let Some(init) = &field.item.init {
cg.add(" = ");
init.gen_mist(ctx, cg);
}
cg.addln(";");
}
if let Some(constructor) = constructor {
if fields.len() > 0 {
cg.addln("");
}
cg.add_indented(&constructor.item.visibility.get_mist());
cg.add("constructor");
cg.add(&constructor.item.generics.get_mist());
cg.add("(");
for (i, param) in constructor.item.params.0.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
param.gen_mist(ctx, cg);
}
cg.add(") ");
cg.start_indent();
constructor.item.body.gen_mist(ctx, cg);
cg.addln("");
if items.len() > 0 {
cg.addln("");
}
}
for (i, item) in items.iter().enumerate() {
if i > 0 {
cg.addln("");
}
match item {
ClassItem::Method(method) => method.gen_mist(ctx, cg),
ClassItem::ImplDecl(impl_) => impl_.gen_mist(ctx, cg),
}
}
cg.indent -= 1;
cg.add_indentedln("}");
}
}
}
}
+41 -21
View File
@@ -1,5 +1,6 @@
pub mod class_decl; pub mod class_decl;
pub mod expr; pub mod expr;
pub mod fmt;
pub mod statement; pub mod statement;
pub mod top_level; pub mod top_level;
@@ -48,7 +49,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,17 +64,17 @@ 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);
} }
@@ -246,23 +247,12 @@ impl GetRust for TypeExpr {
ty, ty,
} => { } => {
if let Some(lifetime) = lifetime { if let Some(lifetime) = lifetime {
match lifetime { format!(
Lifetime::Lifetime(v) => { "&'{} {}{}",
format!( lifetime.get_rust(),
"&'{} {}{}", if *mutable { "mut " } else { "" },
v.get_rust(), ty.get_rust()
if *mutable { "mut " } else { "" }, )
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,10 +261,40 @@ 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(),
)
}
} }
} }
} }
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()
}
}
impl GenRust for Pattern { impl GenRust for Pattern {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) { fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self { match self {
+16
View File
@@ -80,6 +80,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(", ");
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-api" name = "mist-api"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.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"
+14 -14
View File
@@ -11,11 +11,11 @@ use mist_parser::rev_mapper;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MistDiagnosticMessage { pub struct MistDiagnosticMessage {
pub message String, pub String message,
pub file_path PathBuf, pub PathBuf file_path,
pub file_name String , pub String file_name,
pub line usize, pub usize line,
pub column usize, pub usize column,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -25,7 +25,7 @@ pub enum MistDiagnostic {
Rust(CompilerMessage), 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());
@@ -57,7 +57,7 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
break; break;
} }
let map = mapping.entry(mapping_path.clone()).or_insert_with(fn() { let map = mapping.entry(mapping_path.clone()).or_insert_with(() => {
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")
@@ -107,7 +107,7 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
let mut stdout = std::io::stdout(); let mut stdout = std::io::stdout();
std::io::copy(&mut raw_reader, &mut stdout) std::io::copy(&mut raw_reader, &mut stdout)
.map_err(fn(v) -> v.to_string()) .map_err((v) => v.to_string())
.expect("(Mist) Failed to copy IO"); .expect("(Mist) Failed to copy IO");
command.wait().unwrap(); command.wait().unwrap();
@@ -123,7 +123,7 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
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 {
@@ -159,13 +159,13 @@ pub fn void print_diagnostics(diagnostics *Vec<MistDiagnostic>) {
} }
} }
pub fn Option<String> get_line( pub Option<String> get_line(
files *mut HashMap<PathBuf, Vec<String>>, HashMap<PathBuf, Vec<String>> mut& files,
msg *MistDiagnosticMessage, MistDiagnosticMessage& msg,
) { ) {
let src_path = msg.file_path.clone(); let src_path = msg.file_path.clone();
let lines = files.entry(src_path.clone()).or_insert_with(fn() { let lines = files.entry(src_path.clone()).or_insert_with(() => {
fs::read_to_string(src_path) fs::read_to_string(src_path)
.expect("Unable to read mist file") .expect("Unable to read mist file")
.lines() .lines()
@@ -174,5 +174,5 @@ pub fn Option<String> get_line(
.collect() .collect()
}); });
lines.get(msg.line - 1).map(fn(v) -> v.trim().to_string()) lines.get(msg.line - 1).map((v) => v.trim().to_string())
} }
+16 -10
View File
@@ -9,14 +9,14 @@ use crate::transpiler::MistConfig;
#[derive(Debug)] #[derive(Debug)]
pub class Module { pub class Module {
pub name String; pub String name;
pub path PathBuf; pub PathBuf path;
pub children Vec<Module>; 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(fn(s) -> s.to_str()) .and_then((s) => s.to_str())
.expect("Failed to get module name") .expect("Failed to get module name")
.to_string(); .to_string();
self.path = mist_path; self.path = mist_path;
@@ -37,7 +37,7 @@ pub class Module {
} }
} }
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) => {
@@ -65,11 +65,11 @@ pub class Module {
} }
} }
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,7 +77,13 @@ 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 let Some((_, name)) = curr_mod_decl {
&name.0 &name.0
} else { } else {
+40 -25
View File
@@ -16,13 +16,13 @@ use serde::Deserialize;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct MistConfig { pub struct MistConfig {
pub package PathBuf, pub PathBuf package,
pub packages Vec<PathBuf>, pub Vec<PathBuf> packages,
pub main_mods String pub String main_mods
} }
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;
} }
@@ -37,7 +37,7 @@ impl MistConfig {
} }
} }
impl Default for MistConfig { impl Default for MistConfig {
fn Self default() { Self default() {
Self { Self {
package: PathBuf::from("main.mist"), package: PathBuf::from("main.mist"),
packages: Vec::new(), packages: Vec::new(),
@@ -46,7 +46,7 @@ impl Default for MistConfig {
} }
} }
pub fn PathBuf transpile() { pub PathBuf transpile() {
let start = time::Instant::now(); let start = time::Instant::now();
let root = env::current_dir().expect("Unable to find project root"); let root = env::current_dir().expect("Unable to find project root");
@@ -56,10 +56,10 @@ pub fn PathBuf transpile() {
let out = root.join(".mist/src"); let out = root.join(".mist/src");
let toml_content = fs::read_to_string(&toml_path) let toml_content = fs::read_to_string(&toml_path)
.unwrap_or_else(fn(_) -> panic!("Could not read file at {:?}", toml_path)); .unwrap_or_else((_) => panic!("Could not read file at {:?}", toml_path));
let mut config MistConfig = toml::from_str(&toml_content) MistConfig mut config = toml::from_str(&toml_content)
.unwrap_or_else(fn(_) -> panic!("Failed to parse Mist.toml from {:?}", toml_path)); .unwrap_or_else((_) => 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);
@@ -85,10 +85,10 @@ pub fn PathBuf transpile() {
} }
impl modules::Module { impl modules::Module {
fn (bool, String) transpile(*self, parent_dir *PathBuf, config *mut MistConfig) { (bool, String) transpile(&self, PathBuf& parent_dir, MistConfig mut& config) {
if !self.path.is_dir() && self.path.extension().and_then(fn(v) -> v.to_str()) != Some("mist") { if !self.path.is_dir() && self.path.extension().and_then((v) => v.to_str()) != Some("mist") {
let file_name = self.path.file_name() let file_name = self.path.file_name()
.and_then(fn(s) -> s.to_str()) .and_then((s) => s.to_str())
.expect("Failed to get file name"); .expect("Failed to get file name");
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile"); fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
@@ -124,7 +124,7 @@ impl modules::Module {
self.write_transpile(output, parent_dir, child_changed) self.write_transpile(output, parent_dir, child_changed)
} }
fn (bool, String) write_transpile(*self, output String, parent_dir *PathBuf, child_changed bool) { (bool, String) write_transpile(&self, String output, PathBuf& parent_dir, bool child_changed) {
if self.path.is_dir() { if self.path.is_dir() {
let output_file = self.output_path(parent_dir, &None); let output_file = self.output_path(parent_dir, &None);
@@ -174,7 +174,7 @@ 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);
} }
@@ -186,16 +186,22 @@ fn std::io::Result<bool> is_source_newer(source *Path, output *Path) {
} }
pub enum TranspileError<'a> { pub enum TranspileError<'a> {
Parse(error::ParseError<'a, Vec<mist_parser::ast::TopLevel>>), Parse(error::ParseError<'a>),
Semantic(Vec<mist_parser::semantics::SemanticError>) 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>(path *PathBuf, source *'a str, mut output_file PathBuf, mod_decl *str, curr_mod_decl *Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>) { 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
) {
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(".");
@@ -212,18 +218,27 @@ pub fn Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>>
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?; let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
for i in &parsed { for i in &parsed.items {
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?; let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
} }
let output = gc.generate(parsed); gc.generate(parsed.mod_attributes);
gc.mapping.shift_rust(mod_decl.lines().count() as isize, 0); gc.add(mod_decl);
let output = gc.generate(parsed.items);
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) => {
@@ -232,7 +247,7 @@ pub fn void transpile_file(path *PathBuf, source *str, output_file PathBuf, mod_
} }
}; };
let res = fs::write(&output_file, format!("{mod_decl}{output}")); 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");
@@ -259,7 +274,7 @@ pub fn void transpile_file(path *PathBuf, source *str, output_file PathBuf, mod_
} }
} }
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 {
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-parser" name = "mist-parser"
version = "0.3.5-alpha.0" version = "0.3.7-alpha.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"
-1
View File
@@ -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,
+13 -4
View File
@@ -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>,
}, },
@@ -39,6 +42,12 @@ pub enum TypeExpr {
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>), StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
Tuple(Vec<TypeExpr>), Tuple(Vec<TypeExpr>),
Lifetime(Identifier), Lifetime(Identifier),
Void,
Fn {
kind: FnKind,
return_type: Box<TypeExpr>,
params: Vec<TypeExpr>,
},
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
+1 -15
View File
@@ -100,6 +100,7 @@ pub struct FunctionDecl {
pub is_override: Option<Override>, pub is_override: Option<Override>,
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 return_type: Option<TypeExpr>,
pub body: Option<Block>, pub body: Option<Block>,
@@ -125,18 +126,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,
}
}
}
+16 -74
View File
@@ -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)]
@@ -27,30 +26,21 @@ pub enum ErrorCode {
Module, Module,
} }
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 +52,6 @@ impl<'a, F> AstError<'a, F> {
loc.file(), loc.file(),
loc.line(), loc.line(),
), ),
recovered: None,
}) })
} }
} }
@@ -72,21 +61,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 +71,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 +104,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)
}
}
}
+42 -17
View File
@@ -12,6 +12,7 @@ COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
keyword = { keyword = {
"if" "if"
| "else" | "else"
| "fn"
| "for" | "for"
| "while" | "while"
| "match" | "match"
@@ -30,7 +31,6 @@ keyword = {
| "false" | "false"
| "dyn" | "dyn"
| "loop" | "loop"
| "fn"
| "unsafe" | "unsafe"
| "override" | "override"
} }
@@ -82,7 +82,6 @@ module_program = {
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? } visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
mutable = { "mut" } mutable = { "mut" }
unsafe_kw = { "unsafe" }
// ====================================================== // ======================================================
// GENERICS // GENERICS
@@ -105,18 +104,42 @@ 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_closure
| fn_kind_once
| fn_kind_mut
}
fn_type = {
fn_kind ~ "(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
} }
dyn_type = { dyn_type = {
"dyn" ~ type_expr "dyn" ~ type_expr
} }
void_type = {
"void"
}
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)*
} }
lifetime = { lifetime = {
@@ -141,7 +164,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 = {
@@ -200,15 +223,17 @@ attributes = {
// DECLARATION HELPERS // DECLARATION HELPERS
// ====================================================== // ======================================================
var_decl = { var_decl = {
"let" ~ pattern ~ type_expr? ("let" ~ pattern)
| type_expr ~ (!tuple_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 = {
@@ -266,7 +291,7 @@ enum_fields = _{
} }
enum_decl = { enum_decl = {
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields ~ "}" visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields? ~ "}"
} }
// ====================================================== // ======================================================
@@ -286,7 +311,7 @@ class_field = {
} }
self_param = { self_param = {
(deref_px ~ lifetime?)? ~ mutable? ~ "self" (ref_px ~ lifetime?)? ~ mutable? ~ "self"
} }
method_args = _{ method_args = _{
@@ -333,7 +358,7 @@ trait_decl = {
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? ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
} }
// ====================================================== // ======================================================
@@ -341,8 +366,8 @@ function_decl = {
// ====================================================== // ======================================================
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 ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | declare_module | function_decl))
} }
// ====================================================== // ======================================================
@@ -449,7 +474,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 +490,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
View File
@@ -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)::+
};
}
+23 -21
View File
@@ -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,
}; };
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,18 @@ 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()?,
name: Pattern::try_from(inner.next().unwrap())?,
}) })
} }
@@ -63,17 +65,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 +85,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())?))
} }
} }
+58 -75
View File
@@ -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,51 @@ 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 { return_type: consume_rule(&mut inner, Rule::type_expr)
params: collect_recovered(inner.next().unwrap().into_inner()), .map(TypeExpr::try_from)
return_type: consume_rule(&mut inner, Rule::type_expr) .transpose()?,
.map(TypeExpr::try_from) params: collect_recovered(inner.next().unwrap().into_inner())?,
.transpose(), body: Box::new(Expression::try_from(inner.next().unwrap())?),
body: Expression::try_from(inner.next().unwrap()).map(Box::new), }),
})
}
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 => Ok(Expression::Statement(Box::new(pair.try_into()?))),
_ => AstError::bug_unimplemented(pair), _ => AstError::bug_unimplemented(pair),
} }
@@ -110,7 +102,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 +119,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 +128,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 +163,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 +176,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()?,
}) })
}) })
} }
+27 -28
View File
@@ -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)
} }
+42 -46
View File
@@ -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,46 @@ 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::var_decl_statement => Ok(Statement::VarDecl(pair.try_into()?)),
Rule::return_stmt => { Rule::return_stmt => Ok(Statement::Return(
ast_expr!(Statement::Return( inner.next().map(Expression::try_from).transpose()?,
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 +95,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())?,
)) ))
} }
} }
+85 -41
View File
@@ -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,76 @@ 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()
))
}
Rule::ref_type => { for ref_pair in inner {
ast_expr!(TypeExpr::Ref { let mut ref_inner = ref_pair.clone().into_inner();
lifetime: consume_rule(&mut inner, Rule::ref_lifetime)
.map(|v| v.into_inner().next().map(Lifetime::try_from)) match ref_pair.as_rule() {
.unwrap_or_default() Rule::ref_type => {
.transpose(), ty = TypeExpr::Ref {
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<bool>, mutable: listen_rule(&mut ref_inner, Rule::mutable),
ty: TypeExpr::try_from(inner.next().unwrap()).map(Box::new), lifetime: consume_rule(&mut ref_inner, Rule::lifetime)
}) .map(|v| v.into_inner().next().map(Identifier::try_from))
} .unwrap_or_default()
Rule::dyn_type => { .transpose()?,
ast_expr!(TypeExpr::Dyn( ty: Box::new(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)?,
};
}
_ => AstError::bug_unimplemented(ref_pair)?,
}
}
Ok(ty)
} }
Rule::lifetime => Ok(TypeExpr::Lifetime(inner.next().unwrap().try_into()?)),
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 +92,32 @@ 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()?,
)) ))
} 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 +125,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()?
)) ))
} }
}) })
+5 -5
View File
@@ -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())?,
}) })
} }
+9 -18
View File
@@ -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),
} }
+8 -9
View File
@@ -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(),
)), )),
+22 -60
View File
@@ -1,78 +1,55 @@
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 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_override: is_override,
return_type: return_type, return_type: return_type,
name: name, name: name,
generics: generics, generics: generics,
self_param: self_param,
params: params, params: params,
body: body, body: body,
}) })
@@ -81,26 +58,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),
}
}
}
+9 -11
View File
@@ -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),
+42 -42
View File
@@ -7,119 +7,119 @@ 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: inner
.next() .next()
.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())?,
}), }),
Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl { Rule::class_decl => Ok(TopLevelKind::ClassDecl {
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())?,
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)?,
}), }),
_ => AstError::bug_unimplemented(pair), _ => AstError::bug_unimplemented(pair),
+34 -13
View File
@@ -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,
}),
})?,
}) })
} }
} }
+1 -7
View File
@@ -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
@@ -317,12 +317,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());
+27 -19
View File
@@ -1,44 +1,47 @@
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_typed()
let x i32 = 42; {
i32 x = 42;
assert_eq!(x, 42); assert_eq!(x, 42);
str& s = "hello";
let s *str = "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_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,30 +49,35 @@ 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 run_tests()
{
test_let_basic(); test_let_basic();
test_let_typed(); test_let_typed();
test_let_mut(); test_let_mut();
+48 -23
View File
@@ -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,16 +114,25 @@ 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 {
count++; count++;
@@ -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,8 @@ pub fn void test_binary_assign() {
assert_eq!(x, 2); assert_eq!(x, 2);
} }
pub fn void run_tests() { pub void run_tests()
{
test_literals(); test_literals();
test_tuples(); test_tuples();
test_arrays(); test_arrays();
+1 -1
View File
@@ -1,3 +1,3 @@
pub module common; pub module common;
pub fn void test_package() {} pub void test_package() {}
+54 -42
View File
@@ -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,10 +75,10 @@ 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,64 @@ 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 run_tests()
{
test_var_decl(); test_var_decl();
test_var_decl_with_init(); test_var_decl_with_init();
test_if_statement(); test_if_statement();
+21 -21
View File
@@ -1,58 +1,58 @@
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 run_tests() {
test_integer_type(); test_integer_type();
test_float_type(); test_float_type();
test_bool_type(); test_bool_type();
+12 -6
View File
@@ -1,23 +1,29 @@
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() { pub void run_tests()
{
test_derive_attribute(); test_derive_attribute();
test_allow_attribute(); test_allow_attribute();
} }
+30 -18
View File
@@ -1,56 +1,68 @@
pub module class_test; pub module class_test;
pub class Animal { pub class Animal
pub name String; {
pub String name;
constructor() { constructor()
{
self.name = "Rex".to_string(); self.name = "Rex".to_string();
} }
pub fn String speak(*self) { pub String speak(&self)
{
"Unknown".to_string() "Unknown".to_string()
} }
pub fn void test_speak(*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) { 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 void run_tests()
{
let dawg = Dog::new(); let dawg = Dog::new();
dawg.args_test(10, "hello"); dawg.args_test(10, "hello");
dawg.test_speak(); dawg.test_speak();
assert_eq!(format!("{dawg}"), "🐾 Rex"); assert_eq!(format!("{dawg}"), "🐾 Rex");
} }
+55 -23
View File
@@ -1,60 +1,92 @@
pub module enum_test; pub module enum_test;
enum OptionInt { enum OptionInt
{
None, None,
Some(i32), 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 {..} => {
assert_eq!(0, 1);
}
} }
let r = Shape::Rect {
let r = Shape::Rect { w: 3, h: 4 }; 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, Red,
Green, Green,
Blue, 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() { pub void run_tests()
{
test_enum_named(); test_enum_named();
test_enum_tuple(); test_enum_tuple();
test_enum_struct(); test_enum_struct();
+31 -15
View File
@@ -1,60 +1,76 @@
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() { 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);
+43 -19
View File
@@ -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,15 +57,23 @@ 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() { pub void run_tests()
{
test_inherent_impl(); test_inherent_impl();
test_trait_impl_block(); test_trait_impl_block();
test_multiple_impls(); test_multiple_impls();
+39 -17
View File
@@ -1,44 +1,66 @@
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 Point { x, y } = p; let p = Point {
x: 3,
y: 4,
};
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() { 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();
+29 -15
View File
@@ -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();
} }
+2 -3
View File
@@ -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");
} }
+1 -1
View File
@@ -1,3 +1,3 @@
fn void main() { void main() {
mist_analyzer::start(); mist_analyzer::start();
} }
+8 -8
View File
@@ -4,8 +4,8 @@ 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> args = env::args().collect();
if args.len() < 2 { if args.len() < 2 {
print_usage(); print_usage();
@@ -44,7 +44,7 @@ fn void main() {
} }
} }
fn void print_usage() { void print_usage() {
println!("Mist - the mist compiler\n"); println!("Mist - the mist compiler\n");
println!("󰖟 View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m"); println!("󰖟 View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n"); println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
@@ -66,7 +66,7 @@ fn void print_usage() {
println!(" \x1b[36m mist help\x1b[0m print this message\n"); println!(" \x1b[36m mist help\x1b[0m print this message\n");
} }
fn void init_project(mut args Vec<String>) { void init_project(Vec<String> mut args) {
args.remove(0); args.remove(0);
process::Command::new("cargo") process::Command::new("cargo")
@@ -77,7 +77,7 @@ fn void init_project(mut args Vec<String>) {
.spawn() .spawn()
.expect("Failed to run cargo").wait().expect("Unable to wait"); .expect("Failed to run cargo").wait().expect("Unable to wait");
let is_lib bool = fs::metadata("src/lib.rs").is_ok(); bool is_lib = 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");
@@ -92,10 +92,10 @@ fn void init_project(mut args Vec<String>) {
println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n"); println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n");
} }
fn void inject_mist_target(is_lib bool) { void inject_mist_target(bool is_lib) {
let toml_content String = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml"); String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
let inject *str = if is_lib { str& inject = if is_lib {
"\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n" "\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n"
} else { } else {
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n" "\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"