Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8fd8cf999 | ||
|
|
3ce8fe5278 | ||
|
|
2426e585d6 | ||
|
|
2174b99a3f | ||
|
|
31eebb4baa | ||
|
|
41f8b94c82 | ||
|
|
64081bc494 | ||
|
|
3c6ebb66c6 | ||
|
|
a867dbc797 | ||
|
|
a2fc8a4922 | ||
|
|
dbfcaa9b0d | ||
|
|
76541040c9 | ||
|
|
3ddb1bc601 | ||
|
|
bf5d243036 | ||
|
|
b6b5214684 | ||
|
|
a37dffb94b | ||
|
|
84c75c290f | ||
|
|
46e9783257 | ||
|
|
9b7de09b0a | ||
|
|
6c9c0e03d2 | ||
|
|
e5509e89a4 | ||
|
|
fda193b8ff | ||
|
|
c78c9985f4 | ||
|
|
d0341deef9 | ||
|
|
26c0fb34e0 | ||
|
|
75dd2e4af2 | ||
|
|
c47beae67d | ||
|
|
c6c33bf83b | ||
|
|
065dc575a5 | ||
|
|
a1a3ce1a29 | ||
|
|
a63199a41d | ||
|
|
33430f9541 | ||
|
|
2549535e4b | ||
|
|
243b4ba5d0 | ||
|
|
4ab7827955 | ||
|
|
2c11131e1a | ||
|
|
93e7a0fdef | ||
|
|
0dd9e2fb37 | ||
|
|
ae60aee85c | ||
|
|
6cc46751f9 | ||
|
|
2ef2232b84 | ||
|
|
0cbfa10281 | ||
|
|
9ce6d44eb4 | ||
|
|
1f2e989522 | ||
|
|
ca11866328 | ||
|
|
055d50edd5 | ||
|
|
c8d7f05e67 | ||
|
|
9b1519b068 | ||
|
|
dc8acdc2bd | ||
|
|
97de75252d | ||
|
|
2f12f5ac53 | ||
|
|
e4b7b4abf9 | ||
|
|
208e4dac6b | ||
|
|
b73396afb7 | ||
|
|
7f7c1e2000 | ||
|
|
2f6303ba30 | ||
|
|
2ae4ca510d |
@@ -29,3 +29,6 @@ target
|
||||
**/build
|
||||
|
||||
.mist/
|
||||
|
||||
analyzer.bat
|
||||
analyzer.sh
|
||||
|
||||
Generated
+13
-5
@@ -292,6 +292,12 @@ version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
@@ -470,10 +476,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mist-analyzer"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
dependencies = [
|
||||
"cargo_metadata",
|
||||
"dashmap 6.1.0",
|
||||
"heck",
|
||||
"mist-codegen",
|
||||
"mist-parser",
|
||||
"pest",
|
||||
@@ -481,12 +488,13 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"toml",
|
||||
"tower-lsp",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mist-api"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
dependencies = [
|
||||
"cargo_metadata",
|
||||
"mist-codegen",
|
||||
@@ -498,7 +506,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mist-codegen"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
dependencies = [
|
||||
"bytecount",
|
||||
"mist-parser",
|
||||
@@ -506,7 +514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mist-lang"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
dependencies = [
|
||||
"mist-analyzer",
|
||||
"mist-api",
|
||||
@@ -514,7 +522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mist-parser"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
dependencies = [
|
||||
"pest",
|
||||
"pest_derive",
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mist-lang"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
edition = "2024"
|
||||
description = "The Mist programming language compiler"
|
||||
license = "Apache-2.0"
|
||||
@@ -32,10 +32,10 @@ exclude = [
|
||||
]
|
||||
|
||||
[workspace.dependencies]
|
||||
mist-parser = { path = "crates/parser", version = "0.3.5-alpha.0" }
|
||||
mist-analyzer = { path = "crates/analyzer", version = "0.3.5-alpha.0" }
|
||||
mist-codegen = { path = "crates/codegen", version = "0.3.5-alpha.0" }
|
||||
mist-api = { path = "crates/mist-api", 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.7-alpha.0" }
|
||||
mist-codegen = { path = "crates/codegen", version = "0.3.7-alpha.0" }
|
||||
mist-api = { path = "crates/mist-api", version = "0.3.7-alpha.0" }
|
||||
|
||||
[[bin]]
|
||||
name = "mist"
|
||||
|
||||
@@ -19,7 +19,7 @@ The `div` reduces the vertical height. The `picture` prevents autolinking.
|
||||
|
||||
**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
|
||||
- Zero-cost abstractions, no runtime overhead
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
@echo off
|
||||
|
||||
cd D:\projects\mist\mist
|
||||
|
||||
mist build >nul 2>&1
|
||||
|
||||
cd mist-test
|
||||
|
||||
D:\projects\mist\mist\target\debug\mist-analyzer.exe
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 55 KiB |
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mist-analyzer"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
edition = "2024"
|
||||
description = "The Mist programming language Analyzer LSP"
|
||||
license = "Apache-2.0"
|
||||
@@ -21,3 +21,5 @@ cargo_metadata = "0.23.1"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
ropey = "1"
|
||||
heck = "0.5.0"
|
||||
toml = "1.1.2"
|
||||
|
||||
+743
-143
File diff suppressed because it is too large
Load Diff
@@ -103,7 +103,8 @@ impl RustAnalyzer {
|
||||
pub fn new(
|
||||
notification_tx: tokio::sync::mpsc::UnboundedSender<Value>,
|
||||
) -> 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())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -129,7 +130,10 @@ impl RustAnalyzer {
|
||||
match stderr.read(&mut buf).await {
|
||||
Ok(0) => break,
|
||||
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) => {
|
||||
eprintln!("[ra-stderr] read error: {e}");
|
||||
@@ -323,10 +327,7 @@ impl RustAnalyzer {
|
||||
}
|
||||
|
||||
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.notify(
|
||||
<Initialized as Notification>::METHOD,
|
||||
InitializedParams {},
|
||||
)
|
||||
self.notify(<Initialized as Notification>::METHOD, InitializedParams {})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use mist_codegen::RustCodegen;
|
||||
use mist_codegen::fmt::MistCodegen;
|
||||
use mist_parser::rev_mapper::Mapping;
|
||||
use mist_parser::parse;
|
||||
use mist_parser::{MistFmtConfig, parse};
|
||||
|
||||
pub struct TranspiledFile {
|
||||
pub mist_path: PathBuf,
|
||||
@@ -11,7 +12,49 @@ pub struct TranspiledFile {
|
||||
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,
|
||||
source: &str,
|
||||
extra_mod_decl: &str,
|
||||
@@ -26,20 +69,28 @@ pub fn transpile_mist(
|
||||
|
||||
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 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 {
|
||||
mist_path: mist_path.to_path_buf(),
|
||||
rust_path,
|
||||
rust_content: format!("{}{}", extra_mod_decl, output),
|
||||
rust_content: output,
|
||||
mapping: codegen.mapping,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn format_mist(source: &str, config: MistFmtConfig) -> Result<String, String> {
|
||||
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
|
||||
|
||||
let mut codegen = MistCodegen::new(config);
|
||||
codegen.generate(parsed.mod_attributes);
|
||||
let output = codegen.generate(parsed.items);
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mist-codegen"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
edition = "2024"
|
||||
description = "The Mist programming language Rust code generator"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -51,7 +51,7 @@ impl ClassProcessedData {
|
||||
if matches!(method.item.visibility, Visibility::Public) {
|
||||
match &method.item.is_override {
|
||||
None => {
|
||||
if method.item.is_using_self() {
|
||||
if method.item.self_param.is_some() {
|
||||
v_table.push(method.item.name.clone());
|
||||
}
|
||||
}
|
||||
@@ -263,7 +263,7 @@ impl ClassProcessedData {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let TypeExpr::Ref { mutable, .. } = params.remove(0) {
|
||||
if let Some((_, _, mutable)) = &method.item.self_param {
|
||||
method.gen_span(cg);
|
||||
cg.add_indented(&format!("{}::__m_", target_rust_path));
|
||||
cg.add(&method.item.name.get_rust());
|
||||
@@ -273,7 +273,7 @@ impl ClassProcessedData {
|
||||
0,
|
||||
TypeExpr::Ref {
|
||||
lifetime: None,
|
||||
mutable,
|
||||
mutable: *mutable,
|
||||
ty: Box::new(get_type_from_path(&target_path)),
|
||||
},
|
||||
);
|
||||
@@ -375,20 +375,6 @@ impl ClassProcessedData {
|
||||
cg.indent -= 1;
|
||||
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 {
|
||||
line: constructor.line,
|
||||
column: constructor.column,
|
||||
@@ -397,7 +383,8 @@ impl ClassProcessedData {
|
||||
is_override: None,
|
||||
name: Identifier(String::from("constructor")),
|
||||
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())),
|
||||
body: Some(constructor.item.body.clone()),
|
||||
},
|
||||
@@ -409,7 +396,7 @@ impl ClassProcessedData {
|
||||
for method in &self.methods {
|
||||
match method.item.visibility {
|
||||
Visibility::Public => {
|
||||
if method.item.is_using_self() {
|
||||
if method.item.self_param.is_some() {
|
||||
if method.item.is_override.is_none() {
|
||||
gen_method_point(&method.item, ctx, cg);
|
||||
}
|
||||
@@ -513,6 +500,7 @@ fn construct_pattern(pat: &Pattern, idx: usize) -> Pattern {
|
||||
}
|
||||
|
||||
pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustCodegen) {
|
||||
let mutable_self = if let Some((is_ref, lifetime, is_mut)) = &method.self_param {
|
||||
cg.add_indented(&format!(
|
||||
"{}fn {}{}(",
|
||||
method.visibility.get_rust(),
|
||||
@@ -520,6 +508,25 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
|
||||
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
|
||||
.params
|
||||
.0
|
||||
@@ -566,14 +573,10 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
|
||||
.filter_map(|v| v.type_)
|
||||
.collect();
|
||||
|
||||
let TypeExpr::Ref { mutable, .. } = param_types.remove(0) else {
|
||||
panic!("")
|
||||
};
|
||||
|
||||
param_types.insert(
|
||||
0,
|
||||
TypeExpr::UnsafePtr {
|
||||
mutable,
|
||||
mutable: mutable_self,
|
||||
ty: Box::new(TypeExpr::Path(
|
||||
Path(vec![
|
||||
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.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");
|
||||
} else {
|
||||
cg.add_indented("func(self as *const Self as *const std::ffi::c_void");
|
||||
}
|
||||
|
||||
for (i, param) in ¶ms {
|
||||
if *i == 0 {
|
||||
continue; // self already fulfills it
|
||||
}
|
||||
for (_, param) in ¶ms {
|
||||
cg.add(", ");
|
||||
ctx.expr_ensure_semicolon = false;
|
||||
param.name.gen_rust(ctx, cg);
|
||||
|
||||
@@ -256,11 +256,6 @@ impl GenRust for Postfix {
|
||||
|
||||
Postfix::Try => cg.add("?"),
|
||||
|
||||
Postfix::Assign(cmp, expr) => {
|
||||
cg.add(" ");
|
||||
cg.add(cmp);
|
||||
expr.gen_rust(ctx, cg);
|
||||
}
|
||||
Postfix::Increment => cg.add("+=1"),
|
||||
Postfix::Decrement => cg.add("-=1"),
|
||||
}
|
||||
|
||||
@@ -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("--"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(")");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
-16
@@ -1,5 +1,6 @@
|
||||
pub mod class_decl;
|
||||
pub mod expr;
|
||||
pub mod fmt;
|
||||
pub mod statement;
|
||||
pub mod top_level;
|
||||
|
||||
@@ -48,7 +49,7 @@ impl RustCodegen {
|
||||
" ".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');
|
||||
|
||||
if newline_count == 0 {
|
||||
@@ -63,17 +64,17 @@ impl RustCodegen {
|
||||
self.output.push_str(s);
|
||||
}
|
||||
|
||||
fn addln(&mut self, s: &str) {
|
||||
pub fn addln(&mut self, s: &str) {
|
||||
self.add(s);
|
||||
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);
|
||||
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);
|
||||
self.add(&line);
|
||||
}
|
||||
@@ -246,23 +247,12 @@ impl GetRust for TypeExpr {
|
||||
ty,
|
||||
} => {
|
||||
if let Some(lifetime) = lifetime {
|
||||
match lifetime {
|
||||
Lifetime::Lifetime(v) => {
|
||||
format!(
|
||||
"&'{} {}{}",
|
||||
v.get_rust(),
|
||||
lifetime.get_rust(),
|
||||
if *mutable { "mut " } else { "" },
|
||||
ty.get_rust()
|
||||
)
|
||||
}
|
||||
Lifetime::Unsafe => {
|
||||
format!(
|
||||
"*{} {}",
|
||||
if *mutable { "mut" } else { "const" },
|
||||
ty.get_rust()
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
format!("&{}{}", if *mutable { "mut " } else { "" }, ty.get_rust())
|
||||
}
|
||||
@@ -271,8 +261,38 @@ impl GetRust for TypeExpr {
|
||||
Self::Dyn(ty) => {
|
||||
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 {
|
||||
|
||||
@@ -80,6 +80,22 @@ impl GenRust for FunctionDecl {
|
||||
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() {
|
||||
if i > 0 {
|
||||
cg.add(", ");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mist-api"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
edition = "2024"
|
||||
description = "The Mist programming language module system"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -11,11 +11,11 @@ use mist_parser::rev_mapper;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MistDiagnosticMessage {
|
||||
pub message String,
|
||||
pub file_path PathBuf,
|
||||
pub file_name String ,
|
||||
pub line usize,
|
||||
pub column usize,
|
||||
pub String message,
|
||||
pub PathBuf file_path,
|
||||
pub String file_name,
|
||||
pub usize line,
|
||||
pub usize column,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -25,7 +25,7 @@ pub enum MistDiagnostic {
|
||||
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.insert(1, "--message-format=json".to_string());
|
||||
|
||||
@@ -57,7 +57,7 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
|
||||
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");
|
||||
|
||||
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();
|
||||
|
||||
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");
|
||||
|
||||
command.wait().unwrap();
|
||||
@@ -123,7 +123,7 @@ pub fn bool build(mut args Vec<String>, root PathBuf) {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn void print_diagnostics(diagnostics *Vec<MistDiagnostic>) {
|
||||
pub void print_diagnostics(Vec<MistDiagnostic>& diagnostics) {
|
||||
let mut files = HashMap::new();
|
||||
|
||||
for diag in diagnostics {
|
||||
@@ -159,13 +159,13 @@ pub fn void print_diagnostics(diagnostics *Vec<MistDiagnostic>) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn Option<String> get_line(
|
||||
files *mut HashMap<PathBuf, Vec<String>>,
|
||||
msg *MistDiagnosticMessage,
|
||||
pub Option<String> get_line(
|
||||
HashMap<PathBuf, Vec<String>> mut& files,
|
||||
MistDiagnosticMessage& msg,
|
||||
) {
|
||||
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)
|
||||
.expect("Unable to read mist file")
|
||||
.lines()
|
||||
@@ -174,5 +174,5 @@ pub fn Option<String> get_line(
|
||||
.collect()
|
||||
});
|
||||
|
||||
lines.get(msg.line - 1).map(fn(v) -> v.trim().to_string())
|
||||
lines.get(msg.line - 1).map((v) => v.trim().to_string())
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ use crate::transpiler::MistConfig;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub class Module {
|
||||
pub name String;
|
||||
pub path PathBuf;
|
||||
pub children Vec<Module>;
|
||||
pub String name;
|
||||
pub PathBuf path;
|
||||
pub Vec<Module> children;
|
||||
|
||||
pub constructor(mist_path PathBuf, config *MistConfig) {
|
||||
pub constructor(PathBuf mist_path, MistConfig& config) {
|
||||
self.children = Vec::new();
|
||||
self.name = mist_path.file_stem()
|
||||
.and_then(fn(s) -> s.to_str())
|
||||
.and_then((s) => s.to_str())
|
||||
.expect("Failed to get module name")
|
||||
.to_string();
|
||||
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) {
|
||||
Ok(entries) => entries;
|
||||
Err(e) => {
|
||||
@@ -65,11 +65,11 @@ pub class Module {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bool is_package(*self) {
|
||||
self.path.file_name().map(fn(v) -> v.to_str()).unwrap_or_default() == Some("package.mist")
|
||||
pub bool is_package(&self) {
|
||||
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() {
|
||||
parent_dir.join(&self.name)
|
||||
} 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 {
|
||||
&name.0
|
||||
} else {
|
||||
|
||||
@@ -16,13 +16,13 @@ use serde::Deserialize;
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct MistConfig {
|
||||
pub package PathBuf,
|
||||
pub packages Vec<PathBuf>,
|
||||
pub main_mods String
|
||||
pub PathBuf package,
|
||||
pub Vec<PathBuf> packages,
|
||||
pub String main_mods
|
||||
}
|
||||
|
||||
impl MistConfig {
|
||||
pub fn bool should_ignore(*self, path *Path) {
|
||||
pub bool should_ignore(&self, Path& path) {
|
||||
if path == self.package {
|
||||
return true;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ impl MistConfig {
|
||||
}
|
||||
}
|
||||
impl Default for MistConfig {
|
||||
fn Self default() {
|
||||
Self default() {
|
||||
Self {
|
||||
package: PathBuf::from("main.mist"),
|
||||
packages: Vec::new(),
|
||||
@@ -46,7 +46,7 @@ impl Default for MistConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn PathBuf transpile() {
|
||||
pub PathBuf transpile() {
|
||||
let start = time::Instant::now();
|
||||
|
||||
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 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)
|
||||
.unwrap_or_else(fn(_) -> panic!("Failed to parse Mist.toml from {:?}", toml_path));
|
||||
MistConfig mut config = toml::from_str(&toml_content)
|
||||
.unwrap_or_else((_) => panic!("Failed to parse Mist.toml from {:?}", toml_path));
|
||||
|
||||
for pkg in &mut config.packages {
|
||||
*pkg = src.join(&*pkg);
|
||||
@@ -85,10 +85,10 @@ pub fn PathBuf transpile() {
|
||||
}
|
||||
|
||||
impl modules::Module {
|
||||
fn (bool, String) transpile(*self, parent_dir *PathBuf, config *mut MistConfig) {
|
||||
if !self.path.is_dir() && self.path.extension().and_then(fn(v) -> v.to_str()) != Some("mist") {
|
||||
(bool, String) transpile(&self, PathBuf& parent_dir, MistConfig mut& config) {
|
||||
if !self.path.is_dir() && self.path.extension().and_then((v) => v.to_str()) != Some("mist") {
|
||||
let file_name = self.path.file_name()
|
||||
.and_then(fn(s) -> s.to_str())
|
||||
.and_then((s) => s.to_str())
|
||||
.expect("Failed to get file name");
|
||||
|
||||
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
|
||||
@@ -124,7 +124,7 @@ impl modules::Module {
|
||||
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() {
|
||||
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() {
|
||||
return Ok(true);
|
||||
}
|
||||
@@ -186,16 +186,22 @@ fn std::io::Result<bool> is_source_newer(source *Path, output *Path) {
|
||||
}
|
||||
|
||||
pub enum TranspileError<'a> {
|
||||
Parse(error::ParseError<'a, Vec<mist_parser::ast::TopLevel>>),
|
||||
Parse(error::ParseError<'a>),
|
||||
Semantic(Vec<mist_parser::semantics::SemanticError>)
|
||||
}
|
||||
|
||||
pub fn 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)>) {
|
||||
pub Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>>
|
||||
transpile_code<'a>(
|
||||
PathBuf& path,
|
||||
str 'a& source,
|
||||
PathBuf mut output_file,
|
||||
str& mod_decl,
|
||||
Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl
|
||||
) {
|
||||
|
||||
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 let Some(ext) = output_file.extension().map(fn(e) -> e.to_owned()) {
|
||||
if output_file.file_name().map((v) => v.to_str()).unwrap_or_default() != Some("mod.rs") {
|
||||
if let Some(ext) = output_file.extension().map((e) => e.to_owned()) {
|
||||
let mut new_name = std::ffi::OsString::from(&name.0);
|
||||
|
||||
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)?;
|
||||
|
||||
for i in &parsed {
|
||||
for i in &parsed.items {
|
||||
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))
|
||||
}
|
||||
|
||||
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) {
|
||||
Ok(output) => output;
|
||||
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");
|
||||
|
||||
@@ -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();
|
||||
|
||||
match err {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mist-parser"
|
||||
version = "0.3.5-alpha.0"
|
||||
version = "0.3.7-alpha.0"
|
||||
edition = "2024"
|
||||
description = "The Mist programming language parser"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -62,7 +62,6 @@ pub enum Postfix {
|
||||
delimiter: MacroDelimiter,
|
||||
},
|
||||
StructCall(Vec<(Identifier, Option<Expression>)>),
|
||||
Assign(String, Box<Expression>),
|
||||
Index(Expression),
|
||||
As(TypeExpr),
|
||||
Increment,
|
||||
|
||||
@@ -18,15 +18,18 @@ pub struct Identifier(pub String);
|
||||
pub struct ParamList(pub Vec<VarDecl>);
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||
pub enum Lifetime {
|
||||
Lifetime(Identifier),
|
||||
Unsafe,
|
||||
pub enum FnKind {
|
||||
Fn,
|
||||
UnsafeFn,
|
||||
FnClosure,
|
||||
FnOnce,
|
||||
FnMut,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
|
||||
pub enum TypeExpr {
|
||||
Ref {
|
||||
lifetime: Option<Lifetime>,
|
||||
lifetime: Option<Identifier>,
|
||||
mutable: bool,
|
||||
ty: Box<TypeExpr>,
|
||||
},
|
||||
@@ -39,6 +42,12 @@ pub enum TypeExpr {
|
||||
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
|
||||
Tuple(Vec<TypeExpr>),
|
||||
Lifetime(Identifier),
|
||||
Void,
|
||||
Fn {
|
||||
kind: FnKind,
|
||||
return_type: Box<TypeExpr>,
|
||||
params: Vec<TypeExpr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
|
||||
@@ -100,6 +100,7 @@ pub struct FunctionDecl {
|
||||
pub is_override: Option<Override>,
|
||||
pub name: Identifier,
|
||||
pub generics: GenericsDecl,
|
||||
pub self_param: Option<(bool, Option<Identifier>, bool)>,
|
||||
pub params: ParamList,
|
||||
pub return_type: Option<TypeExpr>,
|
||||
pub body: Option<Block>,
|
||||
@@ -125,18 +126,3 @@ pub struct FieldDeclStmt {
|
||||
pub decl: FieldDecl,
|
||||
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
@@ -4,20 +4,19 @@ use pest::iterators::Pair;
|
||||
|
||||
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)]
|
||||
pub enum ParseError<'a, T> {
|
||||
pub enum ParseError<'a> {
|
||||
PreAst(pest::error::Error<Rule>),
|
||||
Ast(AstError<'a, T>),
|
||||
Ast(AstError<'a>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AstError<'a, T> {
|
||||
pub struct AstError<'a> {
|
||||
pub span: pest::Span<'a>,
|
||||
pub error_code: ErrorCode,
|
||||
pub error_message: String,
|
||||
pub recovered: Option<T>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -27,30 +26,21 @@ pub enum ErrorCode {
|
||||
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 {
|
||||
Self::PreAst(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> From<AstError<'a, T>> for ParseError<'a, T> {
|
||||
fn from(value: AstError<'a, T>) -> Self {
|
||||
impl<'a> From<AstError<'a>> for ParseError<'a> {
|
||||
fn from(value: AstError<'a>) -> Self {
|
||||
Self::Ast(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, F> AstError<'a, F> {
|
||||
pub fn get<T>(self) -> AstError<'a, T> {
|
||||
AstError {
|
||||
span: self.span,
|
||||
error_code: self.error_code,
|
||||
error_message: self.error_message,
|
||||
recovered: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AstError<'a> {
|
||||
#[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();
|
||||
|
||||
Err(Self {
|
||||
@@ -62,7 +52,6 @@ impl<'a, F> AstError<'a, F> {
|
||||
loc.file(),
|
||||
loc.line(),
|
||||
),
|
||||
recovered: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -72,21 +61,6 @@ pub trait IntoErr<T, FA, FR> {
|
||||
fn get_map(self, m: impl Fn(FA) -> FR) -> T;
|
||||
}
|
||||
|
||||
impl<'a, T, TE, TE2> IntoErr<AstResult<'a, T, TE2>, TE, TE2> for AstResult<'a, T, TE> {
|
||||
fn get(self) -> AstResult<'a, T, TE2> {
|
||||
self.map_err(AstError::get)
|
||||
}
|
||||
|
||||
fn get_map(self, m: impl Fn(TE) -> TE2) -> AstResult<'a, T, TE2> {
|
||||
self.map_err(|e| AstError {
|
||||
span: e.span,
|
||||
error_code: e.error_code,
|
||||
error_message: e.error_message,
|
||||
recovered: e.recovered.map(m),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait GetLength {
|
||||
fn len(&self) -> usize;
|
||||
}
|
||||
@@ -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>>,
|
||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
||||
) -> AstResult<'a, Vec<T>>
|
||||
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)
|
||||
}
|
||||
|
||||
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>>,
|
||||
f: F,
|
||||
) -> AstResult<'a, Vec<T>, Vec<T>>
|
||||
) -> AstResult<'a, Vec<T>>
|
||||
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 last_error: Option<AstError<'a, ET>> = None;
|
||||
let mut last_error: Option<AstError<'a>> = None;
|
||||
|
||||
for pair in pairs {
|
||||
match f(pair) {
|
||||
@@ -130,39 +104,7 @@ where
|
||||
span: ast_err.span,
|
||||
error_code: ast_err.error_code,
|
||||
error_message: ast_err.error_message,
|
||||
recovered: Some(items),
|
||||
}),
|
||||
None => Ok(items),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AstErrorAnalyzer<'a, T>(pub Option<AstError<'a, T>>);
|
||||
|
||||
impl<'a, T> AstErrorAnalyzer<'a, T> {
|
||||
pub fn get<V: Clone, V2: Clone + Into<V>>(
|
||||
&mut self,
|
||||
r: AstResult<'a, V, V2>,
|
||||
) -> AstResult<'a, V, V2> {
|
||||
if let Err(e) = r {
|
||||
self.0 = Some(e.clone().get());
|
||||
|
||||
if let Some(recovered) = e.recovered {
|
||||
Ok(recovered.into())
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(self, v: T) -> AstResult<'a, T> {
|
||||
if let Some(mut e) = self.0 {
|
||||
e.recovered = Some(v);
|
||||
|
||||
Err(e)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
|
||||
keyword = {
|
||||
"if"
|
||||
| "else"
|
||||
| "fn"
|
||||
| "for"
|
||||
| "while"
|
||||
| "match"
|
||||
@@ -30,7 +31,6 @@ keyword = {
|
||||
| "false"
|
||||
| "dyn"
|
||||
| "loop"
|
||||
| "fn"
|
||||
| "unsafe"
|
||||
| "override"
|
||||
}
|
||||
@@ -82,7 +82,6 @@ module_program = {
|
||||
|
||||
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
|
||||
mutable = { "mut" }
|
||||
unsafe_kw = { "unsafe" }
|
||||
|
||||
// ======================================================
|
||||
// GENERICS
|
||||
@@ -105,18 +104,42 @@ path_type = {
|
||||
static_path ~ generics?
|
||||
}
|
||||
|
||||
ref_lifetime = { lifetime | unsafe_kw }
|
||||
unsafe_ref_type = {
|
||||
mutable? ~ "unsafe" ~ "*"
|
||||
}
|
||||
|
||||
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_expr
|
||||
}
|
||||
|
||||
void_type = {
|
||||
"void"
|
||||
}
|
||||
|
||||
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 = {
|
||||
@@ -141,7 +164,7 @@ literal = {
|
||||
etc_pattern = { ".." }
|
||||
|
||||
multi_pat_template = _{
|
||||
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))*)?
|
||||
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))* ~ ","?)?
|
||||
}
|
||||
|
||||
tuple_pattern = {
|
||||
@@ -200,15 +223,17 @@ attributes = {
|
||||
// DECLARATION HELPERS
|
||||
// ======================================================
|
||||
var_decl = {
|
||||
"let" ~ pattern ~ type_expr?
|
||||
("let" ~ pattern)
|
||||
| type_expr ~ (!tuple_pattern ~ pattern)
|
||||
}
|
||||
|
||||
field = {
|
||||
visibility? ~ identifier ~ type_expr
|
||||
visibility? ~ type_expr ~ identifier
|
||||
}
|
||||
|
||||
param = {
|
||||
pattern ~ type_expr?
|
||||
(type_expr ~ pattern)
|
||||
| pattern
|
||||
}
|
||||
|
||||
field_list = {
|
||||
@@ -266,7 +291,7 @@ enum_fields = _{
|
||||
}
|
||||
|
||||
enum_decl = {
|
||||
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields ~ "}"
|
||||
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields? ~ "}"
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
@@ -286,7 +311,7 @@ class_field = {
|
||||
}
|
||||
|
||||
self_param = {
|
||||
(deref_px ~ lifetime?)? ~ mutable? ~ "self"
|
||||
(ref_px ~ lifetime?)? ~ mutable? ~ "self"
|
||||
}
|
||||
|
||||
method_args = _{
|
||||
@@ -333,7 +358,7 @@ trait_decl = {
|
||||
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
|
||||
|
||||
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 = {
|
||||
(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)* }
|
||||
|
||||
match_item = {
|
||||
pattern_list ~ "=>" ~ statement
|
||||
pattern_list ~ "=>" ~ (block | (expr ~ ","))
|
||||
}
|
||||
|
||||
match_stmt = {
|
||||
@@ -465,8 +490,8 @@ match_stmt = {
|
||||
// ------------------------------------------------------
|
||||
|
||||
closure = {
|
||||
"fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ block
|
||||
| "fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ "->" ~ expr
|
||||
("(" ~ param_list ~ ")" ~ "=>" ~ expr)
|
||||
| (type_expr ~ "(" ~ param_list ~ ")" ~ "=>" ~ expr)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------
|
||||
|
||||
+22
-61
@@ -9,42 +9,46 @@ pub mod semantics;
|
||||
|
||||
use ast::*;
|
||||
|
||||
use crate::error::{IntoErr, ParseError};
|
||||
use crate::error::ParseError;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[grammar = "./src/grammar.pest"]
|
||||
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 statements = vec![];
|
||||
|
||||
let mut analyzer = error::AstErrorAnalyzer(None);
|
||||
|
||||
for pair in pairs.next().unwrap().into_inner() {
|
||||
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) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => {
|
||||
let rec = e.recovered.clone();
|
||||
let (mod_attributes, items): (Vec<_>, Vec<_>) = statements
|
||||
.into_iter()
|
||||
.partition(|item| matches!(item.0.item, TopLevelKind::ModAttribute));
|
||||
|
||||
let mut e2 = e.get();
|
||||
|
||||
e2.recovered = rec;
|
||||
|
||||
Err(ParseError::Ast(e2))
|
||||
}
|
||||
}
|
||||
Ok(Program {
|
||||
items,
|
||||
mod_attributes,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_module<'a>(
|
||||
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)?;
|
||||
|
||||
if let Some(v) = pairs
|
||||
@@ -53,8 +57,7 @@ pub fn parse_module<'a>(
|
||||
.into_inner()
|
||||
.next()
|
||||
.map(TopLevel::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.transpose()?
|
||||
{
|
||||
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
|
||||
Ok(Some((vis.clone(), name.clone())))
|
||||
@@ -76,49 +79,7 @@ macro_rules! ast_ensure {
|
||||
span: $pair.as_span(),
|
||||
error_code: crate::error::ErrorCode::AstGenBug,
|
||||
error_message: format!("Possible bug: expected {:?}, got {:?}", $rule, $pair.as_rule()),
|
||||
recovered: None,
|
||||
})
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! ast_expr {
|
||||
(use $r:expr, $($v:expr),* $(,)?) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
$(
|
||||
analyzer.get($v).get()?;
|
||||
)*
|
||||
|
||||
analyzer.build($r)
|
||||
}};
|
||||
|
||||
($($item:ident)::+ { $($k:ident: $v:expr),* $(,)? }) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
let v = $($item)::+ { $($k: analyzer.get($v).get()?),* };
|
||||
|
||||
analyzer.build(v)
|
||||
}};
|
||||
|
||||
($($item:ident)::+ ( $($v:expr),* $(,)? )) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
let v = $($item)::+ ( $(analyzer.get($v).get()?),* );
|
||||
|
||||
analyzer.build(v)
|
||||
}};
|
||||
|
||||
(( $($v:expr),* $(,)? )) => {{
|
||||
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
|
||||
|
||||
let v = ( $(analyzer.get($v).get()?),* );
|
||||
|
||||
analyzer.build(v)
|
||||
}};
|
||||
|
||||
($($item:ident)::+) => {
|
||||
$($item)::+
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
error::{AstError, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
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> {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl_statement => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(VarDeclStmt {
|
||||
decl: inner.next().unwrap().try_into(),
|
||||
init: inner.next().map(Expression::try_from).transpose()
|
||||
Ok(VarDeclStmt {
|
||||
decl: inner.next().unwrap().try_into()?,
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::class_field => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(FieldDeclStmt {
|
||||
decl: inner.next().unwrap().try_into(),
|
||||
init: inner.next().map(Expression::try_from).transpose(),
|
||||
Ok(FieldDeclStmt {
|
||||
decl: inner.next().unwrap().try_into()?,
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::var_decl | Rule::param => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(VarDecl {
|
||||
name: Pattern::try_from(inner.next().unwrap()),
|
||||
type_: inner.next().map(TypeExpr::try_from).transpose(),
|
||||
Ok(VarDecl {
|
||||
type_: consume_rule(&mut inner, Rule::type_expr)
|
||||
.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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::field => {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
ast_expr!(FieldDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
name: Identifier::try_from(inner.next().unwrap()),
|
||||
type_: TypeExpr::try_from(inner.next().unwrap()),
|
||||
Ok(FieldDecl {
|
||||
visibility: Visibility::try_from(&mut inner)?,
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
|
||||
Ok(ParamList(collect_recovered(pair.into_inner())?))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, AstResult, GetLength, IntoErr, collect_recovered, collect_recovered_map},
|
||||
ast_ensure,
|
||||
error::{AstError, collect_recovered, collect_recovered_map},
|
||||
parser::consume_rule,
|
||||
};
|
||||
use pest::pratt_parser::PrattParser;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
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> {
|
||||
let rule = pair.as_rule();
|
||||
@@ -27,10 +27,10 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
|
||||
pratt
|
||||
.map_primary(|primary_pair| Expression::try_from(primary_pair))
|
||||
.map_infix(|expr, op, rhs| {
|
||||
ast_expr!(Expression::Binary {
|
||||
lhs: expr.map(Box::new).get_map(Box::new),
|
||||
op: Ok(op.as_str().to_string()) as AstResult<'_, String>,
|
||||
rhs: rhs.map(Box::new).get_map(Box::new),
|
||||
Ok(Expression::Binary {
|
||||
lhs: expr.map(Box::new)?,
|
||||
op: op.as_str().to_string(),
|
||||
rhs: rhs.map(Box::new)?,
|
||||
})
|
||||
})
|
||||
.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(
|
||||
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 {
|
||||
ast_expr!(Expression::Fix {
|
||||
initial: exp.map(Box::new),
|
||||
Ok(Expression::Fix {
|
||||
initial: Box::new(exp),
|
||||
prefixes: prefixes,
|
||||
postfixes: postfixes,
|
||||
})
|
||||
} else {
|
||||
ast_expr!(use exp?, prefixes, postfixes)
|
||||
Ok(exp)
|
||||
}
|
||||
}
|
||||
|
||||
Rule::tuple => {
|
||||
ast_expr!(Expression::Literal(
|
||||
collect_recovered(pair.into_inner())
|
||||
.map(Literal::Tuple)
|
||||
.get_map(Literal::Tuple)
|
||||
))
|
||||
}
|
||||
Rule::tuple => Ok(Expression::Literal(Literal::Tuple(collect_recovered(
|
||||
pair.into_inner(),
|
||||
)?))),
|
||||
|
||||
Rule::closure => {
|
||||
ast_expr!(Expression::Closure {
|
||||
params: collect_recovered(inner.next().unwrap().into_inner()),
|
||||
Rule::closure => Ok(Expression::Closure {
|
||||
return_type: consume_rule(&mut inner, Rule::type_expr)
|
||||
.map(TypeExpr::try_from)
|
||||
.transpose(),
|
||||
body: Expression::try_from(inner.next().unwrap()).map(Box::new),
|
||||
})
|
||||
}
|
||||
.transpose()?,
|
||||
params: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||
body: Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||
}),
|
||||
|
||||
Rule::array => {
|
||||
ast_expr!(Expression::Array(collect_recovered(inner)))
|
||||
}
|
||||
Rule::array => Ok(Expression::Array(collect_recovered(inner)?)),
|
||||
|
||||
Rule::array_repeat => {
|
||||
ast_expr!(Expression::ArrayRepeat(
|
||||
Expression::try_from(inner.next().unwrap()).map(Box::new),
|
||||
Expression::try_from(inner.next().unwrap()).map(Box::new)
|
||||
))
|
||||
}
|
||||
Rule::array_repeat => Ok(Expression::ArrayRepeat(
|
||||
Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||
Box::new(Expression::try_from(inner.next().unwrap())?),
|
||||
)),
|
||||
|
||||
Rule::primary => pair.into_inner().next().unwrap().try_into(),
|
||||
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
|
||||
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
|
||||
Rule::expr_path => ast_expr!(Expression::Path(pair.try_into())),
|
||||
Rule::statement | Rule::basic_stmt | Rule::control_flow | Rule::block | Rule::unsafe_block => ast_expr!(
|
||||
Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new))
|
||||
),
|
||||
Rule::static_path => Ok(Expression::Path(pair.try_into()?)),
|
||||
Rule::literal => Ok(Expression::Literal(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 => Ok(Expression::Statement(Box::new(pair.try_into()?))),
|
||||
|
||||
_ => 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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
@@ -136,34 +128,27 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
||||
match rule {
|
||||
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
|
||||
|
||||
Rule::field_px => {
|
||||
ast_expr!(Postfix::FieldAccess(
|
||||
inner.next().unwrap().try_into(),
|
||||
inner.next().map(Generics::try_from).transpose()
|
||||
))
|
||||
}
|
||||
Rule::field_px => Ok(Postfix::FieldAccess(
|
||||
inner.next().unwrap().try_into()?,
|
||||
inner.next().map(Generics::try_from).transpose()?,
|
||||
)),
|
||||
|
||||
Rule::tuple_field_px => {
|
||||
ast_expr!(Postfix::TupleFieldAccess(
|
||||
Ok(inner.next().unwrap().as_str().parse().unwrap_or(255_u8))
|
||||
as AstResult<'_, u8>,
|
||||
inner.next().map(Generics::try_from).transpose(),
|
||||
))
|
||||
}
|
||||
Rule::tuple_field_px => Ok(Postfix::TupleFieldAccess(
|
||||
inner.next().unwrap().as_str().parse().unwrap_or(255_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();
|
||||
Ok((
|
||||
Identifier::try_from(pi.next().unwrap())?,
|
||||
pi.next().map(Expression::try_from).transpose().get()?,
|
||||
pi.next().map(Expression::try_from).transpose()?,
|
||||
))
|
||||
}))),
|
||||
})?)),
|
||||
|
||||
Rule::index_px => {
|
||||
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
|
||||
}
|
||||
Rule::index_px => Ok(Postfix::Index(Expression::try_from(inner.next().unwrap())?)),
|
||||
|
||||
Rule::macro_call_paren => Ok(Postfix::MacroCall {
|
||||
inner: inner.as_str().to_string(),
|
||||
@@ -178,9 +163,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
|
||||
delimiter: MacroDelimiter::Brace,
|
||||
}),
|
||||
|
||||
Rule::as_px => {
|
||||
ast_expr!(Postfix::As(inner.next().unwrap().try_into()))
|
||||
}
|
||||
Rule::as_px => Ok(Postfix::As(inner.next().unwrap().try_into()?)),
|
||||
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::expr_path_segment => {
|
||||
ast_expr!(ExprPathSegment {
|
||||
ident: Identifier::try_from(inner.next().unwrap()),
|
||||
generics: inner.next().map(Generics::try_from).transpose(),
|
||||
Ok(ExprPathSegment {
|
||||
ident: Identifier::try_from(inner.next().unwrap())?,
|
||||
generics: inner.next().map(Generics::try_from).transpose()?,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ pub mod types;
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, AstResult, IntoErr, collect_recovered, collect_recovered_map},
|
||||
ast_ensure,
|
||||
error::{AstError, collect_recovered, collect_recovered_map},
|
||||
parser::{consume_rule, listen_rule},
|
||||
};
|
||||
|
||||
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> {
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
match pair.as_rule() {
|
||||
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
|
||||
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner())?)),
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
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::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
|
||||
Rule::string_lit => Literal::String(inner.as_str().to_string()),
|
||||
Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
|
||||
Rule::tuple => Literal::Tuple(collect_recovered(inner)?),
|
||||
_ => return AstError::bug_unimplemented(pair),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
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)
|
||||
}))),
|
||||
})?)),
|
||||
|
||||
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new)),
|
||||
Rule::named_tuple_pattern => Ok(Pattern::NamedTuple(
|
||||
Path::try_from(inner.next().unwrap())?,
|
||||
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new))?,
|
||||
)),
|
||||
|
||||
Rule::struct_pattern => ast_expr!(Pattern::Struct(
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
Rule::struct_pattern => Ok(Pattern::Struct(
|
||||
Path::try_from(inner.next().unwrap())?,
|
||||
collect_recovered_map(inner, |v| {
|
||||
if v.as_rule() == Rule::etc_pattern {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut inner = v.into_inner();
|
||||
Some(ast_expr!((
|
||||
Identifier::try_from(inner.next().unwrap()),
|
||||
Ok(Some((
|
||||
Identifier::try_from(inner.next().unwrap())?,
|
||||
inner
|
||||
.next()
|
||||
.map(|v| Self::try_from(v).map(Box::new).get_map(Box::new))
|
||||
.transpose()
|
||||
.map(|v| Self::try_from(v).map(Box::new))
|
||||
.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(
|
||||
Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
|
||||
inner.next().unwrap().try_into()
|
||||
Rule::path_pattern => Ok(Pattern::Path(
|
||||
listen_rule(&mut inner, Rule::mutable),
|
||||
inner.next().unwrap().try_into()?,
|
||||
)),
|
||||
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pairs: &mut pest::iterators::Pairs<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
Ok(consume_rule(pairs, Rule::visibility)
|
||||
.map(|pair| -> Result<Visibility, AstError<'a, Self>> {
|
||||
.map(|pair| -> Result<Visibility, AstError<'a>> {
|
||||
if let Some(path) = pair.into_inner().next() {
|
||||
ast_expr!(Visibility::PublicTarget(Path::try_from(path)))
|
||||
Ok(Visibility::PublicTarget(Path::try_from(path)?))
|
||||
} else {
|
||||
Ok(Visibility::Public)
|
||||
}
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
ast_ensure,
|
||||
error::{AstError, collect_recovered},
|
||||
};
|
||||
|
||||
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> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::block => {
|
||||
ast_expr!(Block {
|
||||
statements: collect_recovered(inner.next().unwrap().into_inner()),
|
||||
soft_return: inner.next().map(Spanned::try_from).transpose(),
|
||||
Ok(Block {
|
||||
statements: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||
soft_return: inner.next().map(Spanned::try_from).transpose()?,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::statement_branch => {
|
||||
ast_expr!(StatementBranch {
|
||||
condition: inner.next().unwrap().try_into(),
|
||||
body: inner.next().unwrap().try_into().map(Box::new),
|
||||
Ok(StatementBranch {
|
||||
condition: inner.next().unwrap().try_into()?,
|
||||
body: Box::new(inner.next().unwrap().try_into()?),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
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())
|
||||
}
|
||||
|
||||
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 => {
|
||||
ast_expr!(Statement::Return(
|
||||
inner.next().map(Expression::try_from).transpose()
|
||||
))
|
||||
}
|
||||
Rule::return_stmt => Ok(Statement::Return(
|
||||
inner.next().map(Expression::try_from).transpose()?,
|
||||
)),
|
||||
|
||||
Rule::break_stmt => Ok(Statement::Break),
|
||||
|
||||
Rule::continue_stmt => Ok(Statement::Continue),
|
||||
|
||||
Rule::if_stmt => {
|
||||
ast_expr!(Statement::If {
|
||||
initial: inner.next().unwrap().try_into(),
|
||||
else_if: collect_recovered(inner.next().unwrap().into_inner()),
|
||||
else_branch: inner.next().map(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::if_stmt => Ok(Statement::If {
|
||||
initial: inner.next().unwrap().try_into()?,
|
||||
else_if: collect_recovered(inner.next().unwrap().into_inner())?,
|
||||
else_branch: inner.next().map(Block::try_from).transpose()?,
|
||||
}),
|
||||
|
||||
Rule::for_stmt => ast_expr!(Statement::For {
|
||||
pattern: inner.next().unwrap().try_into(),
|
||||
iterator: inner.next().unwrap().try_into(),
|
||||
body: inner.next().unwrap().try_into(),
|
||||
Rule::while_stmt => Ok(Statement::While(inner.next().unwrap().try_into()?)),
|
||||
|
||||
Rule::loop_stmt => Ok(Statement::Loop(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(
|
||||
inner.next().unwrap().try_into(),
|
||||
collect_recovered(inner),
|
||||
Rule::for_stmt => Ok(Statement::For {
|
||||
pattern: inner.next().unwrap().try_into()?,
|
||||
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),
|
||||
@@ -99,14 +95,14 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
|
||||
}
|
||||
|
||||
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> {
|
||||
let mut match_inner = pair.into_inner();
|
||||
|
||||
Ok(MatchItem(
|
||||
collect_recovered(match_inner.next().unwrap().into_inner()).get()?,
|
||||
Expression::try_from(match_inner.next().unwrap()).get()?,
|
||||
collect_recovered(match_inner.next().unwrap().into_inner())?,
|
||||
Expression::try_from(match_inner.next().unwrap())?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{AstError, AstResult, IntoErr, collect_recovered},
|
||||
ast_ensure,
|
||||
error::{AstError, collect_recovered},
|
||||
parser::{consume_rule, listen_rule},
|
||||
};
|
||||
|
||||
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> {
|
||||
let rule = pair.as_rule();
|
||||
@@ -15,65 +15,109 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
|
||||
|
||||
match rule {
|
||||
Rule::generic => Self::try_from(inner.next().unwrap()),
|
||||
Rule::type_expr => inner.next().unwrap().try_into(),
|
||||
Rule::lifetime => ast_expr!(TypeExpr::Lifetime(inner.next().unwrap().try_into())),
|
||||
Rule::type_expr => {
|
||||
let mut inner = inner;
|
||||
|
||||
Rule::tuple_type => ast_expr!(TypeExpr::Tuple(collect_recovered(inner))),
|
||||
Rule::path_type => {
|
||||
ast_expr!(TypeExpr::Path(
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
inner.next().map(Generics::try_from).transpose()
|
||||
))
|
||||
}
|
||||
let mut ty = TypeExpr::try_from(inner.next().unwrap())?;
|
||||
|
||||
for ref_pair in inner {
|
||||
let mut ref_inner = ref_pair.clone().into_inner();
|
||||
|
||||
match ref_pair.as_rule() {
|
||||
Rule::ref_type => {
|
||||
ast_expr!(TypeExpr::Ref {
|
||||
lifetime: consume_rule(&mut inner, Rule::ref_lifetime)
|
||||
.map(|v| v.into_inner().next().map(Lifetime::try_from))
|
||||
ty = TypeExpr::Ref {
|
||||
mutable: listen_rule(&mut ref_inner, Rule::mutable),
|
||||
lifetime: consume_rule(&mut ref_inner, Rule::lifetime)
|
||||
.map(|v| v.into_inner().next().map(Identifier::try_from))
|
||||
.unwrap_or_default()
|
||||
.transpose(),
|
||||
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<bool>,
|
||||
ty: TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
|
||||
})
|
||||
.transpose()?,
|
||||
ty: Box::new(ty),
|
||||
};
|
||||
}
|
||||
Rule::dyn_type => {
|
||||
ast_expr!(TypeExpr::Dyn(
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let inner = pair.clone().into_inner();
|
||||
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::generic_decl => {
|
||||
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
||||
ast_expr!(GenericDecl::Lifetime(
|
||||
pair.into_inner().next().unwrap().try_into(),
|
||||
Ok(GenericDecl::Lifetime(
|
||||
pair.into_inner().next().unwrap().try_into()?,
|
||||
))
|
||||
} else {
|
||||
ast_expr!(GenericDecl::Type(
|
||||
inner.next().unwrap().try_into(),
|
||||
collect_recovered(inner),
|
||||
Ok(GenericDecl::Type(
|
||||
inner.next().unwrap().try_into()?,
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let inner = pair.clone().into_inner();
|
||||
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
ast_ensure!(pair, Rule::generic => {
|
||||
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
|
||||
ast_expr!(Generic::Lifetime(
|
||||
pair.into_inner().next().unwrap().try_into(),
|
||||
Ok(Generic::Lifetime(
|
||||
pair.into_inner().next().unwrap().try_into()?,
|
||||
))
|
||||
} else {
|
||||
ast_expr!(Generic::Type(
|
||||
inner.next().unwrap().try_into()
|
||||
Ok(Generic::Type(
|
||||
inner.next().unwrap().try_into()?
|
||||
))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
error::{AstError, collect_recovered},
|
||||
};
|
||||
|
||||
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> {
|
||||
match pair.as_rule() {
|
||||
@@ -18,7 +18,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
// 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
|
||||
match inner.next() {
|
||||
@@ -32,7 +32,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
|
||||
// #[path = literal]
|
||||
Ok(Attribute::NameValue {
|
||||
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(...)]
|
||||
Ok(Attribute::List {
|
||||
path,
|
||||
items: collect_recovered(next.into_inner()).get()?,
|
||||
items: collect_recovered(next.into_inner())?,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,48 +1,39 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr},
|
||||
parser::consume_rule,
|
||||
};
|
||||
use crate::{Rule, ast::*, error::AstError, parser::consume_rule};
|
||||
|
||||
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> {
|
||||
let mut inner = pair.into_inner();
|
||||
|
||||
Ok(Self {
|
||||
visibility: Visibility::try_from(&mut inner).get()?,
|
||||
visibility: Visibility::try_from(&mut inner)?,
|
||||
|
||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
|
||||
params: consume_rule(&mut inner, Rule::param_list)
|
||||
.map(ParamList::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.transpose()?
|
||||
.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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let rule = pair.as_rule();
|
||||
|
||||
match rule {
|
||||
Rule::impl_decl | Rule::impl_for_decl => {
|
||||
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
|
||||
}
|
||||
Rule::impl_decl | Rule::impl_for_decl => Ok(ClassItem::ImplDecl(pair.try_into()?)),
|
||||
|
||||
Rule::function_decl => Ok(ClassItem::Method(pair.try_into().get()?)),
|
||||
Rule::function_decl => Ok(ClassItem::Method(pair.try_into()?)),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
}
|
||||
|
||||
@@ -1,31 +1,30 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
error::{AstError, collect_recovered},
|
||||
};
|
||||
|
||||
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> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into().get()?)),
|
||||
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into()?)),
|
||||
|
||||
Rule::enum_tuple => Ok(EnumItem::Tuple(
|
||||
inner.next().unwrap().try_into().get()?,
|
||||
collect_recovered(inner.next().unwrap().into_inner()).get()?,
|
||||
inner.next().unwrap().try_into()?,
|
||||
collect_recovered(inner.next().unwrap().into_inner())?,
|
||||
)),
|
||||
|
||||
Rule::enum_struct => Ok(EnumItem::Struct(
|
||||
inner.next().unwrap().try_into().get()?,
|
||||
inner.next().unwrap().try_into()?,
|
||||
inner
|
||||
.next()
|
||||
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
|
||||
.transpose()
|
||||
.get()?
|
||||
.map(|pair| collect_recovered::<FieldDecl>(pair.into_inner()))
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
)),
|
||||
|
||||
|
||||
@@ -1,78 +1,55 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_ensure, ast_expr,
|
||||
error::{self, AstError, AstResult, IntoErr},
|
||||
parser::{consume_rule, listen_rule},
|
||||
ast_ensure,
|
||||
error::{AstError, AstResult},
|
||||
parser::{consume_rule, consume_rule_map, listen_rule},
|
||||
};
|
||||
|
||||
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> {
|
||||
ast_ensure!(pair, Rule::function_decl => {
|
||||
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)
|
||||
.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)
|
||||
.map(GenericsDecl::try_from)
|
||||
.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 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 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 {
|
||||
name: name.clone(),
|
||||
type_: Some(if is_ref {
|
||||
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
|
||||
}),
|
||||
}
|
||||
});
|
||||
Ok((is_ref, lifetime.map(|v| -> AstResult<Identifier> {
|
||||
Identifier::try_from(v.into_inner().next().unwrap())
|
||||
}).transpose()?, mutable))
|
||||
})?;
|
||||
|
||||
let params = consume_rule(&mut inner, Rule::param_list)
|
||||
.map({
|
||||
let self_param = self_param.clone();
|
||||
|params_pair| -> AstResult<'a, ParamList> {
|
||||
let mut params = ParamList::try_from(params_pair)?;
|
||||
if let Some(x) = self_param {
|
||||
params.0.insert(0, x);
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
|
||||
let params = consume_rule(&mut inner, Rule::param_list).map(ParamList::try_from).transpose()?.unwrap_or_default();
|
||||
|
||||
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,
|
||||
is_override: is_override,
|
||||
return_type: return_type,
|
||||
name: name,
|
||||
generics: generics,
|
||||
self_param: self_param,
|
||||
params: params,
|
||||
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 {
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
ast_ensure!(pair, Rule::override_kw => {
|
||||
ast_expr!(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()))
|
||||
Ok(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()?))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Lifetime {
|
||||
type Error = AstError<'a, Self>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match pair.as_rule() {
|
||||
Rule::ref_lifetime => inner.next().unwrap().try_into(),
|
||||
Rule::lifetime => ast_expr!(Lifetime::Lifetime(inner.next().unwrap().try_into())),
|
||||
Rule::unsafe_kw => Ok(Lifetime::Unsafe),
|
||||
_ => error::AstError::bug_unimplemented(pair),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
error::{AstError, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
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> {
|
||||
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 {
|
||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
trait_: Some(inner.next().unwrap().try_into().get()?),
|
||||
target: inner.next().unwrap().try_into().get()?,
|
||||
methods: collect_recovered(inner).get()?,
|
||||
trait_: Some(inner.next().unwrap().try_into()?),
|
||||
target: inner.next().unwrap().try_into()?,
|
||||
methods: collect_recovered(inner)?,
|
||||
}),
|
||||
|
||||
Rule::impl_decl => Ok(ImplDecl {
|
||||
generics: consume_rule(&mut inner, Rule::generics_decl)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.get()?
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
trait_: None,
|
||||
target: inner.next().unwrap().try_into().get()?,
|
||||
methods: collect_recovered(inner).get()?,
|
||||
target: inner.next().unwrap().try_into()?,
|
||||
methods: collect_recovered(inner)?,
|
||||
}),
|
||||
|
||||
_ => AstError::bug_unimplemented(pair),
|
||||
|
||||
@@ -7,119 +7,119 @@ pub mod impl_decl;
|
||||
use crate::{
|
||||
Rule,
|
||||
ast::*,
|
||||
ast_expr,
|
||||
error::{AstError, IntoErr, collect_recovered},
|
||||
error::{AstError, collect_recovered},
|
||||
parser::consume_rule,
|
||||
};
|
||||
|
||||
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> {
|
||||
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(
|
||||
inner.next().map(Spanned::try_from).unwrap(),
|
||||
Ok(TopLevel(
|
||||
inner
|
||||
.next()
|
||||
.map(Spanned::try_from)
|
||||
.unwrap_or_else(move || Ok(Spanned::new_pair(pair, TopLevelKind::ModAttribute)))?,
|
||||
attributes,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let rule = pair.as_rule();
|
||||
let mut inner = pair.clone().into_inner();
|
||||
|
||||
match rule {
|
||||
Rule::import => ast_expr!(TopLevelKind::Import(
|
||||
Visibility::try_from(&mut inner),
|
||||
Path::try_from(inner.next().unwrap()),
|
||||
Rule::import => Ok(TopLevelKind::Import(
|
||||
Visibility::try_from(&mut inner)?,
|
||||
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 {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
Rule::struct_decl => Ok(TopLevelKind::StructDecl {
|
||||
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)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
.map(|v| v.unwrap_or_default())?,
|
||||
|
||||
fields: inner
|
||||
.next()
|
||||
.map(|pair| collect_recovered(pair.into_inner()))
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
.map(|v| v.unwrap_or_default())?,
|
||||
}),
|
||||
|
||||
Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
Rule::class_decl => Ok(TopLevelKind::ClassDecl {
|
||||
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)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
.map(|v| v.unwrap_or_default())?,
|
||||
|
||||
inherits: consume_rule(&mut inner, Rule::expr_path)
|
||||
.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)
|
||||
.map(Spanned::try_from)
|
||||
.transpose(),
|
||||
.transpose()?,
|
||||
|
||||
items: collect_recovered(inner),
|
||||
items: collect_recovered(inner)?,
|
||||
}),
|
||||
|
||||
Rule::enum_decl => ast_expr!(TopLevelKind::EnumDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
Rule::enum_decl => Ok(TopLevelKind::EnumDecl {
|
||||
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)
|
||||
.map(GenericsDecl::try_from)
|
||||
.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(
|
||||
Visibility::try_from(&mut inner),
|
||||
inner.next().unwrap().try_into(),
|
||||
Rule::declare_module => Ok(TopLevelKind::DeclareModule(
|
||||
Visibility::try_from(&mut inner)?,
|
||||
inner.next().unwrap().try_into()?,
|
||||
)),
|
||||
|
||||
Rule::impl_for_decl | Rule::impl_decl => {
|
||||
ast_expr!(TopLevelKind::ImplDecl(pair.try_into()))
|
||||
}
|
||||
Rule::impl_for_decl | Rule::impl_decl => Ok(TopLevelKind::ImplDecl(pair.try_into()?)),
|
||||
|
||||
Rule::trait_decl => ast_expr!(TopLevelKind::TraitDecl {
|
||||
visibility: Visibility::try_from(&mut inner),
|
||||
Rule::trait_decl => Ok(TopLevelKind::TraitDecl {
|
||||
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)
|
||||
.map(GenericsDecl::try_from)
|
||||
.transpose()
|
||||
.map(|v| v.unwrap_or_default()),
|
||||
.map(|v| v.unwrap_or_default())?,
|
||||
|
||||
requirements: consume_rule(&mut inner, Rule::trait_requirements)
|
||||
.map(|pair| collect_recovered(pair.into_inner()))
|
||||
.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),
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
pub mod common;
|
||||
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 {
|
||||
let consumed = pairs
|
||||
@@ -28,10 +32,36 @@ pub fn consume_rule<'a>(
|
||||
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>
|
||||
{
|
||||
type Error = AstError<'a, Self>;
|
||||
type Error = AstError<'a>;
|
||||
|
||||
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
|
||||
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 {
|
||||
line: span.0,
|
||||
column: span.1,
|
||||
item: pair.try_into().map_err(|err: AstError<'_, T>| AstError {
|
||||
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,
|
||||
}),
|
||||
})?,
|
||||
item: pair.try_into()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn find_function_call<'a>(
|
||||
) -> Option<&'a Spanned<FunctionDecl>> {
|
||||
items.iter().find_map(|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)
|
||||
} else {
|
||||
None
|
||||
@@ -317,12 +317,6 @@ impl GetMutability for Expression {
|
||||
// Recurse into all postfix sub-expressions
|
||||
for postfix in postfixes {
|
||||
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) => {
|
||||
for arg in args {
|
||||
result.append(&mut arg.get_mutability());
|
||||
|
||||
@@ -1,44 +1,47 @@
|
||||
pub module decl_test;
|
||||
|
||||
pub fn void test_let_basic() {
|
||||
pub void test_let_basic()
|
||||
{
|
||||
let x = 42;
|
||||
assert_eq!(x, 42);
|
||||
}
|
||||
|
||||
pub fn void test_let_typed() {
|
||||
let x i32 = 42;
|
||||
pub void test_let_typed()
|
||||
{
|
||||
i32 x = 42;
|
||||
assert_eq!(x, 42);
|
||||
|
||||
let s *str = "hello";
|
||||
str& s = "hello";
|
||||
assert_eq!(s, "hello");
|
||||
|
||||
let b bool = true;
|
||||
bool b = true;
|
||||
assert_eq!(b, true);
|
||||
|
||||
let f f64 = 3.14;
|
||||
f64 f = 3.14;
|
||||
assert_eq!(f, 3.14);
|
||||
}
|
||||
|
||||
pub fn void test_let_mut() {
|
||||
pub void test_let_mut()
|
||||
{
|
||||
let mut _x = 42;
|
||||
_x = 100;
|
||||
assert_eq!(_x, 100);
|
||||
}
|
||||
|
||||
pub fn void test_let_tuple_destructure() {
|
||||
pub void test_let_tuple_destructure()
|
||||
{
|
||||
let (a, b) = (10, "hello");
|
||||
assert_eq!(a, 10);
|
||||
assert_eq!(b, "hello");
|
||||
}
|
||||
|
||||
pub fn void test_let_nested_tuple() {
|
||||
pub void test_let_nested_tuple()
|
||||
{
|
||||
let (a, (b, c)) = (1, (2, 3));
|
||||
assert_eq!(a, 1);
|
||||
assert_eq!(b, 2);
|
||||
assert_eq!(c, 3);
|
||||
}
|
||||
|
||||
pub fn void test_let_pattern_irrefutable() {
|
||||
pub void test_let_pattern_irrefutable()
|
||||
{
|
||||
let x = 5;
|
||||
let (y, z) = (1, 2);
|
||||
assert_eq!(x, 5);
|
||||
@@ -46,30 +49,35 @@ pub fn void test_let_pattern_irrefutable() {
|
||||
assert_eq!(z, 2);
|
||||
}
|
||||
|
||||
pub fn void test_multiple_decls() {
|
||||
pub void test_multiple_decls()
|
||||
{
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
assert_eq!(a + b + c, 6);
|
||||
}
|
||||
|
||||
pub fn void test_let_with_type_and_init() {
|
||||
let x f64 = 10.0;
|
||||
pub void test_let_with_type_and_init()
|
||||
{
|
||||
f64 x = 10.0;
|
||||
assert_eq!(x, 10.0);
|
||||
}
|
||||
|
||||
pub fn void test_string_literal() {
|
||||
pub void test_string_literal()
|
||||
{
|
||||
let s = "hello, world!";
|
||||
assert_eq!(s.len(), 13);
|
||||
}
|
||||
|
||||
pub fn void test_let_bool() {
|
||||
pub void test_let_bool()
|
||||
{
|
||||
let t = true;
|
||||
let f = false;
|
||||
assert_eq!(t, !f);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_let_basic();
|
||||
test_let_typed();
|
||||
test_let_mut();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub module expr_test;
|
||||
|
||||
pub fn void test_literals() {
|
||||
pub void test_literals()
|
||||
{
|
||||
assert_eq!(42, 42);
|
||||
assert_eq!(3.14, 3.14);
|
||||
assert_eq!(true, true);
|
||||
@@ -8,28 +9,32 @@ pub fn void test_literals() {
|
||||
assert_eq!("hello", "hello");
|
||||
}
|
||||
|
||||
pub fn void test_tuples() {
|
||||
pub void test_tuples()
|
||||
{
|
||||
let t = (1, true, "three");
|
||||
assert_eq!(t.0, 1);
|
||||
assert_eq!(t.1, true);
|
||||
assert_eq!(t.2, "three");
|
||||
}
|
||||
|
||||
pub fn void test_arrays() {
|
||||
pub void test_arrays()
|
||||
{
|
||||
let arr = [1, 2, 3];
|
||||
assert_eq!(arr[0], 1);
|
||||
assert_eq!(arr[1], 2);
|
||||
assert_eq!(arr[2], 3);
|
||||
}
|
||||
|
||||
pub fn void test_array_repeat() {
|
||||
pub void test_array_repeat()
|
||||
{
|
||||
let arr = [0; 5];
|
||||
assert_eq!(arr[0], 0);
|
||||
assert_eq!(arr[4], 0);
|
||||
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, 5);
|
||||
assert_eq!(10 * 5, 50);
|
||||
@@ -37,7 +42,8 @@ pub fn void test_binary_arith() {
|
||||
assert_eq!(10 % 3, 1);
|
||||
}
|
||||
|
||||
pub fn void test_binary_cmp() {
|
||||
pub void test_binary_cmp()
|
||||
{
|
||||
assert_eq!(5 < 10, true);
|
||||
assert_eq!(10 <= 10, true);
|
||||
assert_eq!(10 > 5, true);
|
||||
@@ -46,14 +52,16 @@ pub fn void test_binary_cmp() {
|
||||
assert_eq!(5 != 10, true);
|
||||
}
|
||||
|
||||
pub fn void test_binary_logic() {
|
||||
pub void test_binary_logic()
|
||||
{
|
||||
assert_eq!(true && true, true);
|
||||
assert_eq!(true && false, false);
|
||||
assert_eq!(true || false, true);
|
||||
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, 7);
|
||||
assert_eq!(5 ^ 3, 6);
|
||||
@@ -61,20 +69,23 @@ pub fn void test_binary_bit() {
|
||||
assert_eq!(4 >> 1, 2);
|
||||
}
|
||||
|
||||
pub fn void test_prefix() {
|
||||
pub void test_prefix()
|
||||
{
|
||||
let x = 42;
|
||||
assert_eq!(-x, -42);
|
||||
assert_eq!(!true, false);
|
||||
assert_eq!(!false, true);
|
||||
}
|
||||
|
||||
pub fn void test_ref_deref() {
|
||||
pub void test_ref_deref()
|
||||
{
|
||||
let x = 42;
|
||||
let r = &x;
|
||||
assert_eq!(*r, 42);
|
||||
}
|
||||
|
||||
pub fn void test_postfix_inc_dec() {
|
||||
pub void test_postfix_inc_dec()
|
||||
{
|
||||
let mut x = 5;
|
||||
x++;
|
||||
assert_eq!(x, 6);
|
||||
@@ -82,17 +93,20 @@ pub fn void test_postfix_inc_dec() {
|
||||
assert_eq!(x, 5);
|
||||
}
|
||||
|
||||
pub fn void test_as_cast() {
|
||||
pub void test_as_cast()
|
||||
{
|
||||
let x = 42;
|
||||
assert_eq!(x as f64, 42.0);
|
||||
}
|
||||
|
||||
pub fn void test_closure() {
|
||||
let add = fn(a, b) -> a + b;
|
||||
pub void test_closure()
|
||||
{
|
||||
let add = (a, b) => a + b;
|
||||
assert_eq!(add(2, 3), 5);
|
||||
}
|
||||
|
||||
pub fn void test_block_expr() {
|
||||
pub void test_block_expr()
|
||||
{
|
||||
let x = {
|
||||
let y = 10;
|
||||
y + 5
|
||||
@@ -100,16 +114,25 @@ pub fn void test_block_expr() {
|
||||
assert_eq!(x, 15);
|
||||
}
|
||||
|
||||
pub fn void test_if_expr() {
|
||||
let x = if true { 1 } else { 2 };
|
||||
pub void test_if_expr()
|
||||
{
|
||||
let x = if true {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
assert_eq!(x, 1);
|
||||
|
||||
let y = if false { 1 } else { 2 };
|
||||
let y = if false {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
assert_eq!(y, 2);
|
||||
}
|
||||
|
||||
pub fn void test_range_expr() {
|
||||
let r = 0..5;
|
||||
pub void test_range_expr()
|
||||
{
|
||||
let r = 0 .. 5;
|
||||
let mut count = 0;
|
||||
for i in r {
|
||||
count++;
|
||||
@@ -117,7 +140,8 @@ pub fn void test_range_expr() {
|
||||
assert_eq!(count, 5);
|
||||
}
|
||||
|
||||
pub fn void test_binary_assign() {
|
||||
pub void test_binary_assign()
|
||||
{
|
||||
let mut x = 10;
|
||||
x += 5;
|
||||
assert_eq!(x, 15);
|
||||
@@ -131,7 +155,8 @@ pub fn void test_binary_assign() {
|
||||
assert_eq!(x, 2);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_literals();
|
||||
test_tuples();
|
||||
test_arrays();
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub module common;
|
||||
|
||||
pub fn void test_package() {}
|
||||
pub void test_package() {}
|
||||
|
||||
@@ -1,30 +1,29 @@
|
||||
pub module statement_test;
|
||||
|
||||
pub fn void test_var_decl() {
|
||||
pub void test_var_decl()
|
||||
{
|
||||
let x = 42;
|
||||
assert_eq!(x, 42);
|
||||
|
||||
let y i32 = 10;
|
||||
i32 y = 10;
|
||||
assert_eq!(y, 10);
|
||||
|
||||
let name *str = "mist";
|
||||
str& 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;
|
||||
x = 5;
|
||||
assert_eq!(x, 5);
|
||||
}
|
||||
|
||||
pub fn void test_if_statement() {
|
||||
pub void test_if_statement()
|
||||
{
|
||||
let mut x = 0;
|
||||
|
||||
if true {
|
||||
x = 1;
|
||||
}
|
||||
assert_eq!(x, 1);
|
||||
|
||||
if false {
|
||||
x = 2;
|
||||
} else {
|
||||
@@ -33,9 +32,9 @@ pub fn void test_if_statement() {
|
||||
assert_eq!(x, 3);
|
||||
}
|
||||
|
||||
pub fn void test_if_else_if() {
|
||||
pub void test_if_else_if()
|
||||
{
|
||||
let mut x = 0;
|
||||
|
||||
if x == 1 {
|
||||
x = 10;
|
||||
} else if x == 0 {
|
||||
@@ -46,27 +45,27 @@ pub fn void test_if_else_if() {
|
||||
assert_eq!(x, 20);
|
||||
}
|
||||
|
||||
pub fn void test_while_loop() {
|
||||
pub void test_while_loop()
|
||||
{
|
||||
let mut count = 0;
|
||||
|
||||
while count < 5 {
|
||||
count++;
|
||||
}
|
||||
assert_eq!(count, 5);
|
||||
}
|
||||
|
||||
pub fn void test_for_loop() {
|
||||
pub void test_for_loop()
|
||||
{
|
||||
let mut sum = 0;
|
||||
|
||||
for i in 0..4 {
|
||||
for i in 0 .. 4 {
|
||||
sum += i;
|
||||
}
|
||||
assert_eq!(sum, 6);
|
||||
}
|
||||
|
||||
pub fn void test_loop_stmt() {
|
||||
pub void test_loop_stmt()
|
||||
{
|
||||
let mut count = 0;
|
||||
|
||||
loop {
|
||||
count++;
|
||||
if count >= 3 {
|
||||
@@ -76,10 +75,10 @@ pub fn void test_loop_stmt() {
|
||||
assert_eq!(count, 3);
|
||||
}
|
||||
|
||||
pub fn void test_break_continue() {
|
||||
pub void test_break_continue()
|
||||
{
|
||||
let mut sum = 0;
|
||||
|
||||
for i in 0..10 {
|
||||
for i in 0 .. 10 {
|
||||
if i % 2 == 0 {
|
||||
continue;
|
||||
}
|
||||
@@ -91,11 +90,13 @@ pub fn void test_break_continue() {
|
||||
assert_eq!(sum, 1 + 3 + 5);
|
||||
}
|
||||
|
||||
pub fn i32 test_return() {
|
||||
pub i32 test_return()
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
pub fn void test_block_scope() {
|
||||
pub void test_block_scope()
|
||||
{
|
||||
let x = {
|
||||
let inner = 10;
|
||||
inner + 5
|
||||
@@ -103,53 +104,64 @@ pub fn void test_block_scope() {
|
||||
assert_eq!(x, 15);
|
||||
}
|
||||
|
||||
pub fn void test_match_literal() {
|
||||
pub void test_match_literal()
|
||||
{
|
||||
let x = 2;
|
||||
let result;
|
||||
|
||||
match x {
|
||||
1 => { result = 10; }
|
||||
2 => { result = 20; }
|
||||
3 => { result = 30; }
|
||||
_ => panic!();
|
||||
1 => {
|
||||
result = 10;
|
||||
}
|
||||
2 => result = 20,
|
||||
3 => result = 30,
|
||||
_ => panic!(),
|
||||
}
|
||||
assert_eq!(result, 20);
|
||||
}
|
||||
|
||||
pub fn void test_match_or_pattern() {
|
||||
pub void test_match_or_pattern()
|
||||
{
|
||||
let x = 1;
|
||||
let result i32;
|
||||
|
||||
i32 result;
|
||||
match x {
|
||||
1 | 2 => { result = 100; }
|
||||
3 => { result = 200; }
|
||||
_ => panic!();
|
||||
1 | 2 => {
|
||||
result = 100;
|
||||
}
|
||||
3 => {
|
||||
result = 200;
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
assert_eq!(result, 100);
|
||||
}
|
||||
|
||||
pub fn void test_match_default() {
|
||||
pub void test_match_default()
|
||||
{
|
||||
let x = 99;
|
||||
let result;
|
||||
|
||||
match x {
|
||||
1 => { result = 10; }
|
||||
y => { result = y; }
|
||||
1 => {
|
||||
result = 10;
|
||||
}
|
||||
y => {
|
||||
result = y;
|
||||
}
|
||||
}
|
||||
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 mut keys = 0;
|
||||
|
||||
for (k, _) in pairs {
|
||||
keys += k;
|
||||
}
|
||||
assert_eq!(keys, 3);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_var_decl();
|
||||
test_var_decl_with_init();
|
||||
test_if_statement();
|
||||
|
||||
@@ -1,58 +1,58 @@
|
||||
pub module types_test;
|
||||
|
||||
pub fn void test_integer_type() {
|
||||
let x i32 = 42;
|
||||
pub void test_integer_type() {
|
||||
i32 x = 42;
|
||||
assert_eq!(x, 42);
|
||||
}
|
||||
|
||||
pub fn void test_float_type() {
|
||||
let x f64 = 3.14;
|
||||
pub void test_float_type() {
|
||||
f64 x = 3.14;
|
||||
assert_eq!(x, 3.14);
|
||||
}
|
||||
|
||||
pub fn void test_bool_type() {
|
||||
let x bool = true;
|
||||
pub void test_bool_type() {
|
||||
bool x = true;
|
||||
assert_eq!(x, true);
|
||||
|
||||
let y bool = false;
|
||||
bool y = false;
|
||||
assert_eq!(y, false);
|
||||
}
|
||||
|
||||
pub fn void test_string_type() {
|
||||
let s *str = "hello";
|
||||
pub void test_string_type() {
|
||||
str& s = "hello";
|
||||
assert_eq!(s, "hello");
|
||||
}
|
||||
|
||||
pub fn void test_tuple_type() {
|
||||
let t (i32, *str) = (42, "answer");
|
||||
pub void test_tuple_type() {
|
||||
(i32, str&) t = (42, "answer");
|
||||
assert_eq!(t.0, 42);
|
||||
assert_eq!(t.1, "answer");
|
||||
}
|
||||
|
||||
pub fn void test_ref_type() {
|
||||
let x i32 = 42;
|
||||
let r *i32 = &x;
|
||||
pub void test_ref_type() {
|
||||
i32 x = 42;
|
||||
i32& r = &x;
|
||||
assert_eq!(*r, 42);
|
||||
}
|
||||
|
||||
pub fn void test_mut_ref_type() {
|
||||
pub void test_mut_ref_type() {
|
||||
let mut x = 42;
|
||||
let r *mut i32 = &mut x;
|
||||
i32 mut& r = &mut x;
|
||||
*r = 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
|
||||
}
|
||||
|
||||
pub fn void test_fn_return_type() {
|
||||
pub void test_fn_return_type() {
|
||||
assert_eq!(add(3, 4), 7);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests() {
|
||||
test_integer_type();
|
||||
test_float_type();
|
||||
test_bool_type();
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
pub module attribute_test;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Debuggable {
|
||||
value i32,
|
||||
pub struct Debuggable
|
||||
{
|
||||
i32 value,
|
||||
}
|
||||
|
||||
pub fn void test_derive_attribute() {
|
||||
let d = Debuggable { value: 42 };
|
||||
pub void test_derive_attribute()
|
||||
{
|
||||
let d = Debuggable {
|
||||
value: 42,
|
||||
};
|
||||
assert_eq!(d.value, 42);
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
pub fn void test_allow_attribute() {
|
||||
pub void test_allow_attribute()
|
||||
{
|
||||
let x = 42;
|
||||
let y = "unused";
|
||||
assert_eq!(x, 42);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_derive_attribute();
|
||||
test_allow_attribute();
|
||||
}
|
||||
|
||||
@@ -1,56 +1,68 @@
|
||||
pub module class_test;
|
||||
|
||||
pub class Animal {
|
||||
pub name String;
|
||||
pub class Animal
|
||||
{
|
||||
pub String name;
|
||||
|
||||
constructor() {
|
||||
constructor()
|
||||
{
|
||||
self.name = "Rex".to_string();
|
||||
}
|
||||
|
||||
pub fn String speak(*self) {
|
||||
pub String speak(&self)
|
||||
{
|
||||
"Unknown".to_string()
|
||||
}
|
||||
|
||||
pub fn void test_speak(*self) {
|
||||
pub void test_speak<'a>(&'a self)
|
||||
{
|
||||
assert_eq!(self.speak(), "Woof!");
|
||||
}
|
||||
|
||||
pub fn void static_method() {}
|
||||
pub void static_method()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
pub class Mammal : Animal {
|
||||
constructor() {
|
||||
pub class Mammal : Animal
|
||||
{
|
||||
constructor()
|
||||
{
|
||||
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!(y, "hello");
|
||||
}
|
||||
}
|
||||
|
||||
pub class Dog : Mammal {
|
||||
constructor() {
|
||||
pub class Dog : Mammal
|
||||
{
|
||||
constructor()
|
||||
{
|
||||
super = Super::new();
|
||||
}
|
||||
|
||||
pub fn String speak(*self) override(Animal) {
|
||||
pub String speak(&self) override(Animal)
|
||||
{
|
||||
"Woof!".to_string()
|
||||
}
|
||||
|
||||
impl std::fmt::Display {
|
||||
fn Result<(), std::fmt::Error> fmt(*self, f *mut std::fmt::Formatter<'_>) {
|
||||
impl std::fmt::Display
|
||||
{
|
||||
Result<(), std::fmt::Error> fmt(&self, std::fmt::Formatter<'_> mut& f)
|
||||
{
|
||||
write!(f, "🐾 {}", self.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
let dawg = Dog::new();
|
||||
|
||||
dawg.args_test(10, "hello");
|
||||
|
||||
dawg.test_speak();
|
||||
|
||||
assert_eq!(format!("{dawg}"), "🐾 Rex");
|
||||
}
|
||||
|
||||
@@ -1,60 +1,92 @@
|
||||
pub module enum_test;
|
||||
|
||||
enum OptionInt {
|
||||
enum OptionInt
|
||||
{
|
||||
None,
|
||||
Some(i32),
|
||||
}
|
||||
|
||||
pub fn void test_enum_named() {
|
||||
pub void test_enum_named()
|
||||
{
|
||||
let x = OptionInt::None;
|
||||
match x {
|
||||
OptionInt::None => { assert_eq!(1, 1); }
|
||||
OptionInt::Some(_) => { assert_eq!(0, 1); }
|
||||
OptionInt::None => {
|
||||
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);
|
||||
match x {
|
||||
OptionInt::None => { assert_eq!(0, 1); }
|
||||
OptionInt::Some(v) => { assert_eq!(v, 42); }
|
||||
OptionInt::None => {
|
||||
assert_eq!(0, 1);
|
||||
}
|
||||
OptionInt::Some(v) => {
|
||||
assert_eq!(v, 42);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Shape {
|
||||
Circle { radius i32 },
|
||||
Rect { w i32, h i32 },
|
||||
enum Shape
|
||||
{
|
||||
Circle {i32 radius},
|
||||
Rect {i32 w, i32 h},
|
||||
}
|
||||
|
||||
pub fn void test_enum_struct() {
|
||||
let c = Shape::Circle { radius: 5 };
|
||||
pub void test_enum_struct()
|
||||
{
|
||||
let c = Shape::Circle {
|
||||
radius: 5,
|
||||
};
|
||||
match c {
|
||||
Shape::Circle { radius } => { assert_eq!(radius, 5); }
|
||||
Shape::Rect { .. } => { assert_eq!(0, 1); }
|
||||
Shape::Circle {radius} => {
|
||||
assert_eq!(radius, 5);
|
||||
}
|
||||
|
||||
let r = Shape::Rect { w: 3, h: 4 };
|
||||
Shape::Rect {..} => {
|
||||
assert_eq!(0, 1);
|
||||
}
|
||||
}
|
||||
let r = Shape::Rect {
|
||||
w: 3,
|
||||
h: 4,
|
||||
};
|
||||
match r {
|
||||
Shape::Circle { .. } => { assert_eq!(0, 1); }
|
||||
Shape::Rect { w, h } => { assert_eq!(w * h, 12); }
|
||||
Shape::Circle {..} => {
|
||||
assert_eq!(0, 1);
|
||||
}
|
||||
Shape::Rect {w, h} => {
|
||||
assert_eq!(w * h, 12);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Color {
|
||||
enum Color
|
||||
{
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
pub fn void test_enum_eq() {
|
||||
pub void test_enum_eq()
|
||||
{
|
||||
let c = Color::Red;
|
||||
match c {
|
||||
Color::Red => { assert_eq!(1, 1); }
|
||||
_ => { assert_eq!(0, 1); }
|
||||
Color::Red => {
|
||||
assert_eq!(1, 1);
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_enum_named();
|
||||
test_enum_tuple();
|
||||
test_enum_struct();
|
||||
|
||||
@@ -1,60 +1,76 @@
|
||||
pub module function_test;
|
||||
|
||||
fn void greet() {
|
||||
void greet()
|
||||
{
|
||||
let mut x = 1;
|
||||
x++;
|
||||
}
|
||||
|
||||
pub fn void test_basic_function() {
|
||||
pub void test_basic_function()
|
||||
{
|
||||
greet();
|
||||
}
|
||||
|
||||
fn i32 add(a i32, b i32) {
|
||||
i32 add(i32 a, i32 b)
|
||||
{
|
||||
a + b
|
||||
}
|
||||
|
||||
pub fn void test_fn_params() {
|
||||
pub void test_fn_params()
|
||||
{
|
||||
assert_eq!(add(2, 3), 5);
|
||||
}
|
||||
|
||||
pub fn i32 test_fn_return() {
|
||||
pub i32 test_fn_return()
|
||||
{
|
||||
42
|
||||
}
|
||||
|
||||
pub fn i32 test_fn_early_return() {
|
||||
pub i32 test_fn_early_return()
|
||||
{
|
||||
return 100;
|
||||
0
|
||||
}
|
||||
|
||||
pub fn i32 test_fn_mut_param(mut x i32) {
|
||||
pub i32 test_fn_mut_param(i32 mut x)
|
||||
{
|
||||
x = x + 10;
|
||||
x
|
||||
}
|
||||
|
||||
pub fn void test_method_call() {
|
||||
pub void test_method_call()
|
||||
{
|
||||
let s = "hello";
|
||||
assert_eq!(s.len(), 5);
|
||||
assert_eq!(s.to_uppercase(), "HELLO");
|
||||
}
|
||||
|
||||
fn i32 triple(x i32) {
|
||||
i32 triple(i32 x)
|
||||
{
|
||||
add(x, add(x, x))
|
||||
}
|
||||
|
||||
pub fn void test_nested_fn_calls() {
|
||||
pub void test_nested_fn_calls()
|
||||
{
|
||||
assert_eq!(triple(5), 15);
|
||||
}
|
||||
|
||||
fn i32 factorial(n i32) {
|
||||
if n <= 1 { 1 }
|
||||
else { n * factorial(n - 1) }
|
||||
i32 factorial(i32 n)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_basic_function();
|
||||
test_fn_params();
|
||||
assert_eq!(test_fn_return(), 42);
|
||||
|
||||
@@ -1,39 +1,55 @@
|
||||
pub module impl_test;
|
||||
|
||||
struct Vector2 {
|
||||
x i32,
|
||||
y i32,
|
||||
struct Vector2
|
||||
{
|
||||
i32 x,
|
||||
i32 y,
|
||||
}
|
||||
|
||||
impl Vector2 {
|
||||
pub fn i32 magnitude(*self) {
|
||||
impl Vector2
|
||||
{
|
||||
pub i32 magnitude(&self)
|
||||
{
|
||||
self.x * self.x + self.y * self.y
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void test_inherent_impl() {
|
||||
let v = Vector2 { x: 3, y: 4 };
|
||||
pub void test_inherent_impl()
|
||||
{
|
||||
let v = Vector2 {
|
||||
x: 3,
|
||||
y: 4,
|
||||
};
|
||||
assert_eq!(v.magnitude(), 25);
|
||||
}
|
||||
|
||||
trait Display {
|
||||
fn String display(*self);
|
||||
trait Display
|
||||
{
|
||||
String display(&self);
|
||||
}
|
||||
|
||||
impl Display for Vector2 {
|
||||
fn String display(*self) {
|
||||
impl Display for Vector2
|
||||
{
|
||||
String display(&self)
|
||||
{
|
||||
format!("({}, {})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void test_trait_impl_block() {
|
||||
let v = Vector2 { x: 1, y: 2 };
|
||||
pub void test_trait_impl_block()
|
||||
{
|
||||
let v = Vector2 {
|
||||
x: 1,
|
||||
y: 2,
|
||||
};
|
||||
let s = v.display();
|
||||
assert_eq!(s.len() > 0, true);
|
||||
}
|
||||
|
||||
impl Vector2 {
|
||||
pub fn Vector2 add(*self, other Vector2) {
|
||||
impl Vector2
|
||||
{
|
||||
pub Vector2 add(&self, Vector2 other)
|
||||
{
|
||||
Vector2 {
|
||||
x: self.x + other.x,
|
||||
y: self.y + other.y,
|
||||
@@ -41,15 +57,23 @@ impl Vector2 {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void test_multiple_impls() {
|
||||
let a = Vector2 { x: 1, y: 2 };
|
||||
let b = Vector2 { x: 3, y: 4 };
|
||||
pub void test_multiple_impls()
|
||||
{
|
||||
let a = Vector2 {
|
||||
x: 1,
|
||||
y: 2,
|
||||
};
|
||||
let b = Vector2 {
|
||||
x: 3,
|
||||
y: 4,
|
||||
};
|
||||
let c = a.add(b);
|
||||
assert_eq!(c.x, 4);
|
||||
assert_eq!(c.y, 6);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_inherent_impl();
|
||||
test_trait_impl_block();
|
||||
test_multiple_impls();
|
||||
|
||||
@@ -1,44 +1,66 @@
|
||||
pub module struct_test;
|
||||
|
||||
struct Point {
|
||||
x i32,
|
||||
y i32,
|
||||
struct Point
|
||||
{
|
||||
i32 x,
|
||||
i32 y,
|
||||
}
|
||||
|
||||
pub fn void test_struct_create_access() {
|
||||
let p = Point { x: 10, y: 20 };
|
||||
pub void test_struct_create_access()
|
||||
{
|
||||
let p = Point {
|
||||
x: 10,
|
||||
y: 20,
|
||||
};
|
||||
assert_eq!(p.x, 10);
|
||||
assert_eq!(p.y, 20);
|
||||
}
|
||||
|
||||
pub fn void test_struct_mut_field() {
|
||||
let mut p = Point { x: 1, y: 2 };
|
||||
pub void test_struct_mut_field()
|
||||
{
|
||||
let mut p = Point {
|
||||
x: 1,
|
||||
y: 2,
|
||||
};
|
||||
p.x = 100;
|
||||
assert_eq!(p.x, 100);
|
||||
}
|
||||
|
||||
pub fn void test_struct_destructure() {
|
||||
let p = Point { x: 3, y: 4 };
|
||||
let Point { x, y } = p;
|
||||
pub void test_struct_destructure()
|
||||
{
|
||||
let p = Point {
|
||||
x: 3,
|
||||
y: 4,
|
||||
};
|
||||
let Point {x, y} = p;
|
||||
assert_eq!(x, 3);
|
||||
assert_eq!(y, 4);
|
||||
}
|
||||
|
||||
struct Line {
|
||||
start Point,
|
||||
end Point,
|
||||
struct Line
|
||||
{
|
||||
Point start,
|
||||
Point end,
|
||||
}
|
||||
|
||||
pub fn void test_struct_nested() {
|
||||
pub void test_struct_nested()
|
||||
{
|
||||
let l = Line {
|
||||
start: Point { x: 0, y: 0 },
|
||||
end: Point { x: 5, y: 10 },
|
||||
start: Point {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
end: Point {
|
||||
x: 5,
|
||||
y: 10,
|
||||
},
|
||||
};
|
||||
assert_eq!(l.start.x, 0);
|
||||
assert_eq!(l.end.y, 10);
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_struct_create_access();
|
||||
test_struct_mut_field();
|
||||
test_struct_destructure();
|
||||
|
||||
@@ -1,41 +1,55 @@
|
||||
pub module trait_test;
|
||||
|
||||
trait Speak {
|
||||
fn String speak(*self);
|
||||
trait Speak
|
||||
{
|
||||
String speak(&self);
|
||||
}
|
||||
|
||||
trait Greet : Speak {
|
||||
fn String greet(*self);
|
||||
trait Greet : Speak
|
||||
{
|
||||
String greet(&self);
|
||||
}
|
||||
|
||||
struct Dog {
|
||||
name String,
|
||||
struct Dog
|
||||
{
|
||||
String name,
|
||||
}
|
||||
|
||||
impl Speak for Dog {
|
||||
fn String speak(*self) {
|
||||
impl Speak for Dog
|
||||
{
|
||||
String speak(&self)
|
||||
{
|
||||
"woof".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Greet for Dog {
|
||||
fn String greet(*self) {
|
||||
impl Greet for Dog
|
||||
{
|
||||
String greet(&self)
|
||||
{
|
||||
"hello".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn void test_trait_impl() {
|
||||
let d = Dog { name: "Rex".to_string() };
|
||||
pub void test_trait_impl()
|
||||
{
|
||||
let d = Dog {
|
||||
name: "Rex".to_string(),
|
||||
};
|
||||
assert_eq!(d.speak(), "woof");
|
||||
}
|
||||
|
||||
pub fn void test_trait_with_requirement() {
|
||||
let d = Dog { name: "Buddy".to_string() };
|
||||
pub void test_trait_with_requirement()
|
||||
{
|
||||
let d = Dog {
|
||||
name: "Buddy".to_string(),
|
||||
};
|
||||
assert_eq!(d.speak(), "woof");
|
||||
assert_eq!(d.greet(), "hello");
|
||||
}
|
||||
|
||||
pub fn void run_tests() {
|
||||
pub void run_tests()
|
||||
{
|
||||
test_trait_impl();
|
||||
test_trait_with_requirement();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
fn void main() {
|
||||
void main()
|
||||
{
|
||||
println!("running common tests...");
|
||||
common::test_package();
|
||||
common::expr_test::run_tests();
|
||||
common::statement_test::run_tests();
|
||||
common::decl_test::run_tests();
|
||||
common::types_test::run_tests();
|
||||
|
||||
println!("running items tests...");
|
||||
items::function_test::run_tests();
|
||||
items::struct_test::run_tests();
|
||||
@@ -14,6 +14,5 @@ fn void main() {
|
||||
items::trait_test::run_tests();
|
||||
items::impl_test::run_tests();
|
||||
items::attribute_test::run_tests();
|
||||
|
||||
println!("\x1b[32m\nAll tests passed!\x1b[0m");
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
fn void main() {
|
||||
void main() {
|
||||
mist_analyzer::start();
|
||||
}
|
||||
|
||||
+8
-8
@@ -4,8 +4,8 @@ use std::fs;
|
||||
use mist_api::builder;
|
||||
use mist_api::transpiler;
|
||||
|
||||
fn void main() {
|
||||
let args Vec<String> = env::args().collect();
|
||||
void main() {
|
||||
Vec<String> args = env::args().collect();
|
||||
|
||||
if args.len() < 2 {
|
||||
print_usage();
|
||||
@@ -44,7 +44,7 @@ fn void main() {
|
||||
}
|
||||
}
|
||||
|
||||
fn void print_usage() {
|
||||
void print_usage() {
|
||||
println!("Mist - the mist compiler\n");
|
||||
println!(" View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
|
||||
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
|
||||
@@ -66,7 +66,7 @@ fn void print_usage() {
|
||||
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);
|
||||
|
||||
process::Command::new("cargo")
|
||||
@@ -77,7 +77,7 @@ fn void init_project(mut args Vec<String>) {
|
||||
.spawn()
|
||||
.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 {
|
||||
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");
|
||||
}
|
||||
|
||||
fn void inject_mist_target(is_lib bool) {
|
||||
let toml_content String = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
|
||||
void inject_mist_target(bool is_lib) {
|
||||
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"
|
||||
} else {
|
||||
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"
|
||||
|
||||
Reference in New Issue
Block a user