Compare commits

..
50 Commits
Author SHA1 Message Date
selimaj-dev 352d0594b2 Merge pull request #120 from mist-go/patches
Patches
2026-07-14 09:20:05 +02:00
selimaj-dev 48ca58725a RA passthrough 2026-07-14 09:13:22 +02:00
selimaj-dev 708b956750 fix Analyzer file path #118 2026-07-14 08:46:33 +02:00
selimaj-dev df9e31e26d fix Analyzer file path #118 2026-07-14 07:59:36 +02:00
selimaj-dev c716b6352c Fix mapping for analyzer 2026-07-14 07:47:25 +02:00
selimaj-dev 6f675b4253 Fix mapping for compiler 2026-07-14 07:37:16 +02:00
selimaj-dev 5079b10819 Added other struct types #117 2026-07-14 07:32:42 +02:00
selimaj-dev d834ff595d Added more struct rules #117 2026-07-14 07:19:43 +02:00
selimaj-dev 70ec348f4d Fix mutability #119 2026-07-14 07:15:17 +02:00
selimaj-dev 93ba0e97da Bump to full release 2026-07-12 06:44:13 -04:00
selimaj-dev 9c0aa3d182 Merge pull request #116 from mist-go/patches
Patches
2026-07-12 12:02:00 +02:00
selimaj-dev e1b851911d Fix completion polution 2026-07-12 06:00:16 -04:00
selimaj-dev 72f7b8430d Fix publish command 2026-07-12 05:43:50 -04:00
selimaj-dev 0100abfa53 Fix analyzer bugs 2026-07-12 05:36:57 -04:00
selimaj-dev 01b7e816ee Fix include manifest path #106 2026-07-12 05:26:33 -04:00
selimaj-dev ac94882e5a Fix mapping system #115 2026-07-12 05:15:00 -04:00
selimaj-dev 9220ee3b29 Merge pull request #114 from mist-go/type-patches
Type patches
2026-07-09 12:12:54 +02:00
selimaj-dev b15f13880a Fix generics and fn types 2026-07-09 12:07:37 +02:00
selimaj-dev d538168692 Removed unnecessary type (lifetime) 2026-07-09 12:00:11 +02:00
selimaj-dev b68e4245d4 Using core for classes 2026-07-09 10:53:07 +02:00
selimaj-dev c5354ff424 Using core for c_void 2026-07-09 10:51:44 +02:00
selimaj-dev be68f93038 Updated bootstrap 2026-07-09 10:26:06 +02:00
selimaj-dev e3c9657b07 Bump version to 0.4.0-alpha.0 2026-07-09 07:39:46 +02:00
selimaj-dev 2aab50d36d Merge pull request #112 from mist-go/virtual-methods
Virtual methods
2026-07-09 07:38:25 +02:00
selimaj-dev e75b707981 Virtual and overrides in analyzer 2026-07-09 07:34:08 +02:00
selimaj-dev 18a13dd170 Override and virtual semantic checking 2026-07-09 06:59:25 +02:00
selimaj-dev aacc08b983 Updated class tests 2026-07-09 06:51:36 +02:00
selimaj-dev df8e67fd4f Implicit virtual on override 2026-07-09 06:37:37 +02:00
selimaj-dev 08771fe5be Virtual functions 2026-07-09 06:30:11 +02:00
selimaj-dev 0d2199ee3a virtual keyword parsing and ast 2026-07-09 06:23:04 +02:00
selimaj-dev 442d1e66a8 Merge pull request #111 from mist-go/include
Include
2026-07-08 11:26:29 +02:00
selimaj-dev 8198b8d5cb Local include 2026-07-08 11:23:36 +02:00
selimaj-dev 44ac3c365d Inline doc gen 2026-07-08 10:52:11 +02:00
selimaj-dev c564fc3e90 Added use include 2026-07-08 10:44:09 +02:00
selimaj-dev bb006c1ba2 Added global include 2026-07-08 10:11:26 +02:00
selimaj-dev 4b69bbaed0 Merge pull request #110 from mist-go/array-type
Array type
2026-07-05 02:47:19 +02:00
selimaj-dev f574d6e8af Fix parenthesis 2026-07-05 02:45:38 +02:00
selimaj-dev 13664413c5 Array types 2026-07-05 02:37:48 +02:00
selimaj-dev b6256283a6 Merge pull request #109 from mist-go/more-tests
Add comprehensive test coverage for grammar rules
2026-07-04 21:59:58 +02:00
selimaj-dev f30613f094 Added more tests 2026-07-04 21:55:29 +02:00
selimaj-dev a1fd169568 Added more links 2026-07-04 21:39:30 +02:00
selimaj-dev 3c5f13f3f6 Merge pull request #108 from mist-go/struct-field-style
Allman struct/enum field style, tuple var decls, cleanup
2026-07-04 19:34:57 +02:00
selimaj-dev f4f92c57ee Fix as type 2026-07-04 19:26:25 +02:00
selimaj-dev df34c72c97 Add tuple type variable decleration 2026-07-04 19:23:10 +02:00
selimaj-dev 517a2e5a2b Var decl with repeat 2026-07-04 09:55:23 +02:00
selimaj-dev eeac773c06 Removed duped module declerations 2026-07-04 09:40:04 +02:00
selimaj-dev 4f3966d8d8 Allman struct and enum field style 2026-07-04 09:38:13 +02:00
selimaj-dev 409301b3d6 Allman struct and enum field style 2026-07-04 09:16:13 +02:00
selimaj-dev 223bafaad7 Merge pull request #107 from mist-go/fix-class-initializers
Fix default initializers in classes
2026-07-04 09:05:27 +02:00
selimaj-dev 603ce1eb1e Fix default initializers in classes 2026-07-04 09:03:52 +02:00
39 changed files with 1107 additions and 201 deletions
Generated
+5 -5
View File
@@ -476,7 +476,7 @@ dependencies = [
[[package]]
name = "mist-analyzer"
version = "0.3.8-alpha.0"
version = "0.4.0"
dependencies = [
"cargo_metadata",
"dashmap 6.1.0",
@@ -495,7 +495,7 @@ dependencies = [
[[package]]
name = "mist-api"
version = "0.3.8-alpha.0"
version = "0.4.0"
dependencies = [
"cargo_metadata",
"mist-codegen",
@@ -507,7 +507,7 @@ dependencies = [
[[package]]
name = "mist-codegen"
version = "0.3.8-alpha.0"
version = "0.4.0"
dependencies = [
"bytecount",
"mist-parser",
@@ -515,7 +515,7 @@ dependencies = [
[[package]]
name = "mist-lang"
version = "0.3.8-alpha.0"
version = "0.4.0"
dependencies = [
"mist-analyzer",
"mist-api",
@@ -524,7 +524,7 @@ dependencies = [
[[package]]
name = "mist-parser"
version = "0.3.8-alpha.0"
version = "0.4.0"
dependencies = [
"pest",
"pest_derive",
+5 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "mist-lang"
version = "0.3.8-alpha.0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language compiler"
license = "Apache-2.0"
@@ -33,10 +33,10 @@ exclude = [
]
[workspace.dependencies]
mist-parser = { path = "crates/parser", version = "0.3.8-alpha.0" }
mist-analyzer = { path = "crates/analyzer", version = "0.3.8-alpha.0" }
mist-codegen = { path = "crates/codegen", version = "0.3.8-alpha.0" }
mist-api = { path = "crates/mist-api", version = "0.3.8-alpha.0" }
mist-parser = { path = "crates/parser", version = "0.4.0" }
mist-analyzer = { path = "crates/analyzer", version = "0.4.0" }
mist-codegen = { path = "crates/codegen", version = "0.4.0" }
mist-api = { path = "crates/mist-api", version = "0.4.0" }
[[bin]]
name = "mist"
+1 -1
View File
@@ -5,7 +5,7 @@ Originally this readme was part of the Carbon Language project, licensed with Ap
-->
<p align="center">
<a href="https://mist.selimaj.dev">Documentation</a>
<a href="https://mist.selimaj.dev/docs">Documentation</a> ∙ <a href="https://mist.selimaj.dev/blog">Blog</a> ∙ <a href="https://mist.selimaj.dev/faq">FAQ</a>
</p>
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mist-analyzer"
version = "0.3.8-alpha.0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language Analyzer LSP"
license = "Apache-2.0"
+231 -33
View File
@@ -21,12 +21,13 @@ use tower_lsp::{Client, LanguageServer, LspService, Server};
use crate::rust_analyzer::RustAnalyzer;
use crate::transpiler::{
TranspileError, TranspiledFile, format_mist, transpile_mist, transpile_mist_no_sem,
TranspileError, TranspiledFile, format_mist, resolve_rust_path, transpile_mist,
transpile_mist_no_sem,
};
static MARKER_COUNTER: AtomicU64 = AtomicU64::new(0);
const KEYWORDS: [&'static str; 22] = [
const KEYWORDS: [&'static str; 23] = [
"if",
"else",
"for",
@@ -49,6 +50,7 @@ const KEYWORDS: [&'static str; 22] = [
"override",
"module ",
"void ",
"virtual ",
];
fn keyword_completion_items() -> impl Iterator<Item = CompletionItem> {
@@ -92,7 +94,7 @@ fn clean_lsp_url(path: &std::path::Path) -> Option<Url> {
}
fn lsp_pos_to_rust_map(pos: &Position) -> RustMap {
RustMap(pos.line as usize + 1, pos.character as usize)
RustMap(pos.line as usize, pos.character as usize)
}
fn mist_map_to_lsp_pos(map: &MistMap) -> Position {
@@ -187,6 +189,10 @@ fn find_marker_position(content: &str, marker: &str) -> Option<Position> {
Some(Position { line, character })
}
fn is_mist_file(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()) == Some("mist")
}
fn mist_to_rust_path(mist_path: &Path) -> PathBuf {
let mut path = mist_path.to_path_buf();
path.set_extension("rs");
@@ -390,11 +396,14 @@ impl Backend {
// Fallback: the source has a syntax error that prevents transpilation.
// Use the last known working Rust content + mapping to inject the
// marker at the nearest valid Rust position.
let mist_target = MistMap(line as usize + 1, character as usize);
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
rust_path.set_file_name("mod.rs");
}
let mist_target = MistMap(line as usize, character as usize);
let source_for_path = self
.documents
.lock()
.await
.get(mist_path)
.map(|r| r.to_string());
let rust_path = resolve_rust_path(mist_path, source_for_path.as_deref());
let (last_mapping, last_content, original_version) = {
let map_guard = self.mapping.lock().await;
@@ -416,7 +425,7 @@ impl Backend {
.map(|(rust, _)| *rust);
let (modified_rust, rust_pos) = if let Some(next_rust) = rust_next {
let lsp_line = (next_rust.0 - 1) as u32;
let lsp_line = next_rust.0 as u32;
let lsp_col = next_rust.1 as u32;
let modified = inject_marker_at(&last_content, lsp_line, lsp_col, &marker)?;
let pos = find_marker_position(&modified, &marker)?;
@@ -603,6 +612,55 @@ impl Backend {
None => return,
};
// Prune documents whose source files no longer exist on disk.
// Without this, deleted .mist files linger in the in-memory map
// and compute_mod_decls keeps generating stale pub mod declarations.
// Also clean up stale synthetic package.mist entries and generated
// mod.rs output files for directories with no remaining source children.
{
let mut docs = self.documents.lock().await;
let stale: Vec<PathBuf> = docs.keys().filter(|p| !p.exists()).cloned().collect();
for path in &stale {
let source_for_path = docs.get(path).map(|r| r.to_string());
docs.remove(path);
if path.extension().and_then(|e| e.to_str()) == Some("mist") {
let rust_path = resolve_rust_path(path, source_for_path.as_deref());
let _ = std::fs::remove_file(&rust_path);
let map_path = rust_path.with_extension("map.json");
let _ = std::fs::remove_file(&map_path);
}
}
// Also remove synthetic package.mist entries whose directories
// no longer contain any real .mist source files.
let synthetic: Vec<PathBuf> = docs
.keys()
.filter(|p| {
p.file_name().and_then(|n| n.to_str()) == Some("package.mist") && !p.exists()
})
.cloned()
.collect();
for path in &synthetic {
docs.remove(path);
}
drop(docs);
// Clean up auxiliary state for deleted files
let mut versions = self.doc_versions.lock().await;
let mut contents = self.last_rust_contents.lock().await;
let mut diags = self.previous_diagnostics.lock().await;
let all_stale: Vec<PathBuf> = stale.into_iter().chain(synthetic).collect();
let stale_set: std::collections::HashSet<_> = all_stale.iter().collect();
versions.retain(|k, _| !stale_set.contains(k));
contents.retain(|k, _| !stale_set.contains(k));
for path in &all_stale {
if let Some(uri) = clean_lsp_url(path) {
diags.remove(&uri);
}
}
}
self.ensure_implicit_packages().await;
// Collect sources first to avoid holding locks during transpile
@@ -618,7 +676,11 @@ impl Backend {
let package_mist = read_mist_package(crate_root);
let mod_decls = compute_mod_decls(&docs, &src_root, &package_mist);
for (path, decl) in mod_decls {
if !decl.is_empty() {
// Include files that have mod declarations OR that are
// already known package/directory entries in the doc map.
// The latter case covers parents whose children were
// deleted — they need a regenerated (empty) mod.rs.
if !decl.is_empty() || docs.contains_key(&path) {
if let Some(source) = docs.get(&path) {
result.push((path.clone(), source.to_string(), decl));
}
@@ -1031,6 +1093,18 @@ impl LanguageServer for Backend {
return;
}
};
// Non-.mist files pass through directly to rust-analyzer.
if !is_mist_file(&mist_path) {
let _ = self
.rust_analyzer
.lock()
.await
.did_open(uri, &params.text_document.text)
.await;
return;
}
let source = params.text_document.text;
self.documents
@@ -1053,6 +1127,18 @@ impl LanguageServer for Backend {
}
};
if !is_mist_file(&mist_path) {
if let Some(change) = params.content_changes.into_iter().last() {
let _ = self
.rust_analyzer
.lock()
.await
.did_change(uri, &change.text, params.text_document.version)
.await;
}
return;
}
if let Some(change) = params.content_changes.into_iter().last() {
let source = change.text;
@@ -1085,6 +1171,11 @@ impl LanguageServer for Backend {
.expect("Failed to read file")
};
if !is_mist_file(&mist_path) {
let _ = self.rust_analyzer.lock().await.did_save(uri, &text).await;
return;
}
self.documents
.lock()
.await
@@ -1117,9 +1208,18 @@ impl LanguageServer for Backend {
}
};
if !is_mist_file(&mist_path) {
let _ = self.rust_analyzer.lock().await.did_close(uri).await;
return;
}
let source_for_path = {
let docs = self.documents.lock().await;
docs.get(&mist_path).map(|r| r.to_string())
};
self.documents.lock().await.remove(&mist_path);
let rust_path = mist_to_rust_path(&mist_path);
let rust_path = resolve_rust_path(&mist_path, source_for_path.as_deref());
if let Some(rust_uri) = clean_lsp_url(&rust_path) {
let _ = self.rust_analyzer.lock().await.did_close(rust_uri).await;
@@ -1137,6 +1237,25 @@ impl LanguageServer for Backend {
Ok(p) => p,
Err(_) => return Ok(None),
};
// Non-.mist files pass through directly to rust-analyzer.
if !is_mist_file(&mist_path) {
let result = self
.rust_analyzer
.lock()
.await
.request::<lsp_types::request::Completion>(params)
.await;
return match result {
Ok(r) => Ok(r),
Err(e) => {
eprintln!("completion error (passthrough): {e}");
Ok(None)
}
};
}
let source = match self.documents.lock().await.get(&mist_path) {
Some(r) => r.to_string(),
None => return Ok(None),
@@ -1160,6 +1279,11 @@ impl LanguageServer for Backend {
return Ok(None);
};
let trigger_char: Option<String> = params
.context
.as_ref()
.and_then(|c| c.trigger_character.clone());
let comp_params = CompletionParams {
text_document_position: TextDocumentPositionParams {
text_document: TextDocumentIdentifier { uri: rust_uri },
@@ -1187,13 +1311,13 @@ impl LanguageServer for Backend {
match completion_result {
Ok(Some(CompletionResponse::Array(mut items))) => {
mist_ify_completions(&source, &mist_pos, &mut items);
mist_ify_completions(&source, &mist_pos, &mut items, trigger_char.as_deref());
Ok(Some(CompletionResponse::Array(items)))
}
Ok(Some(CompletionResponse::List(mut list))) => {
mist_ify_completions(&source, &mist_pos, &mut list.items);
mist_ify_completions(&source, &mist_pos, &mut list.items, trigger_char.as_deref());
Ok(Some(CompletionResponse::List(list)))
}
@@ -1209,7 +1333,7 @@ impl LanguageServer for Backend {
&self,
params: GotoDefinitionParams,
) -> tower_lsp::jsonrpc::Result<Option<GotoDefinitionResponse>> {
let mist_uri = params.text_document_position_params.text_document.uri;
let mist_uri = &params.text_document_position_params.text_document.uri;
let mist_pos = params.text_document_position_params.position;
eprintln!(
"[goto_definition] entered at mist ({}, {})",
@@ -1220,6 +1344,25 @@ impl LanguageServer for Backend {
Ok(p) => p,
Err(_) => return Ok(None),
};
// Non-.mist files pass through directly to rust-analyzer.
if !is_mist_file(&mist_path) {
let result = self
.rust_analyzer
.lock()
.await
.request::<lsp_types::request::GotoDefinition>(params)
.await;
return match result {
Ok(r) => Ok(r),
Err(e) => {
eprintln!("goto_definition error (passthrough): {e}");
Ok(None)
}
};
}
let source = match self.documents.lock().await.get(&mist_path) {
Some(r) => r.to_string(),
None => return Ok(None),
@@ -1389,13 +1532,32 @@ impl LanguageServer for Backend {
}
async fn hover(&self, params: HoverParams) -> tower_lsp::jsonrpc::Result<Option<Hover>> {
let mist_uri = params.text_document_position_params.text_document.uri;
let mist_uri = &params.text_document_position_params.text_document.uri;
let mist_pos = params.text_document_position_params.position;
let mist_path = match mist_uri.to_file_path() {
Ok(p) => p,
Err(_) => return Ok(None),
};
// Non-.mist files pass through directly to rust-analyzer.
if !is_mist_file(&mist_path) {
let result = self
.rust_analyzer
.lock()
.await
.request::<lsp_types::request::HoverRequest>(params)
.await;
return match result {
Ok(r) => Ok(r),
Err(e) => {
eprintln!("hover error (passthrough): {e}");
Ok(None)
}
};
}
let source = match self.documents.lock().await.get(&mist_path) {
Some(r) => r.to_string(),
None => return Ok(None),
@@ -1459,6 +1621,24 @@ impl LanguageServer for Backend {
.to_file_path()
.map_err(|_| tower_lsp::jsonrpc::Error::internal_error())?;
// Non-.mist files pass through directly to rust-analyzer.
if !is_mist_file(&mist_path) {
let result = self
.rust_analyzer
.lock()
.await
.request::<lsp_types::request::Formatting>(params)
.await;
return match result {
Ok(r) => Ok(r),
Err(e) => {
eprintln!("formatting error (passthrough): {e}");
Ok(None)
}
};
}
let docs = self.documents.lock().await;
let old_text = docs
@@ -1488,10 +1668,13 @@ impl LanguageServer for Backend {
}
}
fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<CompletionItem>) {
let existing: HashSet<String> = items.iter().map(|item| item.label.clone()).collect();
items.extend(keyword_completion_items().filter(|item| !existing.contains(&item.label)));
fn mist_ify_completions(
source: &str,
pos: &Position,
items: &mut Vec<CompletionItem>,
trigger_char: Option<&str>,
) {
let is_scoping_trigger = matches!(trigger_char, Some("." | ":"));
for item in items.iter_mut() {
item.text_edit = None;
@@ -1503,6 +1686,14 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
}
}
if is_scoping_trigger {
return;
}
let existing: HashSet<String> = items.iter().map(|item| item.label.clone()).collect();
items.extend(keyword_completion_items().filter(|item| !existing.contains(&item.label)));
let curr_scope = current_scope(&source, pos.line, pos.character);
// =========================
@@ -1630,11 +1821,11 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
// Struct/Class
// =========================
if matches!(curr_scope, Scope::Struct) {
if matches!(curr_scope, Scope::Class) {
items.push(CompletionItem {
label: "field".into(),
label: "virtual".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("$1 $2,".into()),
insert_text: Some("pub virtual $1 $2()\n{\n\t$3\n}".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
@@ -1642,9 +1833,19 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
});
items.push(CompletionItem {
label: "pub field".into(),
label: "override".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("pub $1 $2,".into()),
insert_text: Some("$1 $2() override$3\n{\n\t$4\n}".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
..Default::default()
});
items.push(CompletionItem {
label: "virtual override".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("pub virtual $1 $2() override$3\n{\n\t$4\n}".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
@@ -1652,7 +1853,7 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
});
}
if matches!(curr_scope, Scope::Class) {
if matches!(curr_scope, Scope::Class | Scope::Struct) {
items.push(CompletionItem {
label: "field".into(),
kind: Some(CompletionItemKind::SNIPPET),
@@ -1682,7 +1883,7 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
items.push(CompletionItem {
label: "variant".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("$1,".into()),
insert_text: Some("$1;".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
@@ -1692,7 +1893,7 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
items.push(CompletionItem {
label: "tuple variant".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("$1($2),".into()),
insert_text: Some("$1($2);".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
@@ -1702,7 +1903,7 @@ fn mist_ify_completions(source: &str, pos: &Position, items: &mut Vec<Completion
items.push(CompletionItem {
label: "struct variant".into(),
kind: Some(CompletionItemKind::SNIPPET),
insert_text: Some("$1\n{\n\t$0\n},".into()),
insert_text: Some("$1\n{\n\t$0\n};".into()),
insert_text_format: Some(InsertTextFormat::SNIPPET),
sort_text: Some("0000".into()),
preselect: Some(true),
@@ -1857,7 +2058,7 @@ async fn handle_ra_notifications(
character: if mist_end_pos.line == mist_start_pos.line {
mist_end_pos.character.max(mist_start_pos.character + 1)
} else {
mist_end_pos.character.max(1)
mist_end_pos.character.max(0)
},
};
@@ -2024,10 +2225,7 @@ fn compute_mod_decls(
let source = rope.to_string();
parse_module(&source).ok().flatten().map(|(_, name)| name.0)
})
.or_else(|| {
file.file_stem()
.and_then(|s| s.to_str().map(String::from))
});
.or_else(|| file.file_stem().and_then(|s| s.to_str().map(String::from)));
if let Some(name) = mod_name {
mod_decl.push_str(&format!("pub mod {};\n", name));
}
+34 -15
View File
@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use mist_codegen::RustCodegen;
use mist_parser::rev_mapper::Mapping;
use mist_parser::{MistFmtConfig, parse};
use mist_parser::{MistFmtConfig, parse, parse_module};
pub struct TranspiledFile {
pub mist_path: PathBuf,
@@ -17,18 +17,43 @@ pub enum TranspileError<'a> {
Semantic(Vec<mist_parser::semantics::SemanticError>),
}
/// Resolve the output `.rs` path for a `.mist` source file.
///
/// Always checks for a `pub module x;` declaration via `parse_module` and
/// uses the declared module name as the filename when present. Falls back
/// to the literal file stem when parsing fails or the file has no module
/// declaration.
pub fn resolve_rust_path(mist_path: &Path, source: Option<&str>) -> PathBuf {
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
// Package files (package.mist) must output as <dir>/mod.rs so the Rust
// module hierarchy resolves correctly.
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
rust_path.set_file_name("mod.rs");
} else if let Some(src) = source {
// Prioritize the module declaration from the source over the file stem.
// Every caller re-parses so we always pick up the current declaration.
if let Ok(Some((_, ref name))) = parse_module(src) {
if rust_path.file_name().map(|v| v.to_str()).unwrap_or_default() != Some("mod.rs") {
if let Some(ext) = rust_path.extension().map(|e| e.to_owned()) {
let mut new_name = std::ffi::OsString::from(&name.0);
new_name.push(".");
new_name.push(ext);
rust_path.set_file_name(new_name);
} else {
rust_path.set_file_name(&name.0);
}
}
}
}
rust_path
}
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 rust_path = resolve_rust_path(mist_path, Some(source));
let parsed = parse(source).map_err(TranspileError::Parse)?;
@@ -58,13 +83,7 @@ pub fn transpile_mist_no_sem(
source: &str,
extra_mod_decl: &str,
) -> Result<TranspiledFile, String> {
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
// Package files (package.mist) must output as <dir>/mod.rs so the Rust module
// hierarchy resolves correctly (pub mod <child>; declarations look for sibling
// .rs files, and the parent module declaration looks for <dir>/mod.rs).
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
rust_path.set_file_name("mod.rs");
}
let rust_path = resolve_rust_path(mist_path, Some(source));
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mist-codegen"
version = "0.3.8-alpha.0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language Rust code generator"
license = "Apache-2.0"
+32 -22
View File
@@ -16,7 +16,7 @@ pub struct ClassProcessedData {
items: Vec<ClassItem>,
methods: Vec<Spanned<FunctionDecl>>,
v_table: Vec<Identifier>,
override_v_table: HashMap<Override, Spanned<Vec<Identifier>>>,
override_v_table: HashMap<Override, Spanned<Vec<(Identifier, bool)>>>,
}
impl ClassProcessedData {
@@ -45,13 +45,13 @@ impl ClassProcessedData {
.collect::<Vec<Spanned<FunctionDecl>>>();
let mut v_table = Vec::new();
let mut override_v_table = std::collections::HashMap::new();
let mut override_v_table = HashMap::new();
for method in &methods {
if matches!(method.item.visibility, Visibility::Public) {
match &method.item.is_override {
None => {
if method.item.self_param.is_some() {
if method.item.is_virtual && method.item.self_param.is_some() {
v_table.push(method.item.name.clone());
}
}
@@ -64,7 +64,7 @@ impl ClassProcessedData {
item: Vec::new(),
})
.item
.push(method.item.name.clone());
.push((method.item.name.clone(), method.item.is_virtual));
}
}
}
@@ -113,7 +113,7 @@ impl ClassProcessedData {
cg.add(&get_type_from_path(inherits).get_rust());
cg.addln(",");
} else {
cg.add_indentedln("pub _vptr: &'static [*const std::ffi::c_void],");
cg.add_indentedln("pub _vptr: &'static [*const core::ffi::c_void],");
}
for field in &self.fields {
@@ -174,11 +174,11 @@ impl ClassProcessedData {
self.v_table.len()
));
cg.add_indentedln("pub const __V_TABLE: &'static [*const std::ffi::c_void] = &{");
cg.add_indentedln("pub const __V_TABLE: &'static [*const core::ffi::c_void] = &{");
cg.indent += 1;
if has_parent {
cg.add_indentedln("let mut table = [std::ptr::null(); Self::__V_COUNT];");
cg.add_indentedln("let mut table = [core::ptr::null(); Self::__V_COUNT];");
cg.add_indentedln(&format!("let parent_table = {}::__V_TABLE;", parent_path));
cg.add_indentedln(
@@ -191,20 +191,20 @@ impl ClassProcessedData {
.as_ref()
.unwrap_or(self.inherits.as_ref().unwrap())
.get_rust();
for method_ident in &overriden_method_idents.item {
for (method_ident, is_virtual) in &overriden_method_idents.item {
cg.add_indentedln(&format!(
"table[{}::__FN_{}] = {}::__m_{} as *const std::ffi::c_void;",
"table[{}::__FN_{}] = {}::{} as *const core::ffi::c_void;",
base_class_path,
method_ident.0.to_uppercase(),
self.self_path.get_rust(),
method_ident.get_rust()
get_virtual_name(method_ident, *is_virtual)
));
}
}
for method_name in &self.v_table {
cg.add_indentedln(&format!(
"table[Self::__FN_{}] = Self::__m_{} as *const std::ffi::c_void;",
"table[Self::__FN_{}] = Self::__m_{} as *const core::ffi::c_void;",
method_name.0.to_uppercase(),
method_name.get_rust()
));
@@ -216,7 +216,7 @@ impl ClassProcessedData {
cg.indent += 1;
for method_name in &self.v_table {
cg.add_indentedln(&format!(
"Self::__m_{} as *const std::ffi::c_void,",
"Self::__m_{} as *const core::ffi::c_void,",
method_name.get_rust()
));
}
@@ -293,7 +293,7 @@ impl ClassProcessedData {
// Deref tests for override targets
if self.inherits.is_some() && !self.override_v_table.is_empty() {
cg.add_indentedln("let this: &Self = &unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
cg.add_indentedln("let this: &Self = &unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
for (override_tier, v) in &self.override_v_table {
if let Some(path) = &override_tier.0 {
@@ -346,14 +346,15 @@ impl ClassProcessedData {
cg.addln(") -> Self {");
cg.indent += 1;
cg.add_indentedln("let mut this: Self = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
cg.add_indentedln("let mut this: Self = unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
for field in &self.fields {
if let Some(init) = &field.item.init {
field.gen_span(cg);
cg.add_indentedln(&format!("this.{} = ", field.item.decl.name.get_rust()));
cg.add_indented(&format!("this.{} = ", field.item.decl.name.get_rust()));
init.gen_rust(ctx, cg);
cg.addln(";");
}
}
@@ -379,6 +380,7 @@ impl ClassProcessedData {
column: constructor.column,
item: FunctionDecl {
visibility: constructor.item.visibility.clone(),
is_virtual: false,
is_override: None,
name: Identifier(String::from("constructor")),
generics: constructor.item.generics.clone(),
@@ -395,7 +397,7 @@ impl ClassProcessedData {
for method in &self.methods {
match method.item.visibility {
Visibility::Public => {
if method.item.self_param.is_some() {
if method.item.is_virtual && method.item.self_param.is_some() {
if method.item.is_override.is_none() {
gen_method_point(&method.item, ctx, cg);
}
@@ -431,7 +433,7 @@ impl ClassProcessedData {
let generics_expr_str = Generics::from(self.generics.clone()).get_rust();
cg.add(&format!(
"impl{} std::ops::Deref for {}{}",
"impl{} core::ops::Deref for {}{}",
generics_str,
self.name.get_rust(),
generics_expr_str
@@ -450,7 +452,7 @@ impl ClassProcessedData {
cg.addln("}");
cg.add(&format!(
"impl{} std::ops::DerefMut for {}{}",
"impl{} core::ops::DerefMut for {}{}",
generics_str,
self.name.get_rust(),
generics_expr_str
@@ -578,7 +580,7 @@ pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustC
mutable: mutable_self,
ty: Box::new(TypeExpr::Path(
Path(vec![
Identifier(String::from("std")),
Identifier(String::from("core")),
Identifier(String::from("ffi")),
Identifier(String::from("c_void")),
]),
@@ -588,12 +590,12 @@ 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);");
cg.addln(" = core::mem::transmute(func_ptr);");
if mutable_self {
cg.add_indented("func(self as *mut Self as *const std::ffi::c_void");
cg.add_indented("func(self as *mut Self as *mut core::ffi::c_void");
} else {
cg.add_indented("func(self as *const Self as *const std::ffi::c_void");
cg.add_indented("func(self as *const Self as *const core::ffi::c_void");
}
for (_, param) in &params {
@@ -616,3 +618,11 @@ pub fn get_type_from_path(path: &ExprPath) -> TypeExpr {
path.0.last().unwrap().generics.clone(),
)
}
pub fn get_virtual_name(name: &Identifier, is_virtual: bool) -> String {
if is_virtual {
format!("__m_{}", name.get_rust())
} else {
name.get_rust()
}
}
+51 -7
View File
@@ -3,7 +3,7 @@ pub mod expr;
pub mod statement;
pub mod top_level;
use std::path::PathBuf;
use std::{collections::HashMap, path::PathBuf};
use mist_parser::{
ast::*,
@@ -26,9 +26,15 @@ pub trait GetRust {
}
}
pub enum Include {
Glob(Path),
Use(Visibility, Path),
}
pub struct RustCodegen {
output: String,
indent: usize,
pub crates: HashMap<Identifier, Vec<Include>>,
pub mapping: Mapping,
position: RustMap,
}
@@ -38,8 +44,9 @@ impl RustCodegen {
Self {
output: String::new(),
indent: 0,
crates: HashMap::new(),
mapping: Mapping::new(mist_path),
position: RustMap(1, 0),
position: RustMap(0, 0),
}
}
@@ -78,14 +85,45 @@ impl RustCodegen {
}
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
let mut ctx = Context {
expr_super: None,
};
let mut ctx = Context { expr_super: None };
for tl in toplevels {
tl.gen_rust(&mut ctx, self);
}
let mut crates = HashMap::new();
std::mem::swap(&mut self.crates, &mut crates);
for (c, items) in crates {
self.add("mod ");
c.gen_rust(&mut ctx, self);
self.addln(" {");
self.indent += 1;
self.add_indented("extern crate ");
c.gen_rust(&mut ctx, self);
self.addln(";");
for item in items {
self.add_indentedln("#[doc(inline)]");
self.add_indented("pub use ");
match item {
Include::Glob(item) => {
item.gen_rust(&mut ctx, self);
self.add("::*");
}
Include::Use(vis, item) => {
vis.gen_rust(&mut ctx, self);
item.gen_rust(&mut ctx, self);
}
}
self.addln(";");
}
self.indent -= 1;
self.addln("}");
}
self.output.clone()
}
@@ -148,7 +186,7 @@ impl<T> GenSpanTranslation for Spanned<T> {
fn gen_span(&self, cg: &mut RustCodegen) {
cg.mapping
.map
.insert((cg.position, MistMap(self.line, self.column)));
.insert((cg.position, MistMap(self.line, self.column - 1)));
}
}
@@ -201,7 +239,6 @@ impl GetRust for TypeExpr {
path.get_rust()
}
}
Self::Lifetime(name) => format!("'{}", name.get_rust()),
Self::Tuple(types) => format!(
"({})",
types
@@ -275,6 +312,13 @@ impl GetRust for TypeExpr {
return_type.get_rust(),
)
}
Self::Array(ty, count) => {
if let Some(count) = count {
format!("[{}; {count}]", ty.get_rust())
} else {
format!("[{}]", ty.get_rust())
}
}
}
}
}
+35 -8
View File
@@ -188,14 +188,41 @@ impl GenRust for Statement {
impl GenRust for VarDecl {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
self.name.gen_rust(ctx, cg);
if self.tuple_names.is_empty() {
self.name.gen_rust(ctx, cg);
} else {
cg.add("(");
self.name.gen_rust(ctx, cg);
for name in &self.tuple_names {
cg.add(", ");
name.gen_rust(ctx, cg);
}
cg.add(")");
}
cg.add(
&self
.type_
.as_ref()
.map(|t| format!(": {}", t.get_rust()))
.unwrap_or_default(),
);
if self.true_type {
cg.add(
&self
.type_
.as_ref()
.map(|t| format!(": {}", t.get_rust()))
.unwrap_or_default(),
);
} else {
cg.add(
&self
.type_
.as_ref()
.map(|t| {
let t = vec![t.get_rust(); self.tuple_names.len() + 1];
if self.tuple_names.is_empty() {
format!(": {}", t.join(", "))
} else {
format!(": ({})", t.join(", "))
}
})
.unwrap_or_default(),
);
}
}
}
+60 -2
View File
@@ -24,7 +24,21 @@ impl GetRust for GenericsDecl {
impl GetRust for GenericDecl {
fn get_rust(&self) -> String {
match self {
GenericDecl::Lifetime(name) => format!("'{}", name.get_rust()),
GenericDecl::Lifetime(name, requirements) => {
format!("'{}", name.get_rust())
+ &(if requirements.len() != 0 {
format!(
": {}",
requirements
.into_iter()
.map(GetRust::get_rust)
.collect::<Vec<_>>()
.join("+")
)
} else {
String::new()
})
}
GenericDecl::Type(name, requirements) => {
name.get_rust()
+ &(if requirements.len() != 0 {
@@ -32,7 +46,7 @@ impl GetRust for GenericDecl {
": {}",
requirements
.into_iter()
.map(TypeExpr::get_rust)
.map(GetRust::get_rust)
.collect::<Vec<_>>()
.join("+")
)
@@ -252,6 +266,33 @@ impl GenRust for TopLevelKind {
cg.indent -= 1;
cg.addln("}\n");
}
Self::StructDeclTupleUnit {
visibility,
name,
generics,
unit,
} => {
cg.addln(&format!(
"{}struct {}{}",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
if let Some(unit) = unit {
cg.add(" (");
for unit in unit {
cg.add_indented("");
unit.gen_rust(ctx, cg);
cg.add(", ");
}
cg.add(")");
}
cg.indent -= 1;
cg.addln(";\n");
}
Self::EnumDecl {
visibility,
name,
@@ -326,6 +367,23 @@ impl GenRust for TopLevelKind {
constructor,
items,
),
Self::IncludeGlobal(incl) => {
cg.crates
.entry(incl.0[0].clone())
.or_insert(Vec::new())
.push(crate::Include::Glob(incl.clone()));
}
Self::IncludeUse(vis, incl) => {
cg.crates
.entry(incl.0[0].clone())
.or_insert(Vec::new())
.push(crate::Include::Use(vis.clone(), incl.clone()));
}
Self::IncludeLocal(path) => {
cg.add("include!(\"");
cg.add(&path.replace(".mist", ".rs"));
cg.add("\");");
}
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mist-api"
version = "0.3.8-alpha.0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language module system"
license = "Apache-2.0"
+38 -30
View File
@@ -19,19 +19,19 @@ use mist_parser::rev_mapper;
#[derive(Debug, Clone)]
pub struct MistDiagnosticMessage
{
pub String message,
pub PathBuf file_path,
pub String file_name,
pub usize line,
pub usize column,
pub String message;
pub PathBuf file_path;
pub String file_name;
pub usize line;
pub usize column;
}
#[derive(Debug, Clone)]
pub enum MistDiagnostic
{
Error(MistDiagnosticMessage),
Warning(MistDiagnosticMessage),
Rust(CompilerMessage),
Error(MistDiagnosticMessage);
Warning(MistDiagnosticMessage);
Rust(CompilerMessage);
}
pub bool build(Vec<String> mut args, PathBuf root)
@@ -58,28 +58,36 @@ pub bool build(Vec<String> mut args, PathBuf root)
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
});
let mist_file = map.mist_path.strip_prefix(&root);
let (_, rev_mapper::MistMap(line, column)) = map.find(&rev_mapper::RustMap(span.line_end, span.column_start)).unwrap_or_default();
let mist_msg = MistDiagnosticMessage {
message: format!("{}: {}",
msg.message.message,
span.label.clone().unwrap_or_default()),
file_name: if let Ok(mist_file) = mist_file {
mist_file.to_string_lossy().to_string()
} else {
map.mist_path.to_string_lossy().to_string()
},
file_path: map.mist_path.clone(),
line: line,
column: column,
};
match msg.message.level {
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
diagnostics.push(MistDiagnostic::Error(mist_msg))
let rust_lookup = rev_mapper::RustMap(span.line_end - 1, span.column_start - 1);
match map.find(&rust_lookup) {
Some((_, rev_mapper::MistMap(line, column))) => {
let mist_msg = MistDiagnosticMessage {
message: format!("{}: {}",
msg.message.message,
span.label.clone().unwrap_or_default()),
file_name: if let Ok(mist_file) = mist_file {
mist_file.to_string_lossy().to_string()
} else {
map.mist_path.to_string_lossy().to_string()
},
file_path: map.mist_path.clone(),
line: line,
column: column,
};
match msg.message.level {
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
diagnostics.push(MistDiagnostic::Error(mist_msg))
}
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
diagnostics.push(MistDiagnostic::Warning(mist_msg))
}
_ => {
}
}
}
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
diagnostics.push(MistDiagnostic::Warning(mist_msg))
}
_ => {
None => {
diagnostics.push(MistDiagnostic::Rust(msg));
break;
}
}
}
@@ -135,5 +143,5 @@ pub Option<String> get_line(HashMap<PathBuf, Vec<String>> mut& files, MistDiagno
let lines = files.entry(src_path.clone()).or_insert_with(() => {
fs::read_to_string(src_path).expect("Unable to read mist file").lines().into_iter().map(String::from).collect()
});
lines.get(msg.line - 1).map((v) => v.trim().to_string())
lines.get(msg.line.saturating_sub(1)).map((v) => v.trim().to_string())
}
+8 -7
View File
@@ -22,10 +22,10 @@ use serde::Deserialize;
#[serde(default)]
pub struct MistConfig
{
pub PathBuf package,
pub Vec<PathBuf> packages,
pub Vec<PathBuf> include,
pub mist_parser::MistFmtConfig fmt,
pub PathBuf package;
pub Vec<PathBuf> packages;
pub Vec<PathBuf> include;
pub mist_parser::MistFmtConfig fmt;
}
impl MistConfig
@@ -77,6 +77,7 @@ pub void transpile(Path& root)
let elapsed = start.elapsed();
println!("\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m", elapsed);
for incl in &config.include {
let incl = if incl.is_relative() { root.join(incl) } else { incl.clone() };
if ends_with_star(&incl) {
let sub_crates = incl.parent().expect("Failed to get parent");
let entries = match fs::read_dir(sub_crates) {
@@ -95,7 +96,7 @@ pub void transpile(Path& root)
}
}
} else {
transpile(incl);
transpile(&incl);
}
}
}
@@ -209,8 +210,8 @@ std::io::Result<bool> is_source_newer(Path& source, Path& output)
pub enum TranspileError<'a>
{
Parse(error::ParseError<'a>),
Semantic(Vec<mist_parser::semantics::SemanticError>),
Parse(error::ParseError<'a>);
Semantic(Vec<mist_parser::semantics::SemanticError>);
}
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)
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mist-parser"
version = "0.3.8-alpha.0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language parser"
license = "Apache-2.0"
+2 -2
View File
@@ -41,13 +41,13 @@ pub enum TypeExpr {
Path(Path, Option<Generics>),
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
Tuple(Vec<TypeExpr>),
Lifetime(Identifier),
Void,
Fn {
kind: FnKind,
return_type: Box<TypeExpr>,
params: Vec<TypeExpr>,
},
Array(Box<TypeExpr>, Option<isize>)
}
#[derive(Debug, Clone, Serialize)]
@@ -60,7 +60,7 @@ pub struct Spanned<T> {
impl From<GenericDecl> for Generic {
fn from(value: GenericDecl) -> Self {
match value {
GenericDecl::Lifetime(life) => Generic::Lifetime(life),
GenericDecl::Lifetime(life, _) => Generic::Lifetime(life),
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
}
}
+3 -1
View File
@@ -44,8 +44,10 @@ pub struct MatchItem(pub Vec<Pattern>, pub Expression);
#[derive(Debug, Clone, Serialize)]
pub struct VarDecl {
pub name: Pattern,
pub type_: Option<TypeExpr>,
pub name: Pattern,
pub true_type: bool,
pub tuple_names: Vec<Pattern>,
}
#[derive(Debug, Clone, Serialize)]
+14 -4
View File
@@ -28,6 +28,9 @@ pub struct TopLevel(pub Spanned<TopLevelKind>, pub Vec<Attribute>);
pub enum TopLevelKind {
ModAttribute,
Import(Visibility, Path),
IncludeGlobal(Path),
IncludeUse(Visibility, Path),
IncludeLocal(String),
DeclareModule(Visibility, Identifier),
ImplDecl(ImplDecl),
StaticDecl(VarDeclStmt),
@@ -56,6 +59,12 @@ pub enum TopLevelKind {
generics: GenericsDecl,
fields: Vec<Spanned<FieldDecl>>,
},
StructDeclTupleUnit {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
unit: Option<Vec<Spanned<TypeExpr>>>,
},
FunctionDecl(FunctionDecl),
ClassDecl {
visibility: Visibility,
@@ -79,8 +88,8 @@ pub struct GenericsDecl(pub Vec<GenericDecl>);
#[derive(Debug, Clone, Serialize)]
pub enum GenericDecl {
Lifetime(Identifier),
Type(Identifier, Vec<TypeExpr>),
Lifetime(Identifier, Vec<Generic>),
Type(Identifier, Vec<Generic>),
}
#[derive(Debug, Clone, Serialize)]
@@ -104,12 +113,13 @@ pub struct Override(pub Option<ExprPath>);
#[derive(Debug, Clone, Serialize)]
pub struct FunctionDecl {
pub visibility: Visibility,
pub is_override: Option<Override>,
pub is_virtual: bool,
pub return_type: Option<TypeExpr>,
pub name: Identifier,
pub generics: GenericsDecl,
pub self_param: Option<(bool, Option<Identifier>, bool)>,
pub params: ParamList,
pub return_type: Option<TypeExpr>,
pub is_override: Option<Override>,
pub body: Option<Block>,
}
+1
View File
@@ -24,6 +24,7 @@ pub enum ErrorCode {
InvalidStatement,
AstGenBug,
Module,
NumberParse,
}
impl From<pest::error::Error<Rule>> for ParseError<'_> {
+36 -14
View File
@@ -36,6 +36,7 @@ keyword = {
| "override"
| "const"
| "type"
| "virtual"
}
identifier = @{
@@ -89,7 +90,7 @@ mutable = { "mut" }
// ======================================================
// GENERICS
// ======================================================
generic_decl = { lifetime | (identifier ~ (":" ~ generic ~ ("+" ~ generic)*)?) }
generic_decl = { (lifetime | identifier) ~ (":" ~ generic ~ ("+" ~ generic)*)? }
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
generic = { lifetime | type_expr }
@@ -124,9 +125,9 @@ fn_kind_mut = { "FnMut" }
fn_kind = _{
fn_kind_fn
| fn_kind_unsafe
| fn_kind_closure
| fn_kind_once
| fn_kind_mut
| fn_kind_closure
}
fn_type = {
@@ -141,8 +142,12 @@ void_type = {
"void"
}
array_type = {
"[" ~ integer? ~ "]"
}
type_expr = {
(void_type | path_type | tuple_type | dyn_type) ~ (unsafe_ref_type | ref_type | fn_type)*
(void_type | path_type | tuple_type | dyn_type) ~ (unsafe_ref_type | ref_type | fn_type | array_type)*
}
lifetime = {
@@ -225,9 +230,12 @@ attributes = {
// ======================================================
// DECLARATION HELPERS
// ======================================================
as_kw = { "as" }
var_decl = {
("let" ~ pattern)
| type_expr ~ (!tuple_pattern ~ pattern)
("let" ~ pattern ~ ("," ~ pattern)*)
| (type_expr ~ as_kw ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)+))
| (type_expr ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)*))
}
field = {
@@ -240,7 +248,7 @@ param = {
}
field_list = {
(field ~ ("," ~ field)* ~ ","?)?
(field ~ ";")*
}
param_list = {
@@ -251,6 +259,18 @@ param_list = {
// IMPORTS / MODULES
// ======================================================
include_global = {
"#" ~ "include" ~ "<" ~ identifier ~ ("/" ~ identifier)* ~ ">"
}
include_use_global = {
visibility? ~ "#" ~ "use" ~ static_path ~ semicolon
}
include_local = {
"#" ~ "include" ~ string_lit
}
import = {
visibility? ~ "use" ~ static_path ~ semicolon
}
@@ -264,7 +284,11 @@ declare_module = {
// ======================================================
struct_decl = {
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ "{" ~ field_list? ~ "}"
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ "{" ~ field_list ~ "}"
}
tuple_struct_decl = {
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ tuple_type? ~ ";"
}
// ======================================================
@@ -289,12 +313,8 @@ enum_field = _{
| enum_named
}
enum_fields = _{
enum_field ~ ("," ~ enum_field)* ~ ","?
}
enum_decl = {
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ enum_fields? ~ "}"
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ (enum_field ~ ";")* ~ "}"
}
// ======================================================
@@ -358,10 +378,12 @@ trait_decl = {
// FUNCTIONS
// ======================================================
virtual_kw = { "virtual" }
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
function_decl = {
visibility? ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
visibility? ~ virtual_kw? ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
}
// ======================================================
@@ -381,7 +403,7 @@ type_alias = { "type" ~ identifier ~ generics_decl? ~ "=" ~ type_expr ~ ";" }
top_level = {
mod_attribute
| (attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | declare_module | function_decl | const_decl | static_decl | type_alias))
| (attributes ~ (include_global | include_local | include_use_global | import | impl_for_decl | impl_decl | trait_decl | struct_decl | tuple_struct_decl | enum_decl | class_decl | declare_module | function_decl | const_decl | static_decl | type_alias))
}
// ======================================================
+3 -1
View File
@@ -2,7 +2,7 @@ use crate::{
Rule,
ast::*,
error::{AstError, collect_recovered},
parser::consume_rule,
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
@@ -55,7 +55,9 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
type_: consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose()?,
true_type: listen_rule(&mut inner, Rule::as_kw),
name: Pattern::try_from(inner.next().unwrap())?,
tuple_names: collect_recovered(inner)?,
})
}
+20 -1
View File
@@ -50,13 +50,31 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
};
}
Rule::array_type => {
ty = TypeExpr::Array(
Box::new(ty),
ref_inner
.next()
.map(|v| {
v.as_str().parse().map_err(|_| AstError {
span: v.as_span(),
error_code: crate::error::ErrorCode::NumberParse,
error_message: format!(
"Number exceeds isize limits: {}",
v.as_str()
),
})
})
.transpose()?,
)
}
_ => 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)?)),
@@ -113,6 +131,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericDecl {
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
Ok(GenericDecl::Lifetime(
pair.into_inner().next().unwrap().try_into()?,
collect_recovered(inner)?,
))
} else {
Ok(GenericDecl::Type(
+4 -1
View File
@@ -14,6 +14,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
let mut inner = pair.into_inner();
let visibility = Visibility::try_from(&mut inner)?;
let is_virtual = listen_rule(&mut inner, Rule::virtual_kw);
let return_type = consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose()?;
@@ -45,12 +47,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
Ok(Self {
visibility: visibility,
is_override: is_override,
is_virtual: is_virtual,
return_type: return_type,
name: name,
generics: generics,
self_param: self_param,
params: params,
is_override: is_override,
body: body,
})
})
+32 -3
View File
@@ -54,11 +54,22 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
.transpose()
.map(|v| v.unwrap_or_default())?,
fields: inner
.next()
.map(|pair| collect_recovered(pair.into_inner()))
fields: collect_recovered(inner.next().unwrap().into_inner())?,
}),
Rule::tuple_struct_decl => Ok(TopLevelKind::StructDeclTupleUnit {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
unit: consume_rule(&mut inner, Rule::tuple_type)
.map(|v| collect_recovered(v.into_inner()))
.transpose()?,
}),
Rule::class_decl => Ok(TopLevelKind::ClassDecl {
@@ -133,6 +144,24 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
ty: inner.next().unwrap().try_into()?,
}),
Rule::include_global => Ok(TopLevelKind::IncludeGlobal(Path(collect_recovered(
&mut inner,
)?))),
Rule::include_use_global => Ok(TopLevelKind::IncludeUse(
Visibility::try_from(&mut inner)?,
Path::try_from(inner.next().unwrap())?,
)),
Rule::include_local => Ok(TopLevelKind::IncludeLocal(
inner
.next()
.unwrap()
.into_inner()
.next()
.unwrap()
.to_string(),
)),
_ => AstError::bug_unimplemented(pair),
}
}
+2 -2
View File
@@ -3,12 +3,12 @@ use std::{collections::HashSet, path::PathBuf};
use serde::{Deserialize, Serialize};
#[derive(
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct MistMap(pub usize, pub usize);
#[derive(
Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct RustMap(pub usize, pub usize);
+29 -4
View File
@@ -46,10 +46,13 @@ pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<Semanti
if let Some(constructor) = constructor {
let mut fields = fields
.iter()
.map(|field| Spanned {
item: field.item.decl.name.clone(),
line: field.line,
column: field.column,
.filter_map(|field| match field.item.init {
Some(_) => None,
None => Some(Spanned {
item: field.item.decl.name.clone(),
line: field.line,
column: field.column,
}),
})
.collect::<Vec<_>>();
@@ -99,6 +102,28 @@ pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<Semanti
}
Ok(())
} else if let TopLevelKind::FunctionDecl(decl) = &top_level.0.item {
if decl.is_virtual && decl.is_override.is_some() {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "virtual and override are only used in classes".to_string(),
}])
} else if decl.is_virtual {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "virtual is only used in classes".to_string(),
}])
} else if decl.is_override.is_some() {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "override is only used in classes".to_string(),
}])
} else {
Ok(())
}
} else {
Ok(())
}
+56 -1
View File
@@ -1,5 +1,4 @@
pub module decl_test;
pub module decl_test;
pub void test_let_basic()
{
@@ -7,6 +6,13 @@ pub void test_let_basic()
assert_eq!(x, 42);
}
pub void test_let_repeat()
{
let x, y = (42, 67);
assert_eq!(x, 42);
assert_eq!(y, 67);
}
pub void test_let_typed()
{
i32 x = 42;
@@ -19,6 +25,29 @@ pub void test_let_typed()
assert_eq!(f, 3.14);
}
pub void test_let_repeat_typed()
{
i32 x, x1 = (42, 67);
assert_eq!(x, 42);
assert_eq!(x1, 67);
str& s, s1 = ("hello", "world");
assert_eq!(s, "hello");
assert_eq!(s1, "world");
bool b, b1 = (true, false);
assert_eq!(b, true);
assert_eq!(b1, false);
f64 f, f1 = (3.14, 5.5);
assert_eq!(f, 3.14);
assert_eq!(f1, 5.5);
(i32, f64) as a, b = (70, 1.4);
assert_eq!(a, 70);
assert_eq!(b, 1.4);
}
pub void test_let_mut()
{
let mut _x = 42;
@@ -77,10 +106,33 @@ pub void test_let_bool()
assert_eq!(t, !f);
}
pub void test_let_decl_only()
{
let x;
x = 42;
assert_eq!(x, 42);
}
pub void test_let_typed_decl_only()
{
i32 x;
x = 100;
assert_eq!(x, 100);
}
pub void test_let_decl_mut_no_init()
{
let mut x;
x = 5;
assert_eq!(x, 5);
}
pub void run_tests()
{
test_let_basic();
test_let_repeat();
test_let_typed();
test_let_repeat_typed();
test_let_mut();
test_let_tuple_destructure();
test_let_nested_tuple();
@@ -89,4 +141,7 @@ pub void run_tests()
test_let_with_type_and_init();
test_string_literal();
test_let_bool();
test_let_decl_only();
test_let_typed_decl_only();
test_let_decl_mut_no_init();
}
+64 -1
View File
@@ -1,5 +1,4 @@
pub module expr_test;
pub module expr_test;
pub void test_literals()
{
@@ -156,6 +155,63 @@ pub void test_binary_assign()
assert_eq!(x, 2);
}
pub void test_binary_assign_bit()
{
let mut x = 10;
x &= 12;
assert_eq!(x, 8);
x |= 1;
assert_eq!(x, 9);
x ^= 3;
assert_eq!(x, 10);
let mut y = 8;
y <<= 2;
assert_eq!(y, 32);
y >>= 1;
assert_eq!(y, 16);
}
pub void test_empty_tuple()
{
let t = ();
assert_eq!(t, ());
}
pub void test_empty_array()
{
let arr = [0; 0];
assert_eq!(arr.len(), 0);
}
pub void test_range_inclusive()
{
let mut sum = 0;
for i in 1 ..= 3 {
sum += i;
}
assert_eq!(sum, 6);
}
pub void test_closure_no_args()
{
let f = () => 42;
assert_eq!(f(), 42);
}
pub void test_closure_with_typed_params()
{
let add = (i32 a, i32 b) => a + b;
assert_eq!(add(3, 4), 7);
}
pub void test_mut_ref()
{
let mut x = 42;
let r = &mut x;
*r = 100;
assert_eq!(x, 100);
}
pub void run_tests()
{
test_literals();
@@ -175,4 +231,11 @@ pub void run_tests()
test_if_expr();
test_range_expr();
test_binary_assign();
test_binary_assign_bit();
test_empty_tuple();
test_empty_array();
test_range_inclusive();
test_closure_no_args();
test_closure_with_typed_params();
test_mut_ref();
}
-1
View File
@@ -1,4 +1,3 @@
pub module package;
pub module common;
pub void test_package() {}
+68 -1
View File
@@ -1,5 +1,4 @@
pub module statement_test;
pub module statement_test;
pub void test_var_decl()
{
@@ -161,6 +160,68 @@ pub void test_for_with_pattern_destructure()
assert_eq!(keys, 3);
}
pub void test_c_for_loop()
{
let mut sum = 0;
for (let mut i = 0; i < 4; i++) {
sum += i;
}
assert_eq!(sum, 6);
}
pub void test_unsafe_block()
{
let mut x = 42;
unsafe {
let r = &mut x;
*r = 100;
}
assert_eq!(x, 100);
}
pub void test_match_parenthesized()
{
let result;
match (2) {
1 => result = 10,
2 => result = 20,
_ => panic!(),
}
assert_eq!(result, 20);
}
pub void test_if_parenthesized()
{
let mut x = 0;
if (true) {
x = 1;
}
assert_eq!(x, 1);
}
pub void test_while_parenthesized()
{
let mut count = 0;
while (count < 3) {
count++;
}
assert_eq!(count, 3);
}
pub void test_loop_with_break_value()
{
let mut x = 0;
let result;
loop {
if x >= 3 {
result = x;
break;
}
x++;
}
assert_eq!(result, 3);
}
pub void run_tests()
{
test_var_decl();
@@ -177,4 +238,10 @@ pub void run_tests()
test_match_or_pattern();
test_match_default();
test_for_with_pattern_destructure();
test_c_for_loop();
test_unsafe_block();
test_match_parenthesized();
test_if_parenthesized();
test_while_parenthesized();
test_loop_with_break_value();
}
+28 -1
View File
@@ -1,5 +1,4 @@
pub module types_test;
pub module types_test;
pub void test_integer_type() {
i32 x = 42;
@@ -53,6 +52,30 @@ pub void test_fn_return_type() {
assert_eq!(add(3, 4), 7);
}
pub void test_generic_type() {
Option<i32> x = Option::Some(42);
assert_eq!(x.is_some(), true);
}
type MyInt = i32;
pub void test_type_alias() {
MyInt x = 42;
assert_eq!(x, 42);
}
const i32 MY_CONST = 100;
pub void test_const_decl() {
assert_eq!(MY_CONST, 100);
}
static i32 my_static = 200;
pub void test_static_decl() {
assert_eq!(my_static, 200);
}
pub void run_tests() {
test_integer_type();
test_float_type();
@@ -63,4 +86,8 @@ pub void run_tests() {
test_mut_ref_type();
test_void_type();
test_fn_return_type();
test_generic_type();
test_type_alias();
test_const_decl();
test_static_decl();
}
+14 -2
View File
@@ -1,10 +1,9 @@
pub module attribute_test;
pub module attribute_test;
#[derive(Debug)]
pub struct Debuggable
{
i32 value,
i32 value;
}
pub void test_derive_attribute()
@@ -23,8 +22,21 @@ pub void test_allow_attribute()
assert_eq!(x, 42);
}
#[allow(dead_code)]
pub struct Tagged
{
i32 id;
}
pub void test_attribute_with_args()
{
Tagged t = Tagged { id: 1 };
assert_eq!(t.id, 1);
}
pub void run_tests()
{
test_derive_attribute();
test_allow_attribute();
test_attribute_with_args();
}
+80 -2
View File
@@ -1,5 +1,8 @@
pub module class_test;
pub module class_test;
pub enum AnimalType {
Mammal;
}
pub class Animal
{
@@ -10,11 +13,17 @@ pub class Animal
self.name = "Rex".to_string();
}
pub String speak(&self)
pub virtual AnimalType get_animal_type(&self) {
panic!()
}
pub virtual String speak(&self)
{
"Unknown".to_string()
}
pub virtual void speak_mut(&mut self){}
pub void test_speak<'a>(&'a self)
{
assert_eq!(self.speak(), "Woof!");
@@ -32,6 +41,11 @@ pub class Mammal : Animal
super = Super::new();
}
// override without a target assumes current super
pub AnimalType get_animal_type(&self) override {
AnimalType::Mammal
}
pub void args_test(&self, i32 x, str& y)
{
assert_eq!(x, 10);
@@ -60,10 +74,74 @@ pub class Dog : Mammal
}
}
pub class Counter
{
pub i32 count;
constructor()
{
self.count = 42;
}
i32 get_count(&self)
{
self.count
}
pub i32 static_fn()
{
99
}
}
pub void test_class_no_inheritance()
{
Counter c = Counter::new();
assert_eq!(c.get_count(), 42);
}
pub class WithDefault
{
pub String name = "default".to_string();
pub i32 value = 42;
constructor()
{
}
pub String get_name(&self)
{
self.name.clone()
}
}
pub void test_class_field_default()
{
WithDefault w = WithDefault::new();
assert_eq!(w.get_name(), "default");
assert_eq!(w.value, 42);
}
pub class EmptyClass
{
constructor()
{
}
}
pub void test_class_empty()
{
EmptyClass e = EmptyClass::new();
}
pub void run_tests()
{
let dawg = Dog::new();
dawg.args_test(10, "hello");
dawg.test_speak();
dawg.get_animal_type();
assert_eq!(format!("{dawg}"), "🐾 Rex");
test_class_no_inheritance();
test_class_field_default();
test_class_empty();
}
+42 -8
View File
@@ -1,10 +1,9 @@
pub module enum_test;
pub module enum_test;
enum OptionInt
{
None,
Some(i32),
None;
Some(i32);
}
pub void test_enum_named()
@@ -35,8 +34,13 @@ pub void test_enum_tuple()
enum Shape
{
Circle {i32 radius},
Rect {i32 w, i32 h},
Circle {
i32 radius;
};
Rect {
i32 w;
i32 h;
};
}
pub void test_enum_struct()
@@ -68,9 +72,9 @@ pub void test_enum_struct()
enum Color
{
Red,
Green,
Blue,
Red;
Green;
Blue;
}
pub void test_enum_eq()
@@ -86,10 +90,40 @@ pub void test_enum_eq()
}
}
enum Option<T>
{
None;
Some(T);
}
pub void test_generic_enum()
{
Option<i32> x = Option::Some(42);
match x {
Option::Some(v) => {
assert_eq!(v, 42);
}
_ => {
assert_eq!(0, 1);
}
}
Option<bool> y = Option::None;
match y {
Option::None => {
assert_eq!(1, 1);
}
_ => {
assert_eq!(0, 1);
}
}
}
pub void run_tests()
{
test_enum_named();
test_enum_tuple();
test_enum_struct();
test_enum_eq();
test_generic_enum();
}
+12 -1
View File
@@ -1,5 +1,4 @@
pub module function_test;
pub module function_test;
void greet()
{
@@ -70,6 +69,17 @@ pub void test_recursive_fn()
assert_eq!(factorial(5), 120);
}
T identity<T>(T x)
{
x
}
pub void test_fn_generic()
{
assert_eq!(identity(42), 42);
assert_eq!(identity("hello"), "hello");
}
pub void run_tests()
{
test_basic_function();
@@ -80,4 +90,5 @@ pub void run_tests()
test_method_call();
test_nested_fn_calls();
test_recursive_fn();
test_fn_generic();
}
+22 -3
View File
@@ -1,10 +1,9 @@
pub module impl_test;
pub module impl_test;
struct Vector2
{
i32 x,
i32 y,
i32 x;
i32 y;
}
impl Vector2
@@ -73,9 +72,29 @@ pub void test_multiple_impls()
assert_eq!(c.y, 6);
}
struct Wrapper<T>
{
T value;
}
impl<T: Copy> Wrapper<T>
{
pub T get(&self)
{
self.value
}
}
pub void test_impl_generic()
{
Wrapper<i32> w = Wrapper { value: 42 };
assert_eq!(w.get(), 42);
}
pub void run_tests()
{
test_inherent_impl();
test_trait_impl_block();
test_multiple_impls();
test_impl_generic();
}
+52 -5
View File
@@ -1,10 +1,9 @@
pub module struct_test;
pub module struct_test;
struct Point
{
i32 x,
i32 y,
i32 x;
i32 y;
}
pub void test_struct_create_access()
@@ -40,8 +39,8 @@ pub void test_struct_destructure()
struct Line
{
Point start,
Point end,
Point start;
Point end;
}
pub void test_struct_nested()
@@ -60,10 +59,58 @@ pub void test_struct_nested()
assert_eq!(l.end.y, 10);
}
struct Empty {}
pub void test_empty_struct()
{
let e = Empty {};
}
struct Pair<T>
{
T first;
T second;
}
pub void test_generic_struct()
{
Pair<i32> p = Pair<i32> { first: 1, second: 2 };
assert_eq!(p.first, 1);
assert_eq!(p.second, 2);
}
pub void test_struct_partial_destructure()
{
let p = Point {
x: 10,
y: 20,
};
let Point {x, ..} = p;
assert_eq!(x, 10);
}
pub void test_struct_destructure_rename()
{
let p = Point {
x: 5,
y: 15,
};
let Point {x: a, y: b} = p;
assert_eq!(a, 5);
assert_eq!(b, 15);
}
struct TuplePoint(i32, i32);
struct Unit;
pub void run_tests()
{
test_struct_create_access();
test_struct_mut_field();
test_struct_destructure();
test_struct_nested();
test_empty_struct();
test_generic_struct();
test_struct_partial_destructure();
test_struct_destructure_rename();
}
+1 -2
View File
@@ -1,5 +1,4 @@
pub module trait_test;
pub module trait_test;
trait Speak
{
@@ -13,7 +12,7 @@ trait Greet : Speak
struct Dog
{
String name,
String name;
}
impl Speak for Dog
+18 -1
View File
@@ -16,10 +16,11 @@ void main()
process::exit(1);
}
match args[1].as_str() {
"run" | "build" | "check" | "test" | "publish" | "bench" | "doc" | "fix" | "clippy" | "r" | "b" | "c" => {
"run" | "build" | "check" | "test" | "bench" | "doc" | "fix" | "clippy" | "r" | "b" | "c" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);
transpiler::transpile(&root);
println!("");
if builder::build(args, root) {
println!("\x1b[32m\nBuild successful\x1b[0m");
@@ -27,6 +28,22 @@ void main()
println!("\x1b[31m\nBuild failed\x1b[0m");
}
}
"publish" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);
transpiler::transpile(&root);
let status = std::process::Command::new("cargo")
.args(args)
.status()
.expect("Failed to run cargo");
if status.success() {
println!("\x1b[32m\nPublished successfully\x1b[0m");
} else {
println!("\x1b[31m\nFailed to publish\x1b[0m");
}
}
"transpile" | "t" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);