This commit is contained in:
2026-03-24 13:40:22 +00:00
parent 747ac81da2
commit bbe7ea4dbe
9 changed files with 1097 additions and 12 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "prometeu-analysis"
version = "0.1.0"
edition = "2021"
license = "MIT"
[lib]
name = "prometeu_analysis"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+29
View File
@@ -0,0 +1,29 @@
//! Tipos e utilitários de análise usados pelo servidor LSP e pelo pipeline.
//!
//! Este crate expõe o `FileDB`, repositório de textos do projeto.
//! Ele será expandido nos próximos PRs para suportar snapshots e índices.
//!
//! Exemplo básico:
//! ```
//! use prometeu_analysis::FileDB;
//! let db = FileDB::default();
//! assert_eq!(db.len_files(), 0);
//! ```
use serde::{Deserialize, Serialize};
/// Banco de arquivos do projeto.
///
/// Responsável por armazenar textos, URIs/paths e permitir criação de snapshots.
/// Implementação mínima no PR-00; funcionalidades serão adicionadas nos PRs seguintes.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct FileDB {
// TODO(PR-03+): armazenar textos, URIs/paths, índices de linha e snapshots
#[serde(skip)]
_placeholder: (),
}
impl FileDB {
/// Retorna a quantidade de arquivos conhecidos.
/// Implementação temporária para manter a API estável.
pub fn len_files(&self) -> usize { 0 }
}
+11
View File
@@ -0,0 +1,11 @@
[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 = "../prometeu-analysis" }
+24
View File
@@ -0,0 +1,24 @@
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
use prometeu_analysis::FileDB;
#[derive(Default)]
pub struct AnalysisDb {
pub file_db: FileDB,
// 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>,
}
pub type SharedDb = Arc<RwLock<AnalysisDb>>;
+77
View File
@@ -0,0 +1,77 @@
use std::sync::Arc;
use tokio::sync::RwLock;
use tower_lsp::{LspService, Server};
mod analysis_db;
mod rebuild;
use analysis_db::SharedDb;
struct Backend {
db: SharedDb,
}
#[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,
),
),
// Declaramos capacidades desde já para evitar churn posterior.
definition_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
document_symbol_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
workspace_symbol_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
hover_provider: Some(true.into()),
references_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
rename_provider: Some(tower_lsp::lsp_types::OneOf::Left(true)),
completion_provider: Some(tower_lsp::lsp_types::CompletionOptions {
resolve_provider: Some(false),
trigger_characters: Some(vec![".".into(), ":".into()]),
..Default::default()
}),
semantic_tokens_provider: Some(
tower_lsp::lsp_types::SemanticTokensServerCapabilities::SemanticTokensOptions(
tower_lsp::lsp_types::SemanticTokensOptions {
legend: tower_lsp::lsp_types::SemanticTokensLegend {
// preenchido no PR-12
token_types: vec![],
token_modifiers: vec![],
},
full: Some(
tower_lsp::lsp_types::SemanticTokensFullOptions::Bool(true),
),
range: None,
..Default::default()
},
),
),
..Default::default()
},
..Default::default()
})
}
async fn initialized(&self, _: tower_lsp::lsp_types::InitializedParams) {}
async fn shutdown(&self) -> tower_lsp::jsonrpc::Result<()> {
Ok(())
}
}
#[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() });
Server::new(stdin, stdout, socket).serve(service).await;
}
+48
View File
@@ -0,0 +1,48 @@
use tokio_util::sync::CancellationToken;
use crate::analysis_db::SharedDb;
/// Solicita rebuild do projeto (coarse). Cancela rebuild anterior se em progresso.
/// Implementação inicial: apenas cria task e retorna.
pub async fn request_rebuild(db: SharedDb) {
// 1) lock curto: cancelar token anterior e instalar token novo
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: roda análise fora do lock
tokio::spawn(async move {
// Ponto seguro: checar antes de começar
if new_token.is_cancelled() { return; }
// TODO(PR-03/04/05):
// - Clonar snapshot de FileDB
// - Parsing
// - Binding/Resolver
// - Typecheck
// - Coleta de diagnostics
// Ponto seguro: após parsing
if new_token.is_cancelled() { return; }
// Ponto seguro: após resolver
if new_token.is_cancelled() { return; }
// Ponto seguro: após typecheck
if new_token.is_cancelled() { return; }
// 3) lock curto: se token não cancelado, swap estado + revision++
if !new_token.is_cancelled() {
let mut guard = db.write().await;
// TODO: checar se o token ainda é o ativo quando tivermos um identificador estável
if !new_token.is_cancelled() {
// TODO: aplicar resultados reais de análise quando disponíveis
guard.revision = guard.revision.saturating_add(1);
// Nota: não limpamos `active_rebuild` aqui para evitar interferir num rebuild mais novo
}
}
});
}