Compare commits

..
Author SHA1 Message Date
selimaj-dev e9b7312362 Added include to Mist.toml 2026-06-30 19:58:47 +02:00
selimaj-dev 6e67fd852b bump to alpha 1 2026-06-30 19:48:33 +02:00
selimaj-dev 67acef8270 Merge pull request #99 from mist-go/subcrates-and-diagnostics
Subcrates and diagnostics
2026-06-30 19:46:58 +02:00
selimaj-dev a3da192b9a Analyzer Sub crate support 2026-06-30 19:41:34 +02:00
selimaj-dev 310ff6b53c Fix include non mist crates #86 2026-06-30 19:28:27 +02:00
selimaj-dev 4e1bcf36fc Include sub crates #86 2026-06-30 19:14:12 +02:00
selimaj-dev c1d7152992 Deduped config 2026-06-30 18:30:19 +02:00
selimaj-dev bd938ec3e7 Updated transpiler config 2026-06-30 18:23:15 +02:00
selimaj-dev bfaa9eeea5 Fix Diagnostics #93 2026-06-30 07:08:39 +02:00
selimaj-dev 3ff4c2ab08 Using FS for saving files #93 2026-06-30 06:24:55 +02:00
selimaj-dev 3d30e0a092 Fix fmt expr path generics 2026-06-28 17:39:35 +02:00
selimaj-dev 502bde1536 Updated boostrap 2026-06-28 17:38:16 +02:00
16 changed files with 427 additions and 389 deletions
Generated
+6 -5
View File
@@ -476,11 +476,12 @@ dependencies = [
[[package]] [[package]]
name = "mist-analyzer" name = "mist-analyzer"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
dependencies = [ dependencies = [
"cargo_metadata", "cargo_metadata",
"dashmap 6.1.0", "dashmap 6.1.0",
"heck", "heck",
"mist-api",
"mist-codegen", "mist-codegen",
"mist-parser", "mist-parser",
"pest", "pest",
@@ -494,7 +495,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-api" name = "mist-api"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
dependencies = [ dependencies = [
"cargo_metadata", "cargo_metadata",
"mist-codegen", "mist-codegen",
@@ -506,7 +507,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-codegen" name = "mist-codegen"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
dependencies = [ dependencies = [
"bytecount", "bytecount",
"mist-parser", "mist-parser",
@@ -514,7 +515,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-lang" name = "mist-lang"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
dependencies = [ dependencies = [
"mist-analyzer", "mist-analyzer",
"mist-api", "mist-api",
@@ -522,7 +523,7 @@ dependencies = [
[[package]] [[package]]
name = "mist-parser" name = "mist-parser"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
dependencies = [ dependencies = [
"pest", "pest",
"pest_derive", "pest_derive",
+5 -5
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-lang" name = "mist-lang"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
edition = "2024" edition = "2024"
description = "The Mist programming language compiler" description = "The Mist programming language compiler"
license = "Apache-2.0" license = "Apache-2.0"
@@ -32,10 +32,10 @@ exclude = [
] ]
[workspace.dependencies] [workspace.dependencies]
mist-parser = { path = "crates/parser", version = "0.3.7-alpha.0" } mist-parser = { path = "crates/parser", version = "0.3.7-alpha.1" }
mist-analyzer = { path = "crates/analyzer", version = "0.3.7-alpha.0" } mist-analyzer = { path = "crates/analyzer", version = "0.3.7-alpha.1" }
mist-codegen = { path = "crates/codegen", version = "0.3.7-alpha.0" } mist-codegen = { path = "crates/codegen", version = "0.3.7-alpha.1" }
mist-api = { path = "crates/mist-api", version = "0.3.7-alpha.0" } mist-api = { path = "crates/mist-api", version = "0.3.7-alpha.1" }
[[bin]] [[bin]]
name = "mist" name = "mist"
+1
View File
@@ -1,2 +1,3 @@
package = "main.mist" package = "main.mist"
packages = [] packages = []
include = ["crates/*"]
+2 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-analyzer" name = "mist-analyzer"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
edition = "2024" edition = "2024"
description = "The Mist programming language Analyzer LSP" description = "The Mist programming language Analyzer LSP"
license = "Apache-2.0" license = "Apache-2.0"
@@ -9,6 +9,7 @@ keywords = ["language-server", "language", "mist"]
categories = ["compilers"] categories = ["compilers"]
[dependencies] [dependencies]
mist-api = { workspace = true }
mist-parser = { workspace = true } mist-parser = { workspace = true }
mist-codegen = { workspace = true } mist-codegen = { workspace = true }
pest = "2.8.6" pest = "2.8.6"
+185 -65
View File
@@ -7,18 +7,21 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use heck::ToSnakeCase; use heck::ToSnakeCase;
use mist_api::transpiler::MistConfig;
use mist_parser::MistFmtConfig; use mist_parser::MistFmtConfig;
use mist_parser::error::ParseError; use mist_parser::error::ParseError;
use mist_parser::rev_mapper::{Mapping, MistMap, RustMap}; use mist_parser::rev_mapper::{Mapping, MistMap, RustMap};
use ropey::Rope; use ropey::Rope;
use serde::{Deserialize, Serialize}; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tower_lsp::lsp_types::{self, *}; use tower_lsp::lsp_types::{self, *};
use tower_lsp::{Client, LanguageServer, LspService, Server}; use tower_lsp::{Client, LanguageServer, LspService, Server};
use crate::rust_analyzer::RustAnalyzer; use crate::rust_analyzer::RustAnalyzer;
use crate::transpiler::{TranspileError, format_mist, transpile_mist, transpile_mist_no_sem}; use crate::transpiler::{
TranspileError, TranspiledFile, format_mist, transpile_mist, transpile_mist_no_sem,
};
static MARKER_COUNTER: AtomicU64 = AtomicU64::new(0); static MARKER_COUNTER: AtomicU64 = AtomicU64::new(0);
@@ -519,8 +522,9 @@ impl Backend {
Some(p) => p.clone(), Some(p) => p.clone(),
None => return String::new(), None => return String::new(),
}; };
let src_root = ws.join("src"); let crate_root = find_crate_root(mist_path).unwrap_or(ws);
let package_mist = read_mist_package(&ws); let src_root = crate_root.join("src");
let package_mist = read_mist_package(&crate_root);
let docs = self.documents.lock().await; let docs = self.documents.lock().await;
let mod_decls = compute_mod_decls(&docs, &src_root, &package_mist); let mod_decls = compute_mod_decls(&docs, &src_root, &package_mist);
mod_decls.get(mist_path).cloned().unwrap_or_default() mod_decls.get(mist_path).cloned().unwrap_or_default()
@@ -547,7 +551,7 @@ impl Backend {
mist_path: &Path, mist_path: &Path,
source: &str, source: &str,
extra_mod_decl: &str, extra_mod_decl: &str,
) { ) -> Option<TranspiledFile> {
let transpiled = match transpile_mist(mist_path, source, extra_mod_decl) { let transpiled = match transpile_mist(mist_path, source, extra_mod_decl) {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
@@ -556,7 +560,7 @@ impl Backend {
if let Some(uri) = clean_lsp_url(mist_path) { if let Some(uri) = clean_lsp_url(mist_path) {
self.publish_diagnostics(uri, diag).await; self.publish_diagnostics(uri, diag).await;
} }
return; return None;
} }
}; };
@@ -577,28 +581,28 @@ impl Backend {
let _ = ra.did_open(rust_uri, &transpiled.rust_content).await; let _ = ra.did_open(rust_uri, &transpiled.rust_content).await;
} }
map.insert(transpiled.rust_path, transpiled.mapping); map.insert(transpiled.rust_path.clone(), transpiled.mapping.clone());
self.last_rust_contents self.last_rust_contents
.lock() .lock()
.await .await
.insert(mist_path.to_path_buf(), transpiled.rust_content); .insert(mist_path.to_path_buf(), transpiled.rust_content.clone());
} }
// Clear any previous diagnostics — transpile succeeded. // Clear any previous diagnostics — transpile succeeded.
if let Some(mist_uri) = clean_lsp_url(mist_path) { if let Some(mist_uri) = clean_lsp_url(mist_path) {
self.publish_diagnostics(mist_uri, vec![]).await; self.publish_diagnostics(mist_uri, vec![]).await;
} }
Some(transpiled)
} }
async fn rebuild_module_tree(&self) { async fn rebuild_module_tree(&self, persist: bool) {
let ws = match &*self.workspace_folder.lock().await { let ws = match &*self.workspace_folder.lock().await {
Some(p) => p.clone(), Some(p) => p.clone(),
None => return, None => return,
}; };
let src_root = ws.join("src");
let package_mist = read_mist_package(&ws);
self.ensure_implicit_packages(&src_root).await; self.ensure_implicit_packages().await;
// Collect sources first to avoid holding locks during transpile // Collect sources first to avoid holding locks during transpile
let sources: Vec<(PathBuf, String, String)> = { let sources: Vec<(PathBuf, String, String)> = {
@@ -606,25 +610,72 @@ impl Backend {
if docs.is_empty() { if docs.is_empty() {
return; return;
} }
let mod_decls = compute_mod_decls(&docs, &src_root, &package_mist); let crate_roots = collect_crate_roots(&docs, &ws);
mod_decls let mut result = Vec::new();
.into_iter() for crate_root in &crate_roots {
.filter(|(_, decl)| !decl.is_empty()) let src_root = crate_root.join("src");
.filter_map(|(path, decl)| docs.get(&path).map(|r| (path, r.to_string(), decl))) let package_mist = read_mist_package(crate_root);
.collect() let mod_decls = compute_mod_decls(&docs, &src_root, &package_mist);
for (path, decl) in mod_decls {
if !decl.is_empty() {
if let Some(source) = docs.get(&path) {
result.push((path.clone(), source.to_string(), decl));
}
}
}
}
result
}; };
for (mist_path, source, decl) in sources { for (mist_path, source, decl) in sources {
self.handle_transpile_and_notify(&mist_path, &source, &decl) if let Some(transpiled) = self
.await; .handle_transpile_and_notify(&mist_path, &source, &decl)
.await
{
if persist {
Self::write_transpiled_to_disk(&transpiled);
}
}
} }
} }
/// Create synthetic `package.mist` documents for subdirectories that contain /// Create synthetic `package.mist` documents for subdirectories that contain
/// .mist files but no real package.mist (implicit packages). /// .mist files but no real package.mist (implicit packages).
async fn ensure_implicit_packages(&self, src_root: &Path) { async fn ensure_implicit_packages(&self) {
let ws = match &*self.workspace_folder.lock().await {
Some(p) => p.clone(),
None => return,
};
let mut docs = self.documents.lock().await; let mut docs = self.documents.lock().await;
ensure_implicit_packages_impl(&mut *docs, src_root); let crate_roots = collect_crate_roots(&docs, &ws);
for crate_root in &crate_roots {
let src_root = crate_root.join("src");
ensure_implicit_packages_impl(&mut *docs, &src_root);
}
}
/// Write a transpiled file's `.rs` content and `.map.json` mapping to disk.
/// The output directory is created if it doesn't exist.
fn write_transpiled_to_disk(transpiled: &TranspiledFile) {
if let Some(parent) = transpiled.rust_path.parent() {
if let Err(e) = std::fs::create_dir_all(parent) {
eprintln!("Failed to create output directory {:?}: {e}", parent);
return;
}
}
if let Err(e) = std::fs::write(&transpiled.rust_path, &transpiled.rust_content) {
eprintln!(
"Failed to write transpiled file {:?}: {e}",
transpiled.rust_path
);
return;
}
let map_path = transpiled.rust_path.with_extension("map.json");
if let Ok(map_json) = serde_json::to_string(&transpiled.mapping) {
if let Err(e) = std::fs::write(&map_path, &map_json) {
eprintln!("Failed to write mapping file {:?}: {e}", map_path);
}
}
} }
async fn publish_diagnostics(&self, uri: Url, diagnostics: Vec<Diagnostic>) { async fn publish_diagnostics(&self, uri: Url, diagnostics: Vec<Diagnostic>) {
@@ -730,8 +781,6 @@ impl LanguageServer for Backend {
tokio::spawn(async move { tokio::spawn(async move {
if let Some(root) = &*ws.lock().await { if let Some(root) = &*ws.lock().await {
let src_root = root.join("src");
// Hold the lock across both initialize + initialized so the // Hold the lock across both initialize + initialized so the
// editor's didOpen cannot race in-between and send notifications // editor's didOpen cannot race in-between and send notifications
// to rust-analyzer before it has received Initialized. // to rust-analyzer before it has received Initialized.
@@ -748,7 +797,21 @@ impl LanguageServer for Backend {
} }
let mut files = Vec::new(); let mut files = Vec::new();
collect_mist_files(&src_root, &mut files); collect_mist_files(&root.join("src"), &mut files);
// Discover subcrates by scanning for Mist.toml in immediate
// subdirectories of the workspace root.
let mut subcrate_roots = Vec::new();
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() && entry_path.join("Mist.toml").is_file() {
let sub_src = entry_path.join("src");
collect_mist_files(&sub_src, &mut files);
subcrate_roots.push(entry_path);
}
}
}
for file in &files { for file in &files {
if let Ok(text) = std::fs::read_to_string(file) { if let Ok(text) = std::fs::read_to_string(file) {
@@ -761,15 +824,32 @@ impl LanguageServer for Backend {
eprintln!("Loaded {} mist files", files.len()); eprintln!("Loaded {} mist files", files.len());
ensure_implicit_packages_impl(&mut *documents.lock().await, &src_root); // Create implicit packages per crate root
{
let mut docs = documents.lock().await;
let all_crate_roots: Vec<PathBuf> = std::iter::once(root.clone())
.chain(subcrate_roots.iter().cloned())
.collect();
for crate_root in &all_crate_roots {
ensure_implicit_packages_impl(&mut *docs, &crate_root.join("src"));
}
}
// Compute mod_decls before any transpile so the root file gets its // Compute mod_decls per crate root before any transpile so each
// child module declarations from the very first didOpen. // crate's root file gets its child module declarations.
let package_mist = read_mist_package(root); let all_crate_roots: Vec<PathBuf> = std::iter::once(root.clone())
let src_root = root.join("src"); .chain(subcrate_roots.iter().cloned())
.collect();
let mod_decls = { let mod_decls = {
let docs = documents.lock().await; let docs = documents.lock().await;
compute_mod_decls(&docs, &src_root, &package_mist) let mut merged = HashMap::new();
for crate_root in &all_crate_roots {
let cr_src = crate_root.join("src");
let pkg = read_mist_package(crate_root);
let decls = compute_mod_decls(&docs, &cr_src, &pkg);
merged.extend(decls);
}
merged
}; };
for file in &files { for file in &files {
@@ -819,14 +899,22 @@ impl LanguageServer for Backend {
.cloned() .cloned()
.collect(); .collect();
for syn_path in &synthetic_paths { for syn_path in &synthetic_paths {
let decl = mod_decls.get(syn_path).map(String::as_str).unwrap_or(""); // Find the crate root for this synthetic file
let syn_crate_root = find_crate_root(syn_path).unwrap_or_else(|| root.clone());
let pkg = read_mist_package(&syn_crate_root);
let cr_src = syn_crate_root.join("src");
let decl = {
let docs = documents.lock().await;
let crate_decls = compute_mod_decls(&docs, &cr_src, &pkg);
crate_decls.get(syn_path).cloned().unwrap_or_default()
};
let source = documents let source = documents
.lock() .lock()
.await .await
.get(syn_path) .get(syn_path)
.map(|r| r.to_string()) .map(|r| r.to_string())
.unwrap_or_default(); .unwrap_or_default();
if let Ok(transpiled) = transpile_mist(syn_path, &source, decl) { if let Ok(transpiled) = transpile_mist(syn_path, &source, &decl) {
if let Some(rust_uri) = clean_lsp_url(&transpiled.rust_path) { if let Some(rust_uri) = clean_lsp_url(&transpiled.rust_path) {
let _ = ra let _ = ra
.lock() .lock()
@@ -949,9 +1037,10 @@ impl LanguageServer for Backend {
.await .await
.insert(mist_path.clone(), Rope::from_str(&source)); .insert(mist_path.clone(), Rope::from_str(&source));
self.handle_transpile_and_notify(&mist_path, &source, "") let extra_decl = self.compute_mod_decl_for_file(&mist_path).await;
self.handle_transpile_and_notify(&mist_path, &source, &extra_decl)
.await; .await;
self.rebuild_module_tree().await; self.rebuild_module_tree(false).await;
} }
async fn did_change(&self, params: DidChangeTextDocumentParams) { async fn did_change(&self, params: DidChangeTextDocumentParams) {
@@ -971,9 +1060,10 @@ impl LanguageServer for Backend {
.await .await
.insert(mist_path.clone(), Rope::from_str(&source)); .insert(mist_path.clone(), Rope::from_str(&source));
self.handle_transpile_and_notify(&mist_path, &source, "") let extra_decl = self.compute_mod_decl_for_file(&mist_path).await;
self.handle_transpile_and_notify(&mist_path, &source, &extra_decl)
.await; .await;
self.rebuild_module_tree().await; self.rebuild_module_tree(false).await;
} }
} }
@@ -986,16 +1076,35 @@ impl LanguageServer for Backend {
} }
}; };
if let Some(text) = params.text { let text = if let Some(text) = &params.text {
self.documents text.clone()
.lock() } else {
tokio::fs::read_to_string(&mist_path)
.await .await
.insert(mist_path.clone(), Rope::from_str(&text)); .expect("Failed to read file")
};
self.handle_transpile_and_notify(&mist_path, &text, "") self.documents
.await; .lock()
self.rebuild_module_tree().await; .await
.insert(mist_path.clone(), Rope::from_str(&text));
let extra_decl = self.compute_mod_decl_for_file(&mist_path).await;
if let Some(transpiled) = self
.handle_transpile_and_notify(&mist_path, &text, &extra_decl)
.await
{
Self::write_transpiled_to_disk(&transpiled);
if let Some(rust_uri) = clean_lsp_url(&transpiled.rust_path) {
let _ = self
.rust_analyzer
.lock()
.await
.did_save(rust_uri, &transpiled.rust_content)
.await;
}
} }
self.rebuild_module_tree(true).await;
} }
async fn did_close(&self, params: DidCloseTextDocumentParams) { async fn did_close(&self, params: DidCloseTextDocumentParams) {
@@ -1775,17 +1884,13 @@ async fn handle_ra_notifications(
}; };
if let Some(mist_uri) = mist_uri.or(Some(rust_uri.clone())) { if let Some(mist_uri) = mist_uri.or(Some(rust_uri.clone())) {
let prev = previous_diagnostics.lock().await.get(&mist_uri).cloned(); previous_diagnostics
.lock()
if prev.as_ref() != Some(&mapped_diagnostics) { .await
previous_diagnostics .insert(mist_uri.clone(), mapped_diagnostics.clone());
.lock() client
.await .publish_diagnostics(mist_uri, mapped_diagnostics, None)
.insert(mist_uri.clone(), mapped_diagnostics.clone()); .await;
client
.publish_diagnostics(mist_uri, mapped_diagnostics, None)
.await;
}
} }
} }
} }
@@ -1842,13 +1947,6 @@ fn read_mist_package(workspace_root: &Path) -> String {
.unwrap_or_else(|| "main.mist".to_string()) .unwrap_or_else(|| "main.mist".to_string())
} }
#[derive(Debug, Serialize, Deserialize)]
pub struct MistConfig {
pub package: PathBuf,
pub packages: Vec<PathBuf>,
pub fmt: Option<MistFmtConfig>,
}
fn read_mist_fmt(workspace_root: &Path) -> Option<MistFmtConfig> { fn read_mist_fmt(workspace_root: &Path) -> Option<MistFmtConfig> {
let toml_path = workspace_root.join("Mist.toml"); let toml_path = workspace_root.join("Mist.toml");
let content = match std::fs::read_to_string(&toml_path) { let content = match std::fs::read_to_string(&toml_path) {
@@ -1860,9 +1958,31 @@ fn read_mist_fmt(workspace_root: &Path) -> Option<MistFmtConfig> {
} }
}; };
toml::from_str::<MistConfig>(&content) toml::from_str::<MistConfig>(&content).ok().map(|v| v.fmt)
.ok() }
.and_then(|v| v.fmt)
fn find_crate_root(file_path: &Path) -> Option<PathBuf> {
let mut dir = file_path.parent()?;
loop {
if dir.join("Mist.toml").is_file() {
return Some(dir.to_path_buf());
}
dir = match dir.parent() {
Some(p) => p,
None => return None,
};
}
}
fn collect_crate_roots(docs: &HashMap<PathBuf, Rope>, workspace_root: &Path) -> HashSet<PathBuf> {
let mut roots = HashSet::new();
roots.insert(workspace_root.to_path_buf());
for path in docs.keys() {
if let Some(crate_root) = find_crate_root(path) {
roots.insert(crate_root);
}
}
roots
} }
fn compute_mod_decls( fn compute_mod_decls(
+17
View File
@@ -374,6 +374,23 @@ impl RustAnalyzer {
.await .await
} }
pub async fn did_save(
&mut self,
uri: Url,
text: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(
"textDocument/didSave",
json!({
"textDocument": {
"uri": uri,
},
"text": text,
}),
)
.await
}
pub async fn did_close( pub async fn did_close(
&mut self, &mut self,
uri: Url, uri: Url,
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-codegen" name = "mist-codegen"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
edition = "2024" edition = "2024"
description = "The Mist programming language Rust code generator" description = "The Mist programming language Rust code generator"
license = "Apache-2.0" license = "Apache-2.0"
+2 -2
View File
@@ -106,7 +106,7 @@ impl GenMist for Postfix {
field, field,
generics generics
.iter() .iter()
.map(|v| format!("::{}", v.get_mist())) .map(|v| format!("{}", v.get_mist()))
.collect::<String>() .collect::<String>()
)); ));
} }
@@ -116,7 +116,7 @@ impl GenMist for Postfix {
field.get_mist(), field.get_mist(),
generics generics
.iter() .iter()
.map(|v| format!("::{}", v.get_mist())) .map(|v| format!("{}", v.get_mist()))
.collect::<String>() .collect::<String>()
)); ));
} }
+1 -1
View File
@@ -266,7 +266,7 @@ impl GetMist for ExprPathSegment {
self.ident.get_mist(), self.ident.get_mist(),
self.generics self.generics
.as_ref() .as_ref()
.map(|v| format!("::{}", v.get_mist())) .map(|v| format!("{}", v.get_mist()))
.unwrap_or_default() .unwrap_or_default()
) )
} }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-api" name = "mist-api"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
edition = "2024" edition = "2024"
description = "The Mist programming language module system" description = "The Mist programming language module system"
license = "Apache-2.0" license = "Apache-2.0"
+34 -73
View File
@@ -1,16 +1,24 @@
pub module builder; pub module builder;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use std::process::Stdio; use std::process::Stdio;
use cargo_metadata::CompilerMessage; use cargo_metadata::CompilerMessage;
use cargo_metadata::Message; use cargo_metadata::Message;
use mist_parser::rev_mapper; use mist_parser::rev_mapper;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MistDiagnosticMessage { pub struct MistDiagnosticMessage
{
pub String message, pub String message,
pub PathBuf file_path, pub PathBuf file_path,
pub String file_name, pub String file_name,
@@ -19,62 +27,42 @@ pub struct MistDiagnosticMessage {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum MistDiagnostic { pub enum MistDiagnostic
{
Error(MistDiagnosticMessage), Error(MistDiagnosticMessage),
Warning(MistDiagnosticMessage), Warning(MistDiagnosticMessage),
Rust(CompilerMessage), Rust(CompilerMessage),
} }
pub bool build(Vec<String> mut args, PathBuf root) { pub bool build(Vec<String> mut args, PathBuf root)
{
args.remove(0); args.remove(0);
args.insert(1, "--message-format=json".to_string()); args.insert(1, "--message-format=json".to_string());
let mut command = Command::new("cargo").args(args).stdout(Stdio::piped()).stderr(Stdio::inherit()).stdin(Stdio::inherit()).spawn().expect("Failed to run cargo");
let mut command = Command::new("cargo")
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.stdin(Stdio::inherit())
.spawn()
.expect("Failed to run cargo");
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader")); let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
let mut diagnostics = Vec::new(); let mut diagnostics = Vec::new();
let mut mapping = HashMap::new(); let mut mapping = HashMap::new();
for message in cargo_metadata::Message::parse_stream(&mut reader) { for message in cargo_metadata::Message::parse_stream(&mut reader) {
match message { match message {
Ok(Message::CompilerMessage(msg)) => { Ok(Message::CompilerMessage(msg)) => {
for span in &msg.message.spans { for span in &msg.message.spans {
if span.is_primary { if span.is_primary {
let rust_path = root.join(&span.file_name); let rust_path = root.join(&span.file_name);
let mapping_path = rust_path.with_extension("map.json"); let mapping_path = rust_path.with_extension("map.json");
if !fs::exists(&mapping_path).expect("Unable to check if map file exists") { if !fs::exists(&mapping_path).expect("Unable to check if map file exists") {
diagnostics.push(MistDiagnostic::Rust(msg)); diagnostics.push(MistDiagnostic::Rust(msg));
break; break;
} }
let map = mapping.entry(mapping_path.clone()).or_insert_with(() => { let map = mapping.entry(mapping_path.clone()).or_insert_with(() => {
let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file"); let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file");
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file") serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
}); });
let mist_file = map.mist_path.strip_prefix(&root); let mist_file = map.mist_path.strip_prefix(&root);
let (_, rev_mapper::MistMap(line, column)) = map.find(&rev_mapper::RustMap(span.line_end, span.column_start)).expect("Unable to find mapping");
let (_, rev_mapper::MistMap(line, column)) =
map.find(&rev_mapper::RustMap(span.line_end, span.column_start))
.expect("Unable to find mapping");
let mist_msg = MistDiagnosticMessage { let mist_msg = MistDiagnosticMessage {
message: format!( message: format!("{}: {}",
"{}: {}",
msg.message.message, msg.message.message,
span.label.clone().unwrap_or_default() span.label.clone().unwrap_or_default()),
),
file_name: if let Ok(mist_file) = mist_file { file_name: if let Ok(mist_file) = mist_file {
mist_file.to_string_lossy().to_string() mist_file.to_string_lossy().to_string()
} else { } else {
@@ -82,97 +70,70 @@ pub bool build(Vec<String> mut args, PathBuf root) {
}, },
file_path: map.mist_path.clone(), file_path: map.mist_path.clone(),
line: line, line: line,
column: column column: column,
}; };
match msg.message.level { match msg.message.level {
cargo_metadata::diagnostic::DiagnosticLevel::Error => { cargo_metadata::diagnostic::DiagnosticLevel::Error => {
diagnostics.push(MistDiagnostic::Error(mist_msg)) diagnostics.push(MistDiagnostic::Error(mist_msg))
} }
cargo_metadata::diagnostic::DiagnosticLevel::Warning => { cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
diagnostics.push(MistDiagnostic::Warning(mist_msg)) diagnostics.push(MistDiagnostic::Warning(mist_msg))
} }
_ => {
_ => {} }
} }
} }
} }
} }
Ok(Message::BuildFinished(finish)) => { Ok(Message::BuildFinished(finish)) => {
print_diagnostics(&diagnostics); print_diagnostics(&diagnostics);
let mut raw_reader = reader.into_inner(); let mut raw_reader = reader.into_inner();
let mut stdout = std::io::stdout(); let mut stdout = std::io::stdout();
std::io::copy(&mut raw_reader, &mut stdout).map_err((v) => v.to_string()).expect("(Mist) Failed to copy IO");
std::io::copy(&mut raw_reader, &mut stdout)
.map_err((v) => v.to_string())
.expect("(Mist) Failed to copy IO");
command.wait().unwrap(); command.wait().unwrap();
return finish.success; return finish.success;
} }
Ok(Message::TextLine(text)) => println!("{text}"),
Ok(Message::TextLine(text)) => println!("{text}"); _ => {
_ => {} }
} }
} }
false false
} }
pub void print_diagnostics(Vec<MistDiagnostic>& diagnostics) { pub void print_diagnostics(Vec<MistDiagnostic>& diagnostics)
{
let mut files = HashMap::new(); let mut files = HashMap::new();
for diag in diagnostics { for diag in diagnostics {
match diag { match diag {
MistDiagnostic::Error(msg) => { MistDiagnostic::Error(msg) => {
let line = get_line(&mut files, &msg); let line = get_line(&mut files, &msg);
println!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
println!(
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
msg.file_name, msg.file_name,
msg.line, msg.line,
msg.column, msg.column,
msg.message, msg.message,
line.unwrap_or_default(), line.unwrap_or_default(),)
)
} }
MistDiagnostic::Warning(msg) => { MistDiagnostic::Warning(msg) => {
let line = get_line(&mut files, &msg); let line = get_line(&mut files, &msg);
println!("\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
println!(
"\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
msg.file_name, msg.file_name,
msg.line, msg.line,
msg.column, msg.column,
msg.message, msg.message,
line.unwrap_or_default(), line.unwrap_or_default(),)
)
} }
MistDiagnostic::Rust(rs) => println!("{rs}"),
MistDiagnostic::Rust(rs) => println!("{rs}");
} }
} }
} }
pub Option<String> get_line( pub Option<String> get_line(HashMap<PathBuf, Vec<String>> mut& files, MistDiagnosticMessage& msg)
HashMap<PathBuf, Vec<String>> mut& files, {
MistDiagnosticMessage& msg,
) {
let src_path = msg.file_path.clone(); let src_path = msg.file_path.clone();
let lines = files.entry(src_path.clone()).or_insert_with(() => { let lines = files.entry(src_path.clone()).or_insert_with(() => {
fs::read_to_string(src_path) fs::read_to_string(src_path).expect("Unable to read mist file").lines().into_iter().map(String::from).collect()
.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 - 1).map((v) => v.trim().to_string())
} }
+18 -27
View File
@@ -1,75 +1,72 @@
pub module modules; pub module modules;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use std::fs; use std::fs;
use std::process; use std::process;
use crate::transpiler::MistConfig; use crate::transpiler::MistConfig;
#[derive(Debug)] #[derive(Debug)]
pub class Module { pub class Module
{
pub String name; pub String name;
pub PathBuf path; pub PathBuf path;
pub Vec<Module> children; pub Vec<Module> children;
pub constructor(PathBuf mist_path, MistConfig& config) { pub constructor(PathBuf mist_path, MistConfig& config)
{
self.children = Vec::new(); self.children = Vec::new();
self.name = mist_path.file_stem() self.name = mist_path.file_stem().and_then((s) => s.to_str()).expect("Failed to get module name").to_string();
.and_then((s) => s.to_str())
.expect("Failed to get module name")
.to_string();
self.path = mist_path; self.path = mist_path;
if self.path.is_dir() { if self.path.is_dir() {
let dir = self.path.clone(); let dir = self.path.clone();
let pkg_gate = self.path.join("package.mist"); let pkg_gate = self.path.join("package.mist");
if pkg_gate.exists() { if pkg_gate.exists() {
self.path = pkg_gate; self.path = pkg_gate;
} }
self.scan_directory(&dir, config); self.scan_directory(&dir, config);
} else if config.should_ignore(&self.path) { } else if config.should_ignore(&self.path) {
let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf(); let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf();
self.scan_directory(&dir, config); self.scan_directory(&dir, config);
} }
} }
void scan_directory(&mut self, Path& search_dir, MistConfig& config) { void scan_directory(&mut self, Path& search_dir, MistConfig& config)
{
let entries = match fs::read_dir(search_dir) { let entries = match fs::read_dir(search_dir) {
Ok(entries) => entries; Ok(entries) => entries,
Err(e) => { Err(e) => {
eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e); eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e);
process::exit(1); process::exit(1);
} }
}; };
for entry in entries { for entry in entries {
let entry = match entry { let entry = match entry {
Ok(entry) => entry; Ok(entry) => entry,
Err(e) => { Err(e) => {
eprintln!("error: failed to read directory entry\n {}", e); eprintln!("error: failed to read directory entry\n {}", e);
process::exit(1); process::exit(1);
} }
}; };
let child_path = entry.path(); let child_path = entry.path();
if child_path == self.path || child_path == config.package { if child_path == self.path || child_path == config.package {
continue; continue;
} }
self.children.push(Module::new(child_path, config)); self.children.push(Module::new(child_path, config));
} }
} }
pub bool is_package(&self) { pub bool is_package(&self)
{
self.path.file_name().map((v) => v.to_str()).unwrap_or_default() == Some("package.mist") self.path.file_name().map((v) => v.to_str()).unwrap_or_default() == Some("package.mist")
} }
pub PathBuf output_dir(&self, PathBuf& parent_dir) { pub PathBuf output_dir(&self, PathBuf& parent_dir)
{
if self.path.is_dir() || self.is_package() { if self.path.is_dir() || self.is_package() {
parent_dir.join(&self.name) parent_dir.join(&self.name)
} else { } else {
@@ -77,19 +74,13 @@ pub class Module {
} }
} }
pub PathBuf output_path(&self, pub PathBuf output_path(&self, PathBuf& parent_dir, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
PathBuf& parent_dir, {
Option<(
mist_parser::ast::Visibility,
mist_parser::ast::Identifier
)>& curr_mod_decl
) {
let name = if let Some((_, name)) = curr_mod_decl { let name = if let Some((_, name)) = curr_mod_decl {
&name.0 &name.0
} else { } else {
&self.name &self.name
}; };
if self.path.is_dir() || self.is_package() { if self.path.is_dir() || self.is_package() {
parent_dir.join(name).join("mod.rs") parent_dir.join(name).join("mod.rs")
} else { } else {
+128 -168
View File
@@ -1,170 +1,170 @@
pub module transpiler; pub module transpiler;
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use std::process; use std::process;
use std::time; use std::time;
use std::env; use std::env;
use mist_parser::error; use mist_parser::error;
use crate::modules; use crate::modules;
use mist_codegen::GetRust; use mist_codegen::GetRust;
use serde::Deserialize; use serde::Deserialize;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct MistConfig { pub struct MistConfig
{
pub PathBuf package, pub PathBuf package,
pub Vec<PathBuf> packages, pub Vec<PathBuf> packages,
pub String main_mods pub Vec<PathBuf> include,
pub mist_parser::MistFmtConfig fmt,
} }
impl MistConfig { impl MistConfig
pub bool should_ignore(&self, Path& path) { {
pub bool should_ignore(&self, Path& path)
{
if path == self.package { if path == self.package {
return true; return true;
} }
for pkg in &self.packages { for pkg in &self.packages {
if path.ends_with(pkg) { if path.ends_with(pkg) {
return true; return true;
} }
} }
false false
} }
} }
impl Default for MistConfig {
Self default() { impl Default for MistConfig
{
Self default()
{
Self { Self {
package: PathBuf::from("main.mist"), package: PathBuf::from("main.mist"),
packages: Vec::new(), packages: Vec::new(),
main_mods: String::new(), include: Vec::new(),
fmt: mist_parser::MistFmtConfig {
allman_bracket_style: true,
},
} }
} }
} }
pub PathBuf transpile() { pub void transpile(Path& root)
{
println!("\x1b[32m\nTranspiling\x1b[0m \x1b[94m{:?}\x1b[0m", root.file_name().unwrap_or_default());
let start = time::Instant::now(); let start = time::Instant::now();
let root = env::current_dir().expect("Unable to find project root");
let toml_path = root.join("Mist.toml"); let toml_path = root.join("Mist.toml");
let src = root.join("src"); let src = root.join("src");
let out = root.join(".mist/src"); let out = root.join(".mist/src");
let toml_content = fs::read_to_string(&toml_path).unwrap_or_else((_) => panic!("Could not read file at {:?}", toml_path));
let toml_content = fs::read_to_string(&toml_path) MistConfig mut config = toml::from_str(&toml_content).unwrap_or_else((_) => panic!("Failed to parse Mist.toml from {:?}", toml_path));
.unwrap_or_else((_) => panic!("Could not read file at {:?}", 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 { for pkg in &mut config.packages {
*pkg = src.join(&*pkg); *pkg = src.join(&*pkg);
} }
config.package = src.join(&*config.package); config.package = src.join(&*config.package);
let master = modules::Module::new(config.package.clone(), &config);
let master = modules::Module::new( master.transpile(&out, &mut config, &mut String::new());
config.package.clone(),
&config
);
master.transpile(&out, &mut config);
let elapsed = start.elapsed(); let elapsed = start.elapsed();
println!("\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m", elapsed);
println!( for incl in &config.include {
"\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m", if ends_with_star(&incl) {
elapsed let sub_crates = incl.parent().expect("Failed to get parent");
); let entries = match fs::read_dir(sub_crates) {
Ok(entries) => entries,
root
}
impl modules::Module {
(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((s) => s.to_str())
.expect("Failed to get file name");
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
return (true, String::new());
}
let dir = self.output_dir(parent_dir);
let _ = fs::create_dir_all(&dir);
let mut output = String::new();
let mut child_changed = false;
for child in &self.children {
if !config.should_ignore(&child.path) {
let out = child.transpile(&dir, config);
if out.0 {
child_changed = true;
}
output.push_str(&out.1);
}
}
if self.path == config.package {
config.main_mods = output.clone();
} else if config.should_ignore(&self.path) {
output.push_str(&config.main_mods)
}
self.write_transpile(output, parent_dir, child_changed)
}
(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);
if output.len() == 0 {
return (true, String::new());
}
let res = fs::write(&output_file, output);
if res.is_err() {
eprintln!(
"error: failed to write output {}\n {}",
output_file.display(),
res.unwrap_err(),
);
process::exit(1);
}
(false, format!("pub mod {};\n", self.name))
} else {
let source = match fs::read_to_string(&self.path) {
Ok(s) => s;
Err(e) => { Err(e) => {
eprintln!("error: failed to read file {}\n {}", self.path.display(), e); eprintln!("error: failed to read directory {}\n {}", sub_crates.display(), e);
process::exit(1); process::exit(1);
} }
}; };
for sub_crate in entries {
if let Ok(sub_crate) = sub_crate {
let sub_crate = sub_crate.path();
if fs::exists(sub_crate.join("Mist.toml")).unwrap_or_default() {
transpile(&sub_crate);
}
}
}
} else {
transpile(incl);
}
}
}
bool ends_with_star(Path& path)
{
path.file_name().and_then((name) => name.to_str()).is_some_and((name) => name.ends_with("*"))
}
impl modules::Module
{
(bool, String) transpile(&self, PathBuf& parent_dir, MistConfig mut& config, String mut& main_mods)
{
if !self.path.is_dir() && self.path.extension().and_then((v) => v.to_str()) != Some("mist") {
let file_name = self.path.file_name().and_then((s) => s.to_str()).expect("Failed to get file name");
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
return (true, String::new());
}
let dir = self.output_dir(parent_dir);
let _ = fs::create_dir_all(&dir);
let mut output = String::new();
let mut child_changed = false;
for child in &self.children {
if !config.should_ignore(&child.path) {
let out = child.transpile(&dir, config, main_mods);
if out.0 {
child_changed = true;
}
output.push_str(&out.1);
}
}
if self.path == config.package {
*main_mods = output.clone();
} else if config.should_ignore(&self.path) {
output.push_str(main_mods)
}
self.write_transpile(output, parent_dir, child_changed)
}
(bool, String) write_transpile(&self, String output, PathBuf& parent_dir, bool child_changed)
{
if self.path.is_dir() {
let output_file = self.output_path(parent_dir, &None);
if output.len() == 0 {
return (true, String::new());
}
let res = fs::write(&output_file, output);
if res.is_err() {
eprintln!("error: failed to write output {}\n {}",
output_file.display(),
res.unwrap_err(),);
process::exit(1);
}
(false, format!("pub mod {};\n", self.name))
} else {
let source = match fs::read_to_string(&self.path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
process::exit(1);
}
};
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module"); let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
let output_file = self.output_path(parent_dir, &curr_mod_decl); let output_file = self.output_path(parent_dir, &curr_mod_decl);
let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache"); let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache");
if should_change || child_changed { if should_change || child_changed {
transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl); transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl);
} }
(should_change, if let Some((vis, name)) = &curr_mod_decl { (should_change, if let Some((vis, name)) = &curr_mod_decl {
format!("{}mod {};\n", vis.get_rust(), name.get_rust()) format!("{}mod {};\n", vis.get_rust(), name.get_rust())
} else { } else {
@@ -174,141 +174,101 @@ impl modules::Module {
} }
} }
std::io::Result<bool> is_source_newer(Path& source, Path& output) { std::io::Result<bool> is_source_newer(Path& source, Path& output)
{
if !output.exists() { if !output.exists() {
return Ok(true); return Ok(true);
} }
let source_time = fs::metadata(source)?.modified()?; let source_time = fs::metadata(source)?.modified()?;
let output_time = fs::metadata(output)?.modified()?; let output_time = fs::metadata(output)?.modified()?;
Ok(source_time > output_time) Ok(source_time > output_time)
} }
pub enum TranspileError<'a> { pub enum TranspileError<'a>
{
Parse(error::ParseError<'a>), Parse(error::ParseError<'a>),
Semantic(Vec<mist_parser::semantics::SemanticError>) Semantic(Vec<mist_parser::semantics::SemanticError>),
} }
pub Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>> pub Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>> transpile_code<'a>(PathBuf& path, str 'a& source, PathBuf mut output_file, str& mod_decl, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
transpile_code<'a>( {
PathBuf& path,
str 'a& source,
PathBuf mut output_file,
str& mod_decl,
Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl
) {
if let Some((_, name)) = &curr_mod_decl { if let Some((_, name)) = &curr_mod_decl {
if output_file.file_name().map((v) => v.to_str()).unwrap_or_default() != Some("mod.rs") { if output_file.file_name().map((v) => v.to_str()).unwrap_or_default() != Some("mod.rs") {
if let Some(ext) = output_file.extension().map((e) => e.to_owned()) { if let Some(ext) = output_file.extension().map((e) => e.to_owned()) {
let mut new_name = std::ffi::OsString::from(&name.0); let mut new_name = std::ffi::OsString::from(&name.0);
new_name.push("."); new_name.push(".");
new_name.push(ext); new_name.push(ext);
output_file.set_file_name(new_name); output_file.set_file_name(new_name);
} else { } else {
output_file.set_file_name(&name.0); output_file.set_file_name(&name.0);
} }
} }
} }
let mut gc = mist_codegen::RustCodegen::new(path.clone()); let mut gc = mist_codegen::RustCodegen::new(path.clone());
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?; let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
for i in &parsed.items { for i in &parsed.items {
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?; let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
} }
gc.generate(parsed.mod_attributes); gc.generate(parsed.mod_attributes);
gc.add(mod_decl); gc.add(mod_decl);
let output = gc.generate(parsed.items); let output = gc.generate(parsed.items);
Ok((output_file, gc, output)) Ok((output_file, gc, output))
} }
pub void transpile_file( 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)
PathBuf& path, {
str& source,
PathBuf output_file,
str& mod_decl,
Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl
) {
let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) { let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) {
Ok(output) => output; Ok(output) => output,
Err(e) => { Err(e) => {
decode_err(&e, path); decode_err(&e, path);
process::exit(1); process::exit(1);
} }
}; };
let res = fs::write(&output_file, output); let res = fs::write(&output_file, output);
let output_file_map = output_file.with_extension("map.json"); let output_file_map = output_file.with_extension("map.json");
let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap()); let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap());
if res_map.is_err() { if res_map.is_err() {
eprintln!( eprintln!("error: failed to write mapping output {}\n {}",
"error: failed to write mapping output {}\n {}",
output_file_map.display(), output_file_map.display(),
res.as_ref().unwrap_err(), res.as_ref().unwrap_err(),);
);
} }
if res.is_err() { if res.is_err() {
eprintln!( eprintln!("error: failed to write output {}\n {}",
"error: failed to write output {}\n {}",
output_file.display(), output_file.display(),
res.as_ref().unwrap_err(), res.as_ref().unwrap_err(),);
);
} }
if res_map.is_err() || res.is_err() { if res_map.is_err() || res.is_err() {
process::exit(1); process::exit(1);
} }
} }
pub void decode_err<'a>(TranspileError<'a>& err, PathBuf& path) { pub void decode_err<'a>(TranspileError<'a>& err, PathBuf& path)
{
let curr_dir = std::env::current_dir().unwrap(); let curr_dir = std::env::current_dir().unwrap();
match err { match err {
TranspileError::Semantic(e_list) => { TranspileError::Semantic(e_list) => {
for e in e_list { for e in e_list {
eprintln!( eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(), path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
e.line, e.line,
e.column, e.column,
e.error_message, e.error_message,);
);
} }
} }
TranspileError::Parse(e) => { TranspileError::Parse(e) => {
match e { match e {
error::ParseError::Ast(e) => { error::ParseError::Ast(e) => {
let start_pos = e.span.start_pos().line_col(); let start_pos = e.span.start_pos().line_col();
let span = e.span.as_str(); let span = e.span.as_str();
eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
eprintln!(
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(), path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
start_pos.0, start_pos.0,
start_pos.1, start_pos.1,
e.error_message, e.error_message,
span, span,
if span.ends_with("\n") { "" } else { "\n" }, if span.ends_with("\n") { "" } else { "\n" },
"^".repeat(span.trim().len()), "^".repeat(span.trim().len()),);
);
} }
error::ParseError::PreAst(e) => { error::ParseError::PreAst(e) => {
eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e); eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e);
} }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mist-parser" name = "mist-parser"
version = "0.3.7-alpha.0" version = "0.3.7-alpha.1"
edition = "2024" edition = "2024"
description = "The Mist programming language parser" description = "The Mist programming language parser"
license = "Apache-2.0" license = "Apache-2.0"
+2 -1
View File
@@ -1,3 +1,4 @@
void main() { void main()
{
mist_analyzer::start(); mist_analyzer::start();
} }
+23 -38
View File
@@ -1,23 +1,25 @@
use std::process; use std::process;
use std::env; use std::env;
use std::fs; use std::fs;
use mist_api::builder; use mist_api::builder;
use mist_api::transpiler; use mist_api::transpiler;
void main() { void main()
{
Vec<String> args = env::args().collect(); Vec<String> args = env::args().collect();
if args.len() < 2 { if args.len() < 2 {
print_usage(); print_usage();
process::exit(1); process::exit(1);
} }
match args[1].as_str() { match args[1].as_str() {
"run" | "build" | "check" | "r" | "b" | "c" => { "run" | "build" | "check" | "r" | "b" | "c" => {
let root = transpiler::transpile(); let root = env::current_dir().expect("Unable to find project root");
transpiler::transpile(&root);
println!(""); println!("");
if builder::build(args, root) { if builder::build(args, root) {
println!("\x1b[32m\nBuild successful\x1b[0m"); println!("\x1b[32m\nBuild successful\x1b[0m");
} else { } else {
@@ -25,7 +27,8 @@ void main() {
} }
} }
"transpile" | "t" => { "transpile" | "t" => {
transpiler::transpile(); let root = env::current_dir().expect("Unable to find project root");
transpiler::transpile(&root);
} }
"init" => { "init" => {
init_project(args); init_project(args);
@@ -44,41 +47,26 @@ void main() {
} }
} }
void print_usage() { void print_usage()
{
println!("Mist - the mist compiler\n"); println!("Mist - the mist compiler\n");
println!("󰖟 View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m"); println!("󰖟 View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n"); println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
println!("usage:"); println!("usage:");
println!(" \x1b[36m mist run\x1b[0m,\x1b[36m r\x1b[0m run the project in the current directory\n"); println!(" \x1b[36m mist run\x1b[0m,\x1b[36m r\x1b[0m run the project in the current directory\n");
println!( println!(" \x1b[36m mist build\x1b[0m,\x1b[36m b\x1b[0m build the project in the current directory\n");
" \x1b[36m mist build\x1b[0m,\x1b[36m b\x1b[0m build the project in the current directory\n" println!(" \x1b[36m mist transpile\x1b[0m,\x1b[36m t\x1b[0m transpile the project in the current directory\n");
); println!(" \x1b[36m mist check\x1b[0m,\x1b[36m c\x1b[0m check the project in the current directory\n");
println!( println!(" \x1b[36m mist init\x1b[0m initialize a project in the current folder\n");
" \x1b[36m mist transpile\x1b[0m,\x1b[36m t\x1b[0m transpile the project in the current directory\n"
);
println!(
" \x1b[36m mist check\x1b[0m,\x1b[36m c\x1b[0m check the project in the current directory\n"
);
println!(
" \x1b[36m mist init\x1b[0m initialize a project in the current folder\n"
);
println!(" \x1b[36m mist version \x1b[0m print the compiler version\n"); println!(" \x1b[36m mist version \x1b[0m print the compiler version\n");
println!(" \x1b[36m mist help\x1b[0m print this message\n"); println!(" \x1b[36m mist help\x1b[0m print this message\n");
} }
void init_project(Vec<String> mut args) { void init_project(Vec<String> mut args)
{
args.remove(0); args.remove(0);
process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
process::Command::new("cargo")
.args(args)
.stdout(process::Stdio::inherit())
.stderr(process::Stdio::inherit())
.stdin(process::Stdio::inherit())
.spawn()
.expect("Failed to run cargo").wait().expect("Unable to wait");
bool is_lib = fs::metadata("src/lib.rs").is_ok(); bool is_lib = fs::metadata("src/lib.rs").is_ok();
if is_lib { if is_lib {
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs"); fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
fs::write("src/lib.mist", "fn test() {\n}").expect("Failed to create src/lib.mist"); fs::write("src/lib.mist", "fn test() {\n}").expect("Failed to create src/lib.mist");
@@ -86,20 +74,17 @@ void init_project(Vec<String> mut args) {
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs"); fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
fs::write("src/main.mist", "fn main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist"); fs::write("src/main.mist", "fn main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
} }
inject_mist_target(is_lib); inject_mist_target(is_lib);
println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n"); println!("\n\x1b[34minfo\x1b[0m: Please open Cargo.toml and adjust `\x1b[35mname\x1b[0m = ` as needed, Thank you for using Mist!\n");
} }
void inject_mist_target(bool is_lib) { void inject_mist_target(bool is_lib)
{
String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml"); String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
str& inject = if is_lib { str& inject = if is_lib {
"\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n" "\n[lib]\nname = \"my_lib\"\npath = \".mist/src/lib.rs\"\n"
} else { } else {
"\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n" "\n[[bin]]\nname = \"my_bin\"\npath = \".mist/src/main.rs\"\n"
}; };
fs::write("Cargo.toml", toml_content + inject).expect("Failed to inject to Cargo.toml");
fs::write("Cargo.toml", toml_content+inject).expect("Failed to inject to Cargo.toml"); }
}