Merge pull request #61 from mist-go/refactor-module-system

Refactor module system
This commit is contained in:
2026-06-03 16:49:13 +02:00
committed by GitHub
11 changed files with 102 additions and 373 deletions
@@ -1,36 +1,37 @@
use std::{ use <std::collections::HashMap>;
collections::HashMap, use <std::env>;
env, fs, use <std::fs>;
path::{MAIN_SEPARATOR, PathBuf}, use <std::path::MAIN_SEPARATOR>;
process::{Command, Stdio}, use <std::path::PathBuf>;
}; use <std::process::Command>;
use <std::process::Stdio>;
use cargo_metadata::{CompilerMessage, Message}; use <cargo_metadata::CompilerMessage>;
use mist_parser::rev_mapper::{RustMap, find_mapping, get_mapping}; use <cargo_metadata::Message>;
use <mist_parser::rev_mapper>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MistDiagnosticMessage { pub struct MistDiagnosticMessage {
pub message: String, pub String message,
pub file_path: PathBuf, pub PathBuf file_path,
pub file_name: String, pub String file_name,
pub line: usize, pub usize line,
pub column: usize, pub usize column,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum MistDiagnostic { pub enum MistDiagnostic {
Error(MistDiagnosticMessage), Error[MistDiagnosticMessage],
Warning(MistDiagnosticMessage), Warning[MistDiagnosticMessage],
Rust(CompilerMessage), Rust[CompilerMessage],
} }
pub fn build(mut args: Vec<String>, root: PathBuf) -> bool { 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 is_root = root == env::current_dir().expect("Failed getting env"); var is_root = root == env::current_dir().expect("Failed getting env");
let mut command = Command::new("cargo") var mut command = Command::new("cargo")
.args(args) .args(args)
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::inherit()) .stderr(Stdio::inherit())
@@ -38,63 +39,63 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
.spawn() .spawn()
.expect("Failed to run cargo"); .expect("Failed to run cargo");
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader")); var mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
let mut diagnostics = Vec::new(); var mut diagnostics = Vec::new();
let mut mapping = HashMap::new(); var mut mapping = HashMap::new();
let mist_src = format!(".mist{MAIN_SEPARATOR}src"); var mist_src = format!(".mist{MAIN_SEPARATOR}src");
for message in cargo_metadata::Message::parse_stream(&mut reader) { for (message : 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 : &msg.message.spans) {
if span.is_primary { if (span.is_primary) {
let rust_path = root.join(&span.file_name); var rust_path = root.join(&span.file_name);
let mist_file = span var mist_file = span
.file_name .file_name
.replacen(&mist_src, "src", 1) .replacen(&mist_src, "src", 1)
.trim_end_matches(".rs") .trim_end_matches(".rs")
.to_string() .to_string()
+ ".mist"; + ".mist";
let mist_path = root.join(&mist_file); var mist_path = root.join(&mist_file);
if !fs::exists(&mist_path).expect("Unable to check if mist file exists") { if (!fs::exists(&mist_path).expect("Unable to check if mist file exists")) {
diagnostics.push(MistDiagnostic::Rust(msg)); diagnostics.push(MistDiagnostic::Rust(msg));
break; break;
} }
let map = mapping.entry(rust_path.clone()).or_insert_with(|| { var map = mapping.entry(rust_path.clone()).or_insert_with(|| {
get_mapping( rev_mapper::get_mapping(
&fs::read_to_string(rust_path) &fs::read_to_string(rust_path)
.expect("Failed to read file for mapping"), .expect("Failed to read file for mapping")
) )
}); });
let mist_span = var [_, rev_mapper::MistMap[line, column]] =
find_mapping(&map, &RustMap(span.line_end, span.column_start)) rev_mapper::find_mapping(&map, &rev_mapper::RustMap(span.line_end, span.column_start))
.expect("Unable to find mapping"); .expect("Unable to find mapping");
let mist_msg = MistDiagnosticMessage { var 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 is_root { file_name: if (is_root) {
mist_file mist_file
} else { } else {
mist_path.to_string_lossy().to_string() mist_path.to_string_lossy().to_string()
}, },
file_path: mist_path, file_path: mist_path,
line: mist_span.1.0, line: line,
column: mist_span.1.1, 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))
} }
@@ -109,14 +110,14 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
} }
} }
Ok(Message::BuildFinished(finish)) => { Ok[Message::BuildFinished[finish]] => {
print_diagnostics(&diagnostics); print_diagnostics(&diagnostics);
let mut raw_reader = reader.into_inner(); var mut raw_reader = reader.into_inner();
let mut stdout = std::io::stdout(); var mut stdout = std::io::stdout();
std::io::copy(&mut raw_reader, &mut stdout) std::io::copy(&mut raw_reader, &mut stdout)
.map_err(|v| v.to_string()) .map_err(|var v| v.to_string())
.expect("(Mist) Failed to copy IO"); .expect("(Mist) Failed to copy IO");
command.wait().unwrap(); command.wait().unwrap();
@@ -124,7 +125,7 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
return finish.success; return finish.success;
} }
Ok(Message::TextLine(text)) => println!("{text}"), Ok[Message::TextLine[text]] => println!("{text}");
_ => {} _ => {}
} }
} }
@@ -132,13 +133,13 @@ pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
false false
} }
pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) { pub void print_diagnostics(Vec<MistDiagnostic>* diagnostics) {
let mut files = HashMap::new(); var mut files = HashMap::new();
for diag in diagnostics { for (diag : diagnostics) {
match diag { match (diag) {
MistDiagnostic::Error(msg) => { MistDiagnostic::Error[msg] => {
let line = get_line(&mut files, &msg); var line = get_line(&mut files, &msg);
println!( println!(
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}", "\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
@@ -150,8 +151,8 @@ pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) {
) )
} }
MistDiagnostic::Warning(msg) => { MistDiagnostic::Warning[msg] => {
let line = get_line(&mut files, &msg); var line = get_line(&mut files, &msg);
println!( println!(
"\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}", "\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
@@ -163,18 +164,18 @@ pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) {
) )
} }
MistDiagnostic::Rust(rs) => println!("{rs}"), MistDiagnostic::Rust[rs] => println!("{rs}");
} }
} }
} }
pub fn get_line( pub Option<String> get_line(
files: &mut HashMap<PathBuf, Vec<String>>, HashMap<PathBuf, Vec<String>> mut* files,
msg: &MistDiagnosticMessage, MistDiagnosticMessage* msg,
) -> Option<String> { ) {
let src_path = msg.file_path.clone(); var src_path = msg.file_path.clone();
let lines = files.entry(src_path.clone()).or_insert_with(|| { var lines = files.entry(src_path.clone()).or_insert_with(|| {
fs::read_to_string(src_path) fs::read_to_string(src_path)
.expect("Unable to read mist file") .expect("Unable to read mist file")
.lines() .lines()
@@ -183,5 +184,5 @@ pub fn get_line(
.collect() .collect()
}); });
lines.get(msg.line - 1).map(|v| v.trim().to_string()) lines.get(msg.line - 1).map(|var v| v.trim().to_string())
} }
+13 -44
View File
@@ -9,25 +9,27 @@ pub class Module {
pub PathBuf path; pub PathBuf path;
pub Vec<Self> children; pub Vec<Self> children;
pub constructor(String name, PathBuf mist_path, PathBuf rust_path) { pub constructor(PathBuf mist_path) {
self.children = new Vec(); self.children = new Vec();
self.name = name; self.name = mist_path.file_stem()
.and_then(|var 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()) {
PathBuf dir = self.path.clone(); PathBuf dir = self.path.clone();
// Behavior 2: It's a directory node. Check for gateway package.mist first.
PathBuf pkg_gate = self.path.join("package.mist"); PathBuf 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, &rust_path); self.scan_directory(&dir);
} }
} }
void scan_directory(self mut*, Path* search_dir, Path* rust_path) { void scan_directory(self mut*, Path* search_dir) {
var entries = match (fs::read_dir(search_dir)) { var entries = match (fs::read_dir(search_dir)) {
Ok[entries] => entries; Ok[entries] => entries;
Err[e] => { Err[e] => {
@@ -51,18 +53,7 @@ pub class Module {
continue; continue;
} }
String child_name = child_path.file_stem() self.children.push(new Module(child_path));
.and_then(|var s| s.to_str())
.expect("Failed to get module name")
.to_string();
PathBuf child_output = rust_path.join(&child_name).with_extension("rs");
if (!child_path.is_dir() && should_skip(&child_path, &child_output)) {
continue;
}
self.children.push(new Module(child_name, child_path, child_output));
} }
} }
@@ -83,35 +74,13 @@ pub class Module {
} }
} }
pub Module master_package(PathBuf mist_path, PathBuf rust_path) { pub Module master_package(PathBuf mist_path) {
String name = mist_path.file_stem() var mut root_mod = new Module(mist_path.clone());
.and_then(|var s| s.to_str())
.expect("Failed to get module name")
.to_string();
var mut root_mod = new Module(name, mist_path.clone(), rust_path.clone()); Path* parent_dir = mist_path.parent()
.expect("Failed to get parent directory of root file");
if (!mist_path.is_dir()) { root_mod.scan_directory(parent_dir);
PathBuf parent_dir = mist_path.parent()
.expect("Failed to get parent directory of root file")
.to_path_buf();
root_mod.scan_directory(&parent_dir, &rust_path);
}
root_mod root_mod
} }
bool should_skip(Path* source, Path* output) {
var src_time = fs::metadata(source)
.ok()
.and_then(|var v| v.modified().ok());
var out_time = fs::metadata(output)
.ok()
.and_then(|var v| v.modified().ok());
out_time
.map(|var out_time| out_time >= src_time.unwrap())
.unwrap_or_default()
}
+16 -3
View File
@@ -1,5 +1,4 @@
use <std::fs>; use <std::fs>;
use <std::path::Path>;
use <std::path::PathBuf>; use <std::path::PathBuf>;
use <std::process>; use <std::process>;
use <std::time>; use <std::time>;
@@ -8,7 +7,7 @@ use <std::env>;
use <mist_parser::error>; use <mist_parser::error>;
use <crate::modules>; use <crate::modules>;
pub PathBuf build(bool force) { pub PathBuf transpile() {
var start = time::Instant::now(); var start = time::Instant::now();
var root = env::current_dir().expect("Unable to find project root"); var root = env::current_dir().expect("Unable to find project root");
@@ -16,7 +15,7 @@ pub PathBuf build(bool force) {
PathBuf src = root.join("src"); PathBuf src = root.join("src");
PathBuf out = root.join(".mist/src"); PathBuf out = root.join(".mist/src");
var master = modules::master_package(src.join("main.mist"), out.join("main.rs")); var master = modules::master_package(src.join("main.mist"));
master.transpile(&out); master.transpile(&out);
@@ -32,6 +31,16 @@ pub PathBuf build(bool force) {
impl modules::Module { impl modules::Module {
String transpile(self*, PathBuf* parent_dir) { String transpile(self*, PathBuf* parent_dir) {
if (!self.path.is_dir() && self.path.extension().and_then(|var v| v.to_str()) != Some("mist")) {
var file_name = self.path.file_name()
.and_then(|var 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 String::new();
}
PathBuf dir = self.output_dir(&parent_dir); PathBuf dir = self.output_dir(&parent_dir);
PathBuf output_file = self.output_path(&parent_dir); PathBuf output_file = self.output_path(&parent_dir);
@@ -44,6 +53,10 @@ impl modules::Module {
} }
if (self.path.is_dir()) { if (self.path.is_dir()) {
if (output.len() == 0) {
return String::new();
}
var res = fs::write(&output_file, output); var res = fs::write(&output_file, output);
if (res.is_err()) { if (res.is_err()) {
-123
View File
@@ -1,123 +0,0 @@
use <super::task>;
use <super::logger>;
use <super::event>;
pub class Application {
String name;
Vec<task::Task> tasks;
Vec<String> plugins;
logger::Logger logger;
bool running;
i32 ticks;
pub constructor(str* name) {
self.name = name.to_string();
self.tasks = new Vec();
self.plugins = new Vec();
self.logger = new logger::Logger("app");
self.running = false;
self.ticks = 0;
}
pub void boot(self mut*) {
self.logger.info("booting application");
self.running = true;
self.emit(event::Event::Startup);
}
pub void run(self mut*) {
while(self.running) {
self.tick();
if(self.ticks >= 5) {
self.shutdown();
}
}
}
void tick(self mut*) {
self.logger.info("tick");
self.ticks++;
var task = task::create_task("background-job");
self.tasks.push(task);
println!("tasks: {}", self.tasks.len());
}
pub void shutdown(self mut*) {
self.emit(event::Event::Shutdown);
self.logger.warning("shutdown");
self.running = false;
}
pub void register_plugin(self mut*, String name) {
self.plugins.push(name.clone());
self.emit(event::Event::PluginLoaded(name));
}
void emit(self*, event::Event event) {
match(event) {
event::Event::Startup => {
self.logger.info("startup event");
}
event::Event::Shutdown => {
self.logger.info("shutdown event");
}
event::Event::PluginLoaded[name] => {
println!("plugin loaded: {}", name);
}
event::Event::TaskExecuted[name] => {
println!("task executed: {}", name);
}
event::Event::Error[message] => {
self.logger.error(&message);
}
}
}
}
i32 test_stmt() {
if (0 == 0) {
0
}
else {
1
}
}
void loops_test() {
for (x : 0..10) {
println!("{x}");
}
for (var mut i = 0; i < 10; i++) {
println!("{i}");
}
var i = 0;
while (i == 1) {
println!("hi");
}
loop {
println!("loop!");
}
}
-7
View File
@@ -1,7 +0,0 @@
pub enum Event {
Startup,
Shutdown,
TaskExecuted[String],
PluginLoaded[String],
Error[String],
}
-72
View File
@@ -1,72 +0,0 @@
use <std::fmt::Formatter>;
use <std::fmt>;
pub trait TestLogging<T: fmt::Display>: fmt::Display {
String get(self*);
}
pub enum LogLevel {
Info,
Warning,
Error,
}
impl fmt::Display for LogLevel {
fmt::Result fmt(self*, Formatter<'_> mut* f) {
match (self) {
LogLevel::Info => write!(f, "[INFO]");
LogLevel::Warning => write!(f, "[WARN]");
LogLevel::Error => write!(f, "[ERROR]");
}
}
}
impl TestLogging<LogLevel> for LogLevel {
String get(self*) {
return format!("{self}");
}
}
pub class Logger {
String prefix;
pub constructor(str* prefix) {
self.prefix = prefix.to_string();
}
pub void info(self*, str* message) {
self.log(LogLevel::Info, message);
}
pub void warning(self*, str* message) {
self.log(LogLevel::Warning, message);
}
pub void error(self*, str* message) {
self.log(LogLevel::Error, message);
}
void log(self*, LogLevel level, str* message) {
match(level) {
LogLevel::Info => {
println!("{level} {} {}", self.prefix, message);
}
LogLevel::Warning => {
println!("{} {} {}", level.get(), self.prefix, message);
}
LogLevel::Error => {
println!("{level} {} {}", self.prefix, message);
}
}
}
impl fmt::Display {
fmt::Result fmt(self*, Formatter<'_> mut* f) {
write!(f, "logger ({})", self.prefix)
}
}
}
+1 -20
View File
@@ -1,22 +1,3 @@
void main() { void main() {
var mut app_instance = new app::Application("mist-app"); test_package::hello();
app_instance.boot();
app_instance.run();
}
void do_stuff() {
vec!(1, 2, 3).into_iter().map(Option<i32> |var v| {Some(v)}).collect::<Vec<_>>();
if (43==69) testing1();
}
i32 testing1() {
i32 v = if (0 == 0) {
0
} else {
1
};
v
} }
-16
View File
@@ -1,16 +0,0 @@
pub struct PluginInfo {
pub String name,
pub String version,
}
pub class PluginRegistry<T> {
T plugins;
pub constructor(T plugins) {
self.plugins = plugins;
}
pub T plugins(self) {
return self.plugins;
}
}
-20
View File
@@ -1,20 +0,0 @@
pub enum TaskState {
Pending,
Running,
Finished,
Failed,
}
pub struct Task {
pub String name,
pub TaskState state,
pub i32 executions,
}
pub Task create_task(str* name) {
Task {
name: name.to_string(),
state: TaskState::Pending,
executions: 0,
}
}
+3
View File
@@ -0,0 +1,3 @@
pub void hello() {
println!("Hello")
}
+2 -2
View File
@@ -14,7 +14,7 @@ void main() {
match (args[1].as_str()) { match (args[1].as_str()) {
"run" | "build" | "check" | "r" | "b" | "c" => { "run" | "build" | "check" | "r" | "b" | "c" => {
var root = transpiler::build(false); var root = transpiler::transpile();
println!(""); println!("");
@@ -25,7 +25,7 @@ void main() {
} }
} }
"transpile" | "t" => { "transpile" | "t" => {
transpiler::build(args.get(2).is_some()); transpiler::transpile();
} }
"init" => { "init" => {
init_project(args); init_project(args);