hard reseet

This commit is contained in:
2026-03-24 13:40:34 +00:00
parent bddd588464
commit 463f72a123
133 changed files with 769 additions and 20159 deletions
+1 -1
View File
@@ -27,5 +27,5 @@ include = [
[dependencies]
clap = { version = "4.5", features = ["derive"] }
prometeu-host-desktop-winit = { path = "../../host/prometeu-host-desktop-winit" }
prometeu-compiler = { path = "../../compiler/prometeu-compiler" }
prometeu-build-pipeline = { path = "../../compiler/prometeu-build-pipeline" }
anyhow = "1.0.100"
@@ -1 +1 @@
fn main() -> anyhow::Result<()> { prometeu_compiler::run() }
fn main() -> anyhow::Result<()> { prometeu_build_pipeline::run() }
+1 -1
View File
@@ -8,7 +8,7 @@ use std::process::Command;
/// 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`.
/// components like `prometeu-host-desktop-winit` or `prometeu-build-pipeline`.
#[derive(Parser)]
#[command(name = "prometeu")]
#[command(about = "Dispatcher for the Prometeu ecosystem", long_about = None)]
+2 -2
View File
@@ -8,5 +8,5 @@ license = "MIT"
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" }
prometeu-core = { path = "../../compiler/prometeu-core" }
prometeu-build-pipeline = { path = "../../compiler/prometeu-build-pipeline" }
+51 -52
View File
@@ -1,52 +1,51 @@
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>,
}
// use std::sync::Arc;
// use tokio::sync::RwLock;
// use tokio_util::sync::CancellationToken;
//
// use std::collections::HashMap;
// use prometeu_core::{FileDB, FileId, ProjectId};
// 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>,
// }
+183 -185
View File
@@ -1,192 +1,190 @@
use std::sync::Arc;
use tokio::sync::RwLock;
use tower_lsp::{Client, LspService, Server};
use tower_lsp::lsp_types as lsp;
// 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;
mod analysis_db;
mod rebuild;
// struct Backend {
// db: SharedDb,
// client: Client,
// }
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![]))
// }
}
// #[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;
// let stdin = tokio::io::stdin();
// let stdout = tokio::io::stdout();
//
// let db: SharedDb = Arc::new(RwLock::new(analysis_db::sourceDb::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 }
}
// // 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 }
// }
+147 -225
View File
@@ -1,225 +1,147 @@
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 })
}
}
}
// use tokio_util::sync::CancellationToken;
// use tower_lsp::Client;
//
// use crate::source_db::{AnalysisSnapshot, SharedDb};
// use tower_lsp::lsp_types as lsp;
// use prometeu_core::{FileId, NameInterner, Severity, SymbolKind, TextIndex};
//
// #[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 = 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 {
// SymbolKind::Function => lsp::SymbolKind::FUNCTION,
// SymbolKind::Service => lsp::SymbolKind::INTERFACE,
// SymbolKind::Struct => lsp::SymbolKind::STRUCT,
// SymbolKind::Contract => lsp::SymbolKind::CLASS,
// 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 },
// }
// }
@@ -1,33 +0,0 @@
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);
}