added domains into crates
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "prometeu-cli"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "prometeu"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "prometeu-runtime"
|
||||
path = "src/bin/prometeu-runtime.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "prometeuc"
|
||||
path = "src/bin/prometeuc.rs"
|
||||
|
||||
[package.metadata.dist]
|
||||
dist = true
|
||||
include = [
|
||||
"../../../VERSION.txt",
|
||||
"../../../dist-staging/devtools/debugger-protocol"
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
prometeu-host-desktop-winit = { path = "../../host/prometeu-host-desktop-winit" }
|
||||
prometeu-compiler = { path = "../../compiler/prometeu-compiler" }
|
||||
anyhow = "1.0.100"
|
||||
@@ -0,0 +1,16 @@
|
||||
# PROMETEU CLI (Dispatcher)
|
||||
|
||||
The `prometeu` binary acts as the unified front-end for the ecosystem. It does not implement the execution or compilation logic but knows where to find the binaries that do.
|
||||
|
||||
## Commands
|
||||
|
||||
- `prometeu run <cart>`: Runs a cartridge using the available runtime.
|
||||
- `prometeu debug <cart> [--port <p>]`: Starts execution in debug mode.
|
||||
- `prometeu build <projectDir>`: Calls the `prometeuc` compiler.
|
||||
- `prometeu verify c <projectDir>`: Calls the `prometeuc` compiler.
|
||||
- `prometeu pack <cartDir>`: (Planned) Calls the `prometeup` packager.
|
||||
- `prometeu verify p <cartDir>`: (Planned) Calls the `prometeup` packager.
|
||||
|
||||
## How it works
|
||||
|
||||
The dispatcher locates sibling binaries (`prometeu-host-desktop-winit`, `prometeuc`, etc.) in the same directory where it is installed. It inherits `stdin`, `stdout`, and `stderr`, and propagates the exit code of the called process.
|
||||
@@ -0,0 +1 @@
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> { prometeu_host_desktop_winit::run() }
|
||||
@@ -0,0 +1 @@
|
||||
fn main() -> anyhow::Result<()> { prometeu_compiler::run() }
|
||||
@@ -0,0 +1,176 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// PROMETEU Dispatcher (CLI).
|
||||
///
|
||||
/// The main entry point for the user. This binary does not implement
|
||||
/// compilation or execution logic itself; instead, it acts as a smart
|
||||
/// front-end that locates and dispatches commands to specialized
|
||||
/// components like `prometeu-host-desktop-winit` or `prometeu-compiler`.
|
||||
#[derive(Parser)]
|
||||
#[command(name = "prometeu")]
|
||||
#[command(about = "Dispatcher for the Prometeu ecosystem", long_about = None)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Option<Commands>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Executes a cartridge using the available runtime.
|
||||
Run {
|
||||
/// Path to the cartridge (directory or .pmc file).
|
||||
cart: String,
|
||||
},
|
||||
/// Executes a cartridge in Assisted Mode (Debug).
|
||||
/// The runtime will wait for a DevTools connection before starting.
|
||||
Debug {
|
||||
/// Path to the cartridge.
|
||||
cart: String,
|
||||
/// TCP port for the DevTools server (default: 7777).
|
||||
#[arg(long, default_value_t = 7777)]
|
||||
port: u16,
|
||||
},
|
||||
/// Compiles a source project into a cartridge (PBC).
|
||||
Build {
|
||||
/// Project source directory.
|
||||
project_dir: String,
|
||||
|
||||
/// Whether to explain the dependency resolution process.
|
||||
#[arg(long)]
|
||||
explain_deps: bool,
|
||||
},
|
||||
/// Packages a cartridge directory into a distributable .pmc file.
|
||||
Pack {
|
||||
/// Cartridge directory.
|
||||
cart_dir: String,
|
||||
},
|
||||
/// Diagnostic commands to verify project or cartridge integrity.
|
||||
Verify {
|
||||
#[command(subcommand)]
|
||||
target: VerifyCommands,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum VerifyCommands {
|
||||
/// Verifies a project
|
||||
C {
|
||||
/// Project directory
|
||||
project_dir: String,
|
||||
|
||||
/// Whether to explain the dependency resolution process.
|
||||
#[arg(long)]
|
||||
explain_deps: bool,
|
||||
},
|
||||
/// Verifies a cartridge or PMC file
|
||||
P {
|
||||
/// Path to the cartridge or PMC
|
||||
cart_or_pmc: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
let exe_dir = match env::current_exe() {
|
||||
Ok(exe_path) => exe_path.parent().unwrap_or_else(|| Path::new("../../../..")).to_path_buf(),
|
||||
Err(e) => {
|
||||
eprintln!("Error obtaining executable path: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
match cli.command {
|
||||
Some(Commands::Run { cart }) => {
|
||||
dispatch(&exe_dir, "prometeu-runtime", &["--run", &cart]);
|
||||
}
|
||||
Some(Commands::Debug { cart, port }) => {
|
||||
dispatch(
|
||||
&exe_dir,
|
||||
"prometeu-runtime",
|
||||
&["--debug", &cart, "--port", &port.to_string()],
|
||||
);
|
||||
}
|
||||
Some(Commands::Build { project_dir, explain_deps }) => {
|
||||
let mut args = vec!["build", &project_dir];
|
||||
if explain_deps {
|
||||
args.push("--explain-deps");
|
||||
}
|
||||
dispatch(&exe_dir, "prometeuc", &args);
|
||||
}
|
||||
Some(Commands::Pack { .. }) => {
|
||||
not_implemented("pack", "prometeup");
|
||||
}
|
||||
Some(Commands::Verify { target }) => match target {
|
||||
VerifyCommands::C { project_dir, explain_deps } => {
|
||||
let mut args = vec!["verify", &project_dir];
|
||||
if explain_deps {
|
||||
args.push("--explain-deps");
|
||||
}
|
||||
dispatch(&exe_dir, "prometeuc", &args);
|
||||
}
|
||||
VerifyCommands::P { .. } => not_implemented("verify p", "prometeup"),
|
||||
},
|
||||
None => {
|
||||
use clap::CommandFactory;
|
||||
Cli::command().print_help().unwrap();
|
||||
println!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_binary_path(dir: &Path, name: &str) -> PathBuf {
|
||||
let mut path = dir.join(name);
|
||||
if cfg!(target_os = "windows") {
|
||||
path.set_extension("exe");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn dispatch(exe_dir: &Path, bin_name: &str, args: &[&str]) {
|
||||
let bin_path = get_binary_path(exe_dir, bin_name);
|
||||
|
||||
if !bin_path.exists() {
|
||||
eprintln!(
|
||||
"prometeu: command '{}' is not yet available in this distribution on {}",
|
||||
match bin_name {
|
||||
"prometeu-runtime" => "run/debug",
|
||||
"prometeuc" => "build/verify c",
|
||||
"prometeup" => "pack/verify p",
|
||||
_ => bin_name,
|
||||
}, exe_dir.display()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
execute_bin(&bin_path, args);
|
||||
}
|
||||
|
||||
fn execute_bin(bin_path: &Path, args: &[&str]) {
|
||||
let status = Command::new(bin_path)
|
||||
.args(args)
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.status();
|
||||
|
||||
match status {
|
||||
Ok(status) => {
|
||||
std::process::exit(status.code().unwrap_or(0));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error executing {}: {}", bin_path.display(), e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn not_implemented(cmd: &str, _bin_name: &str) {
|
||||
eprintln!(
|
||||
"prometeu: command '{}' is not yet available in this distribution",
|
||||
cmd
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "prometeu-lsp"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
tower-lsp = "0.20"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-util = { version = "0.7" }
|
||||
prometeu-analysis = { path = "../../compiler/prometeu-analysis" }
|
||||
prometeu-compiler = { path = "../../compiler/prometeu-compiler" }
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use prometeu_analysis::FileDB;
|
||||
use prometeu_analysis::ids::{FileId, ProjectId};
|
||||
use std::collections::HashMap;
|
||||
use crate::rebuild::LspDiagnostic;
|
||||
use crate::rebuild::FlatSymbol;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AnalysisDb {
|
||||
pub file_db: FileDB,
|
||||
pub file_to_project: HashMap<FileId, ProjectId>,
|
||||
|
||||
// Os campos abaixo serão conectados conforme PR-03/04/05 (podem começar como None)
|
||||
// pub ast: Option<AstArena>,
|
||||
// pub symbols: Option<SymbolArena>,
|
||||
// pub types: Option<TypeArena>,
|
||||
// pub diagnostics: Vec<Diagnostic>,
|
||||
|
||||
/// Incrementa a cada rebuild concluído com sucesso
|
||||
pub revision: u64,
|
||||
|
||||
/// Cancel token do último rebuild em progresso (se houver)
|
||||
pub active_rebuild: Option<CancellationToken>,
|
||||
|
||||
/// Último snapshot bom (consultado pelos handlers LSP)
|
||||
pub last_good: Option<AnalysisSnapshot>,
|
||||
}
|
||||
|
||||
pub type SharedDb = Arc<RwLock<AnalysisDb>>;
|
||||
|
||||
impl AnalysisDb {
|
||||
pub fn project_for_file(&self, file: FileId) -> Option<ProjectId> {
|
||||
self.file_to_project.get(&file).copied()
|
||||
}
|
||||
|
||||
/// Returns all known file ids in the FileDB.
|
||||
pub fn file_ids(&self) -> Vec<FileId> {
|
||||
// delegate to FileDB helper (added in prometeu-analysis)
|
||||
self.file_db.all_files()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct AnalysisSnapshot {
|
||||
/// Diagnostics por arquivo (URI LSP → diagnostics já convertidos)
|
||||
pub diagnostics_by_uri: HashMap<String, Vec<LspDiagnostic>>,
|
||||
/// Lista “flatten” de símbolos para workspaceSymbol/documentSymbol
|
||||
pub symbols_flat: Vec<FlatSymbol>,
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tower_lsp::{Client, LspService, Server};
|
||||
use tower_lsp::lsp_types as lsp;
|
||||
|
||||
mod analysis_db;
|
||||
mod rebuild;
|
||||
|
||||
use analysis_db::SharedDb;
|
||||
|
||||
struct Backend {
|
||||
db: SharedDb,
|
||||
client: Client,
|
||||
}
|
||||
|
||||
#[tower_lsp::async_trait]
|
||||
impl tower_lsp::LanguageServer for Backend {
|
||||
async fn initialize(
|
||||
&self,
|
||||
_: tower_lsp::lsp_types::InitializeParams,
|
||||
) -> tower_lsp::jsonrpc::Result<tower_lsp::lsp_types::InitializeResult> {
|
||||
Ok(tower_lsp::lsp_types::InitializeResult {
|
||||
capabilities: tower_lsp::lsp_types::ServerCapabilities {
|
||||
text_document_sync: Some(
|
||||
tower_lsp::lsp_types::TextDocumentSyncCapability::Kind(
|
||||
tower_lsp::lsp_types::TextDocumentSyncKind::FULL,
|
||||
),
|
||||
),
|
||||
// MVP capabilities only (PR-08):
|
||||
definition_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
|
||||
document_symbol_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
|
||||
// workspace_symbol is not available in tower-lsp 0.20 trait
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn initialized(&self, _: tower_lsp::lsp_types::InitializedParams) {}
|
||||
|
||||
async fn shutdown(&self) -> tower_lsp::jsonrpc::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// didOpen: upsert texto, solicita rebuild
|
||||
async fn did_open(&self, params: tower_lsp::lsp_types::DidOpenTextDocumentParams) {
|
||||
let uri = params.text_document.uri.to_string();
|
||||
let text = params.text_document.text;
|
||||
{
|
||||
let mut guard = self.db.write().await;
|
||||
guard.file_db.upsert(&uri, text);
|
||||
}
|
||||
rebuild::request_rebuild(self.db.clone(), self.client.clone()).await;
|
||||
}
|
||||
|
||||
// didChange (FULL): receber conteúdo completo e upsert
|
||||
async fn did_change(&self, params: tower_lsp::lsp_types::DidChangeTextDocumentParams) {
|
||||
let uri = params.text_document.uri.to_string();
|
||||
// Full-sync: esperamos 1 conteúdo completo
|
||||
if let Some(change) = params.content_changes.into_iter().last() {
|
||||
let text = change.text;
|
||||
let mut guard = self.db.write().await;
|
||||
guard.file_db.upsert(&uri, text);
|
||||
}
|
||||
rebuild::request_rebuild(self.db.clone(), self.client.clone()).await;
|
||||
}
|
||||
|
||||
// didClose: opcionalmente remover do db e limpar diagnostics
|
||||
async fn did_close(&self, params: tower_lsp::lsp_types::DidCloseTextDocumentParams) {
|
||||
let uri = params.text_document.uri;
|
||||
// Estratégia simples: manter FileDB para estabilidade de IDs, mas limpar diagnostics
|
||||
let _ = self
|
||||
.client
|
||||
.publish_diagnostics(uri.clone(), vec![], Some(0))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn goto_definition(
|
||||
&self,
|
||||
params: tower_lsp::lsp_types::GotoDefinitionParams,
|
||||
) -> tower_lsp::jsonrpc::Result<Option<tower_lsp::lsp_types::GotoDefinitionResponse>> {
|
||||
let tdp = params.text_document_position_params;
|
||||
let uri = tdp.text_document.uri;
|
||||
let pos = tdp.position;
|
||||
|
||||
let guard = self.db.read().await;
|
||||
// Map URI to current text and index
|
||||
let Some(fid) = guard.file_db.file_id(uri.as_str()) else { return Ok(None) };
|
||||
let text = guard.file_db.text(fid).to_string();
|
||||
let idx = prometeu_analysis::TextIndex::new(&text);
|
||||
let byte = idx.lsp_to_byte(pos.line, pos.character);
|
||||
let ident = ident_at(&text, byte);
|
||||
|
||||
if let Some(name) = ident {
|
||||
if let Some(snap) = &guard.last_good {
|
||||
let mut hits: Vec<lsp::Location> = Vec::new();
|
||||
for s in &snap.symbols_flat {
|
||||
if s.name == name {
|
||||
hits.push(s.location.clone());
|
||||
}
|
||||
}
|
||||
if !hits.is_empty() {
|
||||
return Ok(Some(lsp::GotoDefinitionResponse::Array(hits)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
||||
// MVP stubs: documentSymbol/workspaceSymbol/definition retornam vazio até PRs seguintes
|
||||
async fn document_symbol(
|
||||
&self,
|
||||
params: tower_lsp::lsp_types::DocumentSymbolParams,
|
||||
) -> tower_lsp::jsonrpc::Result<Option<tower_lsp::lsp_types::DocumentSymbolResponse>> {
|
||||
let uri = params.text_document.uri;
|
||||
let guard = self.db.read().await;
|
||||
if let Some(snap) = &guard.last_good {
|
||||
let mut items: Vec<lsp::SymbolInformation> = Vec::new();
|
||||
for s in &snap.symbols_flat {
|
||||
if s.location.uri == uri {
|
||||
items.push(lsp::SymbolInformation {
|
||||
name: s.name.clone(),
|
||||
kind: s.kind,
|
||||
location: s.location.clone(),
|
||||
tags: None,
|
||||
deprecated: None,
|
||||
container_name: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
return Ok(Some(lsp::DocumentSymbolResponse::Flat(items)));
|
||||
}
|
||||
Ok(Some(lsp::DocumentSymbolResponse::Flat(vec![])))
|
||||
}
|
||||
|
||||
// async fn workspace_symbol(
|
||||
// &self,
|
||||
// params: lsp::WorkspaceSymbolParams,
|
||||
// ) -> tower_lsp::jsonrpc::Result<Option<Vec<lsp::SymbolInformation>>> {
|
||||
// let query = params.query.to_lowercase();
|
||||
// let guard = self.db.read().await;
|
||||
// if let Some(snap) = &guard.last_good {
|
||||
// let mut out: Vec<lsp::SymbolInformation> = Vec::new();
|
||||
// for s in &snap.symbols_flat {
|
||||
// if s.name.to_lowercase().contains(&query) {
|
||||
// out.push(lsp::SymbolInformation {
|
||||
// name: s.name.clone(),
|
||||
// kind: s.kind,
|
||||
// location: s.location.clone(),
|
||||
// tags: None,
|
||||
// deprecated: None,
|
||||
// container_name: None,
|
||||
// });
|
||||
// if out.len() >= 50 { break; }
|
||||
// }
|
||||
// }
|
||||
// return Ok(Some(out));
|
||||
// }
|
||||
// Ok(Some(vec![]))
|
||||
// }
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let stdin = tokio::io::stdin();
|
||||
let stdout = tokio::io::stdout();
|
||||
|
||||
let db: SharedDb = Arc::new(RwLock::new(analysis_db::AnalysisDb::default()));
|
||||
|
||||
let (service, socket) = LspService::new(|client| Backend { db: db.clone(), client });
|
||||
Server::new(stdin, stdout, socket).serve(service).await;
|
||||
}
|
||||
|
||||
// Simple textual identifier extraction for MVP definition lookup.
|
||||
fn ident_at(text: &str, byte: u32) -> Option<String> {
|
||||
let b = byte as usize;
|
||||
if b > text.len() { return None; }
|
||||
// Expand left and right over identifier characters (ASCII + underscore; acceptable MVP)
|
||||
let bytes = text.as_bytes();
|
||||
let mut start = b;
|
||||
while start > 0 {
|
||||
let c = bytes[start - 1];
|
||||
if (c as char).is_ascii_alphanumeric() || c == b'_' { start -= 1; } else { break; }
|
||||
}
|
||||
let mut end = b;
|
||||
while end < bytes.len() {
|
||||
let c = bytes[end];
|
||||
if (c as char).is_ascii_alphanumeric() || c == b'_' { end += 1; } else { break; }
|
||||
}
|
||||
if start < end { Some(text[start..end].to_string()) } else { None }
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tower_lsp::Client;
|
||||
|
||||
use crate::analysis_db::{AnalysisSnapshot, SharedDb};
|
||||
use prometeu_analysis::{TextIndex};
|
||||
use tower_lsp::lsp_types as lsp;
|
||||
use prometeu_analysis::ids::FileId;
|
||||
use crate::rebuild::compiler_bridge::{ParserFacade, Severity};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LspDiagnostic {
|
||||
pub range: lsp::Range,
|
||||
pub severity: Option<lsp::DiagnosticSeverity>,
|
||||
pub code: Option<lsp::NumberOrString>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FlatSymbol {
|
||||
pub name: String,
|
||||
pub kind: lsp::SymbolKind,
|
||||
pub location: lsp::Location,
|
||||
}
|
||||
|
||||
/// Requests a project rebuild (coarse). Cancels the previous rebuild if in progress.
|
||||
pub async fn request_rebuild(db: SharedDb, client: Client) {
|
||||
// 1) short lock: cancel previous token and install a new one
|
||||
let new_token = CancellationToken::new();
|
||||
{
|
||||
let mut guard = db.write().await;
|
||||
if let Some(prev) = guard.active_rebuild.take() {
|
||||
prev.cancel();
|
||||
}
|
||||
guard.active_rebuild = Some(new_token.clone());
|
||||
}
|
||||
|
||||
// 2) spawn task: run analysis outside the lock
|
||||
tokio::spawn(async move {
|
||||
// Safe point: check before starting
|
||||
if new_token.is_cancelled() { return; }
|
||||
|
||||
// Clone snapshot of files (URIs and texts) under a short read lock
|
||||
let (files, revision) = {
|
||||
let guard = db.read().await;
|
||||
let mut v = Vec::new();
|
||||
for fid in guard.file_ids() {
|
||||
let uri = guard.file_db.uri(fid).to_string();
|
||||
let text = guard.file_db.text(fid).to_string();
|
||||
v.push((fid, uri, text));
|
||||
}
|
||||
(v, guard.revision)
|
||||
};
|
||||
|
||||
// Prepare accumulators
|
||||
let mut diagnostics_by_uri: std::collections::HashMap<String, Vec<LspDiagnostic>> = std::collections::HashMap::new();
|
||||
let mut symbols_flat: Vec<FlatSymbol> = Vec::new();
|
||||
|
||||
// For each file: run a minimal frontend to collect diagnostics and top-level symbols
|
||||
for (fid, uri, text) in files.into_iter() {
|
||||
if new_token.is_cancelled() { return; }
|
||||
let text_index = TextIndex::new(&text);
|
||||
|
||||
// Parser + basic pipeline
|
||||
let mut interner = prometeu_analysis::NameInterner::new();
|
||||
let mut parser = ParserFacade::new(&text, fid, &mut interner);
|
||||
match parser.parse_and_collect() {
|
||||
Ok(parsed) => {
|
||||
// Diagnostics (from parse/collect are already inside parsed.diags)
|
||||
let mut file_diags = Vec::new();
|
||||
for d in parsed.diagnostics {
|
||||
let range = span_to_range(fid, &text_index, d.span.start, d.span.end);
|
||||
file_diags.push(LspDiagnostic {
|
||||
range,
|
||||
severity: Some(match d.severity { Severity::Error => lsp::DiagnosticSeverity::ERROR, Severity::Warning => lsp::DiagnosticSeverity::WARNING }),
|
||||
code: Some(lsp::NumberOrString::String(d.code)),
|
||||
message: d.message,
|
||||
});
|
||||
}
|
||||
diagnostics_by_uri.insert(uri.clone(), file_diags);
|
||||
|
||||
// Symbols: flatten only top-level decls with their decl_span
|
||||
for sym in parsed.symbols {
|
||||
let lsp_loc = lsp::Location {
|
||||
uri: uri.parse().unwrap_or_else(|_| lsp::Url::parse("untitled:").unwrap()),
|
||||
range: span_to_range(fid, &text_index, sym.decl_span.start, sym.decl_span.end),
|
||||
};
|
||||
let kind = match sym.kind {
|
||||
prometeu_compiler::analysis::symbols::SymbolKind::Function => lsp::SymbolKind::FUNCTION,
|
||||
prometeu_compiler::analysis::symbols::SymbolKind::Service => lsp::SymbolKind::INTERFACE,
|
||||
prometeu_compiler::analysis::symbols::SymbolKind::Struct => lsp::SymbolKind::STRUCT,
|
||||
prometeu_compiler::analysis::symbols::SymbolKind::Contract => lsp::SymbolKind::CLASS,
|
||||
prometeu_compiler::analysis::symbols::SymbolKind::ErrorType => lsp::SymbolKind::ENUM,
|
||||
_ => lsp::SymbolKind::VARIABLE,
|
||||
};
|
||||
symbols_flat.push(FlatSymbol { name: sym.name, kind, location: lsp_loc });
|
||||
}
|
||||
}
|
||||
Err(diags) => {
|
||||
// Parser returned errors only; publish them
|
||||
let mut file_diags = Vec::new();
|
||||
for d in diags {
|
||||
let range = span_to_range(fid, &text_index, d.span.start, d.span.end);
|
||||
file_diags.push(LspDiagnostic {
|
||||
range,
|
||||
severity: Some(match d.severity { Severity::Error => lsp::DiagnosticSeverity::ERROR, Severity::Warning => lsp::DiagnosticSeverity::WARNING }),
|
||||
code: Some(lsp::NumberOrString::String(d.code)),
|
||||
message: d.message,
|
||||
});
|
||||
}
|
||||
diagnostics_by_uri.insert(uri.clone(), file_diags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if new_token.is_cancelled() { return; }
|
||||
|
||||
// 3) short lock: swap state + revision++ if not cancelled; then publish diagnostics
|
||||
let snapshot = AnalysisSnapshot { diagnostics_by_uri: diagnostics_by_uri.clone(), symbols_flat };
|
||||
{
|
||||
let mut guard = db.write().await;
|
||||
if new_token.is_cancelled() { return; }
|
||||
// if no new changes since we started, accept this snapshot
|
||||
guard.last_good = Some(snapshot);
|
||||
guard.revision = revision.saturating_add(1);
|
||||
}
|
||||
|
||||
// Publish diagnostics per file
|
||||
for (uri, diags) in diagnostics_by_uri.into_iter() {
|
||||
let lsp_diags: Vec<lsp::Diagnostic> = diags.into_iter().map(|d| lsp::Diagnostic {
|
||||
range: d.range,
|
||||
severity: d.severity,
|
||||
code: d.code,
|
||||
message: d.message,
|
||||
..Default::default()
|
||||
}).collect();
|
||||
let _ = client.publish_diagnostics(uri.parse().unwrap_or_else(|_| lsp::Url::parse("untitled:").unwrap()), lsp_diags, None).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn span_to_range(file: FileId, idx: &TextIndex, start: u32, end: u32) -> lsp::Range {
|
||||
// Ignore `file` here since idx is built from that file's text
|
||||
let (s_line, s_col) = idx.byte_to_lsp(start);
|
||||
let (e_line, e_col) = idx.byte_to_lsp(end);
|
||||
lsp::Range {
|
||||
start: lsp::Position { line: s_line, character: s_col },
|
||||
end: lsp::Position { line: e_line, character: e_col },
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal integration with the compiler frontend for the MVP rebuild loop.
|
||||
mod compiler_bridge {
|
||||
use super::*;
|
||||
use prometeu_compiler::frontends::pbs as p;
|
||||
use prometeu_compiler::common::spans as cspans;
|
||||
use prometeu_compiler::common::diagnostics as cdiag;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Severity { Error, Warning }
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Diag { pub severity: Severity, pub code: String, pub message: String, pub span: cspans::Span }
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SymbolItem { pub name: String, pub kind: prometeu_compiler::analysis::symbols::SymbolKind, pub decl_span: cspans::Span }
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParsedResult { pub diagnostics: Vec<Diag>, pub symbols: Vec<SymbolItem> }
|
||||
|
||||
pub struct ParserFacade<'a> {
|
||||
text: &'a str,
|
||||
file_id: FileId,
|
||||
interner: &'a mut prometeu_analysis::NameInterner,
|
||||
}
|
||||
|
||||
impl<'a> ParserFacade<'a> {
|
||||
pub fn new(text: &'a str, file_id: FileId, interner: &'a mut prometeu_analysis::NameInterner) -> Self {
|
||||
Self { text, file_id, interner }
|
||||
}
|
||||
|
||||
pub fn parse_and_collect(&mut self) -> Result<ParsedResult, Vec<Diag>> {
|
||||
let mut parser = p::parser::Parser::new(self.text, cspans::FileId(self.file_id.0), self.interner);
|
||||
let parsed = match parser.parse_file() {
|
||||
Ok(p) => p,
|
||||
Err(bundle) => {
|
||||
let diags = bundle.diagnostics.into_iter().map(|d| Diag { severity: match d.severity { cdiag::Severity::Error => Severity::Error, cdiag::Severity::Warning => Severity::Warning }, code: d.code, message: d.message, span: d.span }).collect();
|
||||
return Err(diags);
|
||||
}
|
||||
};
|
||||
|
||||
let mut collector = p::collector::SymbolCollector::new(self.interner);
|
||||
let (type_symbols, value_symbols) = match collector.collect(&parsed.arena, parsed.root) {
|
||||
Ok(v) => v,
|
||||
Err(bundle) => {
|
||||
let diags = bundle.diagnostics.into_iter().map(|d| Diag { severity: match d.severity { cdiag::Severity::Error => Severity::Error, cdiag::Severity::Warning => Severity::Warning }, code: d.code, message: d.message, span: d.span }).collect();
|
||||
return Err(diags);
|
||||
}
|
||||
};
|
||||
let module_symbols = p::symbols::ModuleSymbols { type_symbols, value_symbols };
|
||||
|
||||
struct EmptyProvider;
|
||||
impl p::resolver::ModuleProvider for EmptyProvider { fn get_module_symbols(&self, _from_path: &str) -> Option<&p::symbols::ModuleSymbols> { None } }
|
||||
let mut resolver = p::resolver::Resolver::new(&module_symbols, &EmptyProvider, self.interner);
|
||||
// bootstrap primitives using a throwaway interner behavior
|
||||
resolver.bootstrap_types(self.interner);
|
||||
if let Err(bundle) = resolver.resolve(&parsed.arena, parsed.root) {
|
||||
let diags = bundle.diagnostics.into_iter().map(|d| Diag { severity: match d.severity { cdiag::Severity::Error => Severity::Error, cdiag::Severity::Warning => Severity::Warning }, code: d.code, message: d.message, span: d.span }).collect();
|
||||
return Err(diags);
|
||||
}
|
||||
|
||||
// Collect top-level symbols only for MVP
|
||||
let mut symbols = Vec::new();
|
||||
for s in &resolver.symbol_arena.symbols {
|
||||
// Keep only decls in this file
|
||||
if s.decl_span.file.0 == self.file_id.0 {
|
||||
let name = self.interner.resolve(s.name).to_string();
|
||||
let kind = s.kind;
|
||||
symbols.push(SymbolItem { name, kind, decl_span: s.decl_span.clone() });
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ParsedResult { diagnostics: vec![], symbols })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use prometeu_analysis::TextIndex;
|
||||
|
||||
#[test]
|
||||
fn span_to_range_uses_utf16() {
|
||||
// "ação" has: a (1), ç (1 utf16, BMP), ã (1 utf16, BMP), o (1) → total 4 utf16 units
|
||||
let s = "ação\n"; // newline to ensure line indexing works
|
||||
let idx = TextIndex::new(s);
|
||||
|
||||
// Byte offsets for each char boundary
|
||||
let bytes: Vec<u32> = s.char_indices().map(|(i, _)| i as u32).collect();
|
||||
// last boundary is newline; the previous is end of line content
|
||||
let end_of_line = bytes[bytes.len() - 1];
|
||||
let (line, col) = idx.byte_to_lsp(end_of_line);
|
||||
assert_eq!(line, 0);
|
||||
assert_eq!(col, 4, "UTF-16 column should be 4 for 'ação'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_to_byte_roundtrip() {
|
||||
let s = "😀a\n"; // emoji is surrogate pair in UTF-16
|
||||
let idx = TextIndex::new(s);
|
||||
// emoji (😀) occupies 2 utf16 code units; 'a' adds 1
|
||||
let emoji_end_byte = "😀".len() as u32; // byte length of emoji
|
||||
|
||||
// From bytes→(line,col)
|
||||
let (line, col) = idx.byte_to_lsp(emoji_end_byte);
|
||||
assert_eq!(line, 0);
|
||||
assert_eq!(col, 2, "emoji should count as 2 UTF-16 units");
|
||||
|
||||
// Back from (line,col)→bytes should land at the same boundary
|
||||
let back = idx.lsp_to_byte(line, col);
|
||||
assert_eq!(back, emoji_end_byte);
|
||||
}
|
||||
Reference in New Issue
Block a user