Dino compiler: language, formatter, language server, docs, editor support
Compiler in Rust (lexer, parser, checker, C codegen), maps, chars, dino fmt, dino lsp (diagnostics, formatting, outline, definition, hover, completion, signature help), docs, examples, VS Code/Vim files. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3e2779f447
commit
eaf9567a36
117 files changed
+19970
No files matched your search
+110
@@ -0,0 +1,110 @@
|
||||
//! Ties the compiler stages together and invokes the C compiler.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::error::{Diag, PResult};
|
||||
use crate::{check, codegen_c, loader, parser};
|
||||
|
||||
/// Dino source -> C source, for a program in a single file.
|
||||
pub fn compile_to_c(src: &str) -> PResult<String> {
|
||||
let ast = parser::parse(src)?;
|
||||
let hir = check::check(&ast)?;
|
||||
Ok(codegen_c::generate(&hir))
|
||||
}
|
||||
|
||||
/// A whole program: the main file and the files it imports. `read(key)` finds a module
|
||||
/// (see `loader`). Errors come back already rendered, naming the file they are in.
|
||||
pub fn compile_project(
|
||||
main_path: &str,
|
||||
main_src: &str,
|
||||
mut read: impl FnMut(&str) -> Option<(String, String)>,
|
||||
) -> Result<String, String> {
|
||||
let mut seen: HashMap<String, (String, String)> = HashMap::new();
|
||||
let loaded = loader::load(main_src, &mut |key| {
|
||||
let found = read(key);
|
||||
if let Some((path, src)) = &found {
|
||||
seen.insert(key.to_string(), (path.clone(), src.clone()));
|
||||
}
|
||||
found
|
||||
});
|
||||
let render = |d: Diag| -> String {
|
||||
match d.file.as_deref().and_then(|k| seen.get(k)) {
|
||||
Some((path, src)) => d.render(path, src),
|
||||
None if d.file.is_some() => d.render(d.file.as_deref().unwrap(), ""),
|
||||
None => d.render(main_path, main_src),
|
||||
}
|
||||
};
|
||||
let loaded = loaded.map_err(&render)?;
|
||||
let modules: Vec<(String, crate::ast::Program)> =
|
||||
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
|
||||
let hir = check::check_project(&loaded.main, &modules).map_err(&render)?;
|
||||
Ok(codegen_c::generate(&hir))
|
||||
}
|
||||
|
||||
/// Compile the program whose main file is `path`; imports are found next to it.
|
||||
pub fn compile_file(path: &str) -> Result<String, String> {
|
||||
let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?;
|
||||
let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
compile_project(path, &src, |key| {
|
||||
let file = dir.join(format!("{}.dino", key.replace('.', "/")));
|
||||
std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s))
|
||||
})
|
||||
}
|
||||
|
||||
fn unique_name(tag: &str, ext: &str) -> PathBuf {
|
||||
// the counter makes names differ even when two threads ask in the same nanosecond
|
||||
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
std::env::temp_dir().join(format!("dino-{}-{}-{}-{}{}", std::process::id(), nanos, n, tag, ext))
|
||||
}
|
||||
|
||||
/// A path for a throw-away executable.
|
||||
pub fn temp_exe() -> PathBuf {
|
||||
unique_name("exe", if cfg!(windows) { ".exe" } else { "" })
|
||||
}
|
||||
|
||||
/// Compile C source to an executable with the system C compiler (`$CC`, else `cc`).
|
||||
pub fn build_exe(c_code: &str, out: &Path) -> Result<(), String> {
|
||||
build_exe_with(c_code, out, &["-O2", "-std=c11", "-fwrapv", "-w"])
|
||||
}
|
||||
|
||||
/// Like `build_exe`, with explicit compiler flags (used by tests to turn on strict warnings).
|
||||
pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), String> {
|
||||
let c_file = unique_name("prog", ".c");
|
||||
std::fs::write(&c_file, c_code).map_err(|e| format!("cannot write {}: {e}", c_file.display()))?;
|
||||
let cc = std::env::var("CC").unwrap_or_else(|_| "cc".to_string());
|
||||
let result = Command::new(&cc)
|
||||
.args(flags)
|
||||
.arg("-o")
|
||||
.arg(out)
|
||||
.arg(&c_file)
|
||||
.arg("-lm") // the math functions
|
||||
.output();
|
||||
let _ = std::fs::remove_file(&c_file);
|
||||
match result {
|
||||
Err(e) => Err(format!("cannot run the C compiler `{cc}`: {e}\nInstall one (gcc or clang) or set $CC.")),
|
||||
Ok(o) if !o.status.success() => Err(format!(
|
||||
"the C compiler rejected the generated code (this is a bug in Dino):\n{}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
)),
|
||||
Ok(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a whole program without building it, for editors: `main_src` is the text of the main
|
||||
/// file (it may differ from what is on disk) and `read(key)` finds the other files.
|
||||
/// The error's `file` says which module it is in (`None`: the main file).
|
||||
pub fn diagnose(
|
||||
main_src: &str,
|
||||
mut read: impl FnMut(&str) -> Option<(String, String)>,
|
||||
) -> Result<(), Diag> {
|
||||
let loaded = loader::load(main_src, &mut |key| read(key))?;
|
||||
let modules: Vec<(String, crate::ast::Program)> =
|
||||
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
|
||||
check::check_project(&loaded.main, &modules)?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user