Separated mist api
This commit is contained in:
@@ -4,7 +4,12 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.228", features = ["serde_derive"] }
|
||||
serde_json = "1.0.149"
|
||||
cargo_metadata = "0.23.1"
|
||||
mist-parser = { workspace = true }
|
||||
mist-codegen = { workspace = true }
|
||||
|
||||
[lib]
|
||||
name = "mist-api"
|
||||
name = "mist_api"
|
||||
path = ".mist/src/lib.rs"
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env, fs,
|
||||
path::{MAIN_SEPARATOR, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use cargo_metadata::{CompilerMessage, Message};
|
||||
use mist_parser::rev_mapper::{RustMap, find_mapping, get_mapping};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MistDiagnosticMessage {
|
||||
pub message: String,
|
||||
pub file_path: PathBuf,
|
||||
pub file_name: String,
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum MistDiagnostic {
|
||||
Error(MistDiagnosticMessage),
|
||||
Warning(MistDiagnosticMessage),
|
||||
Rust(CompilerMessage),
|
||||
}
|
||||
|
||||
pub fn build(mut args: Vec<String>, root: PathBuf) -> bool {
|
||||
args.remove(0);
|
||||
args.insert(1, "--message-format=json".to_string());
|
||||
|
||||
let is_root = root == env::current_dir().expect("Failed getting env");
|
||||
|
||||
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 diagnostics = Vec::new();
|
||||
|
||||
let mut mapping = HashMap::new();
|
||||
|
||||
let mist_src = format!(".mist{MAIN_SEPARATOR}src");
|
||||
|
||||
for message in cargo_metadata::Message::parse_stream(&mut reader) {
|
||||
match message {
|
||||
Ok(Message::CompilerMessage(msg)) => {
|
||||
for span in &msg.message.spans {
|
||||
if span.is_primary {
|
||||
let rust_path = root.join(&span.file_name);
|
||||
|
||||
let mist_file = span
|
||||
.file_name
|
||||
.replacen(&mist_src, "src", 1)
|
||||
.trim_end_matches(".rs")
|
||||
.to_string()
|
||||
+ ".mist";
|
||||
|
||||
let mist_path = root.join(&mist_file);
|
||||
|
||||
if !fs::exists(&mist_path).expect("Unable to check if mist file exists") {
|
||||
diagnostics.push(MistDiagnostic::Rust(msg));
|
||||
break;
|
||||
}
|
||||
|
||||
let map = mapping.entry(rust_path.clone()).or_insert_with(|| {
|
||||
get_mapping(
|
||||
&fs::read_to_string(rust_path)
|
||||
.expect("Failed to read file for mapping"),
|
||||
)
|
||||
});
|
||||
|
||||
let mist_span =
|
||||
find_mapping(&map, &RustMap(span.line_end, span.column_start))
|
||||
.expect("Unable to find mapping");
|
||||
|
||||
let mist_msg = MistDiagnosticMessage {
|
||||
message: format!(
|
||||
"{}: {}",
|
||||
msg.message.message,
|
||||
span.label.clone().unwrap_or_default()
|
||||
),
|
||||
file_name: if is_root {
|
||||
mist_file
|
||||
} else {
|
||||
mist_path.to_string_lossy().to_string()
|
||||
},
|
||||
file_path: mist_path,
|
||||
line: mist_span.1.0,
|
||||
column: mist_span.1.1,
|
||||
};
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Message::BuildFinished(finish)) => {
|
||||
print_diagnostics(&diagnostics);
|
||||
|
||||
let mut raw_reader = reader.into_inner();
|
||||
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");
|
||||
|
||||
command.wait().unwrap();
|
||||
|
||||
return finish.success;
|
||||
}
|
||||
|
||||
Ok(Message::TextLine(text)) => println!("{text}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub fn print_diagnostics(diagnostics: &Vec<MistDiagnostic>) {
|
||||
let mut files = HashMap::new();
|
||||
|
||||
for diag in diagnostics {
|
||||
match diag {
|
||||
MistDiagnostic::Error(msg) => {
|
||||
let line = get_line(&mut files, &msg);
|
||||
|
||||
println!(
|
||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
|
||||
msg.file_name,
|
||||
msg.line,
|
||||
msg.column,
|
||||
msg.message,
|
||||
line.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
MistDiagnostic::Warning(msg) => {
|
||||
let line = get_line(&mut files, &msg);
|
||||
|
||||
println!(
|
||||
"\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
|
||||
msg.file_name,
|
||||
msg.line,
|
||||
msg.column,
|
||||
msg.message,
|
||||
line.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
MistDiagnostic::Rust(rs) => println!("{rs}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_line(
|
||||
files: &mut HashMap<PathBuf, Vec<String>>,
|
||||
msg: &MistDiagnosticMessage,
|
||||
) -> Option<String> {
|
||||
let src_path = msg.file_path.clone();
|
||||
|
||||
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())
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
void test() {
|
||||
}
|
||||
pub mod builder;
|
||||
pub mod transpiler;
|
||||
@@ -0,0 +1,162 @@
|
||||
use <std::fs>;
|
||||
use <std::path::Path>;
|
||||
use <std::path::PathBuf>;
|
||||
use <std::process>;
|
||||
use <std::time>;
|
||||
use <std::env>;
|
||||
|
||||
use <mist_parser::error>;
|
||||
|
||||
pub PathBuf build(bool force) {
|
||||
var start = time::Instant::now();
|
||||
|
||||
var root = env::current_dir().expect("Unable to find project root");
|
||||
|
||||
PathBuf src = root.join("src");
|
||||
PathBuf out = root.join(".mist/src");
|
||||
|
||||
build_dir(&root, &src, &src, &out, force);
|
||||
|
||||
var elapsed = start.elapsed();
|
||||
|
||||
println!(
|
||||
"\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m",
|
||||
elapsed
|
||||
);
|
||||
|
||||
root
|
||||
}
|
||||
|
||||
void build_dir(Path* root, Path* base_src, Path* current, Path* out, bool force) {
|
||||
var entries = match (fs::read_dir(current)) {
|
||||
Ok[entries] => entries;
|
||||
Err[e] => {
|
||||
eprintln!(
|
||||
"error: failed to read directory {}\n {}",
|
||||
current.display(),
|
||||
e
|
||||
);
|
||||
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
for (entry : entries) {
|
||||
var entry = match (entry) {
|
||||
Ok[entry] => entry;
|
||||
Err[e] => {
|
||||
eprintln!("error: failed to read directory entry\n {}", e);
|
||||
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
PathBuf path = entry.path();
|
||||
|
||||
if (path.is_dir()) {
|
||||
build_dir(root, base_src, &path, out, force);
|
||||
continue;
|
||||
}
|
||||
|
||||
Path* relative = path.strip_prefix(base_src).expect("Failed to strip base src from path");
|
||||
|
||||
if (path.extension().and_then(|var e| e.to_str()) != Some("mist")) {
|
||||
PathBuf dest = out.join(relative);
|
||||
|
||||
Option<Path*> parent = dest.parent();
|
||||
|
||||
if (parent.is_some()) {
|
||||
fs::create_dir_all(parent.unwrap()).expect("failed to create output directory");
|
||||
}
|
||||
|
||||
if (!force && should_skip(&path, &dest)) {
|
||||
continue
|
||||
}
|
||||
|
||||
fs::copy(&path, dest).expect("Failed to copy non-mist file");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
PathBuf output_file = out.join(relative).with_extension("rs");
|
||||
|
||||
if (!force && should_skip(&path, &output_file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Option<Path*> parent = output_file.parent();
|
||||
|
||||
if (parent.is_some()) {
|
||||
fs::create_dir_all(parent.unwrap()).expect("failed to create output directory");
|
||||
}
|
||||
|
||||
String source = match (fs::read_to_string(&path)) {
|
||||
Ok[s] => s;
|
||||
Err[e] => {
|
||||
eprintln!("error: failed to read file {}\n {}", path.display(), e);
|
||||
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
var mut gc = mist_codegen::RustCodegen::new();
|
||||
|
||||
String output = gc.generate(match (mist_parser::parse(&source)) {
|
||||
Ok[ast] => ast;
|
||||
Err[e] => {
|
||||
match (e) {
|
||||
error::ParseError::Ast[e] => {
|
||||
var start_pos = e.span.start_pos().line_col();
|
||||
|
||||
var span = e.span.as_str();
|
||||
|
||||
eprintln!(
|
||||
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
|
||||
path.as_os_str().display(),
|
||||
start_pos.0,
|
||||
start_pos.1,
|
||||
e.error_message,
|
||||
span,
|
||||
if span.ends_with("\n") { "" } else { "\n" },
|
||||
"^".repeat(span.trim().len()),
|
||||
);
|
||||
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
error::ParseError::PreAst[e] => {
|
||||
eprintln!("error: parse failed in {}\n{}", path.display(), e);
|
||||
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user