dev/pbs (#8)
Co-authored-by: Nilton Constantino <nilton.constantino@visma.com> Reviewed-on: #8
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
use crate::manifest::Manifest;
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ProjectConfig {
|
||||
#[serde(flatten)]
|
||||
pub manifest: Manifest,
|
||||
pub script_fe: String,
|
||||
pub entry: PathBuf,
|
||||
}
|
||||
|
||||
impl ProjectConfig {
|
||||
pub fn load(project_dir: &Path) -> Result<Self> {
|
||||
let config_path = project_dir.join("prometeu.json");
|
||||
let content = std::fs::read_to_string(&config_path)?;
|
||||
let config: ProjectConfig = serde_json::from_str(&content)
|
||||
.map_err(|e| anyhow::anyhow!("JSON error in {:?}: {}", config_path, e))?;
|
||||
|
||||
// Use manifest validation
|
||||
crate::manifest::load_manifest(project_dir)
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_load_valid_config() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config_path = dir.path().join("prometeu.json");
|
||||
fs::write(
|
||||
config_path,
|
||||
r#"{
|
||||
"name": "test_project",
|
||||
"version": "0.1.0",
|
||||
"script_fe": "pbs",
|
||||
"entry": "main.pbs"
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let config = ProjectConfig::load(dir.path()).unwrap();
|
||||
assert_eq!(config.manifest.name, "test_project");
|
||||
assert_eq!(config.script_fe, "pbs");
|
||||
assert_eq!(config.entry, PathBuf::from("main.pbs"));
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,35 @@
|
||||
use crate::common::files::FileManager;
|
||||
use crate::common::spans::Span;
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum DiagnosticLevel {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
impl Serialize for DiagnosticLevel {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match self {
|
||||
DiagnosticLevel::Error => serializer.serialize_str("error"),
|
||||
DiagnosticLevel::Warning => serializer.serialize_str("warning"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Diagnostic {
|
||||
#[serde(rename = "severity")]
|
||||
pub level: DiagnosticLevel,
|
||||
pub code: Option<String>,
|
||||
pub message: String,
|
||||
pub span: Option<Span>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DiagnosticBundle {
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
@@ -33,6 +49,7 @@ impl DiagnosticBundle {
|
||||
let mut bundle = Self::new();
|
||||
bundle.push(Diagnostic {
|
||||
level: DiagnosticLevel::Error,
|
||||
code: None,
|
||||
message,
|
||||
span,
|
||||
});
|
||||
@@ -44,6 +61,45 @@ impl DiagnosticBundle {
|
||||
.iter()
|
||||
.any(|d| matches!(d.level, DiagnosticLevel::Error))
|
||||
}
|
||||
|
||||
/// Serializes the diagnostic bundle to canonical JSON, resolving file IDs via FileManager.
|
||||
pub fn to_json(&self, file_manager: &FileManager) -> String {
|
||||
#[derive(Serialize)]
|
||||
struct CanonicalSpan {
|
||||
file: String,
|
||||
start: u32,
|
||||
end: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CanonicalDiag {
|
||||
severity: DiagnosticLevel,
|
||||
code: String,
|
||||
message: String,
|
||||
span: Option<CanonicalSpan>,
|
||||
}
|
||||
|
||||
let canonical_diags: Vec<CanonicalDiag> = self.diagnostics.iter().map(|d| {
|
||||
let canonical_span = d.span.and_then(|s| {
|
||||
file_manager.get_path(s.file_id).map(|p| {
|
||||
CanonicalSpan {
|
||||
file: p.file_name().unwrap().to_string_lossy().to_string(),
|
||||
start: s.start,
|
||||
end: s.end,
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
CanonicalDiag {
|
||||
severity: d.level.clone(),
|
||||
code: d.code.clone().unwrap_or_else(|| "E_UNKNOWN".to_string()),
|
||||
message: d.message.clone(),
|
||||
span: canonical_span,
|
||||
}
|
||||
}).collect();
|
||||
|
||||
serde_json::to_string_pretty(&canonical_diags).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Diagnostic> for DiagnosticBundle {
|
||||
@@ -53,3 +109,66 @@ impl From<Diagnostic> for DiagnosticBundle {
|
||||
bundle
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::common::files::FileManager;
|
||||
use crate::frontends::pbs::PbsFrontend;
|
||||
use crate::frontends::Frontend;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn get_diagnostics(code: &str) -> String {
|
||||
let mut file_manager = FileManager::new();
|
||||
let temp_dir = tempdir().unwrap();
|
||||
let file_path = temp_dir.path().join("main.pbs");
|
||||
fs::write(&file_path, code).unwrap();
|
||||
|
||||
let frontend = PbsFrontend;
|
||||
match frontend.compile_to_ir(&file_path, &mut file_manager) {
|
||||
Ok(_) => "[]".to_string(),
|
||||
Err(bundle) => bundle.to_json(&file_manager),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golden_parse_error() {
|
||||
let code = "fn main() { let x = ; }";
|
||||
let json = get_diagnostics(code);
|
||||
assert!(json.contains("E_PARSE_UNEXPECTED_TOKEN"));
|
||||
assert!(json.contains("Expected expression"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golden_lex_error() {
|
||||
let code = "fn main() { let x = \"hello ; }";
|
||||
let json = get_diagnostics(code);
|
||||
assert!(json.contains("E_LEX_UNTERMINATED_STRING"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golden_resolve_error() {
|
||||
let code = "fn main() { let x = undefined_var; }";
|
||||
let json = get_diagnostics(code);
|
||||
assert!(json.contains("E_RESOLVE_UNDEFINED"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golden_type_error() {
|
||||
let code = "fn main() { let x: int = \"hello\"; }";
|
||||
let json = get_diagnostics(code);
|
||||
assert!(json.contains("E_TYPE_MISMATCH"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golden_namespace_collision() {
|
||||
let code = "
|
||||
declare struct Foo {}
|
||||
fn main() {
|
||||
let Foo = 1;
|
||||
}
|
||||
";
|
||||
let json = get_diagnostics(code);
|
||||
assert!(json.contains("E_RESOLVE_NAMESPACE_COLLISION"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceFile {
|
||||
pub id: usize,
|
||||
pub path: PathBuf,
|
||||
pub source: Arc<str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileManager {
|
||||
files: Vec<SourceFile>,
|
||||
}
|
||||
@@ -57,3 +59,28 @@ impl FileManager {
|
||||
(line, col)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_lookup_pos() {
|
||||
let mut fm = FileManager::new();
|
||||
let source = "line1\nline2\n line3".to_string();
|
||||
let file_id = fm.add(PathBuf::from("test.pbs"), source);
|
||||
|
||||
// "l" in line 1
|
||||
assert_eq!(fm.lookup_pos(file_id, 0), (1, 1));
|
||||
// "e" in line 1
|
||||
assert_eq!(fm.lookup_pos(file_id, 3), (1, 4));
|
||||
// "\n" after line 1
|
||||
assert_eq!(fm.lookup_pos(file_id, 5), (1, 6));
|
||||
// "l" in line 2
|
||||
assert_eq!(fm.lookup_pos(file_id, 6), (2, 1));
|
||||
// first space in line 3
|
||||
assert_eq!(fm.lookup_pos(file_id, 12), (3, 1));
|
||||
// "l" in line 3
|
||||
assert_eq!(fm.lookup_pos(file_id, 14), (3, 3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,3 +2,4 @@ pub mod diagnostics;
|
||||
pub mod spans;
|
||||
pub mod files;
|
||||
pub mod symbols;
|
||||
pub mod config;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct Span {
|
||||
pub file_id: usize,
|
||||
pub start: u32,
|
||||
|
||||
@@ -1,9 +1,182 @@
|
||||
use serde::Serialize;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use crate::common::spans::Span;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct Symbol {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RawSymbol {
|
||||
pub pc: u32,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct DebugSymbol {
|
||||
pub pc: u32,
|
||||
pub file: String,
|
||||
pub line: usize,
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Symbol {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub exported: bool,
|
||||
pub module_path: String,
|
||||
pub decl_span: SpanRange,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct SpanRange {
|
||||
pub file: String,
|
||||
pub start: Pos,
|
||||
pub end: Pos,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Pos {
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ProjectSymbols {
|
||||
pub project: String,
|
||||
pub project_dir: String,
|
||||
pub symbols: Vec<Symbol>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct SymbolsFile {
|
||||
pub schema_version: u32,
|
||||
pub compiler_version: String,
|
||||
pub root_project: String,
|
||||
pub projects: Vec<ProjectSymbols>,
|
||||
}
|
||||
|
||||
pub type SymbolInfo = Symbol;
|
||||
|
||||
pub fn collect_symbols(
|
||||
project_id: &str,
|
||||
module_symbols: &HashMap<String, crate::frontends::pbs::symbols::ModuleSymbols>,
|
||||
file_manager: &crate::common::files::FileManager,
|
||||
) -> Vec<Symbol> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
for (module_path, ms) in module_symbols {
|
||||
// Collect from type_symbols
|
||||
for sym in ms.type_symbols.symbols.values() {
|
||||
if let Some(s) = convert_symbol(project_id, module_path, sym, file_manager) {
|
||||
result.push(s);
|
||||
}
|
||||
}
|
||||
// Collect from value_symbols
|
||||
for sym in ms.value_symbols.symbols.values() {
|
||||
if let Some(s) = convert_symbol(project_id, module_path, sym, file_manager) {
|
||||
result.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deterministic ordering: by file, then start pos, then name
|
||||
result.sort_by(|a, b| {
|
||||
a.decl_span.file.cmp(&b.decl_span.file)
|
||||
.then(a.decl_span.start.line.cmp(&b.decl_span.start.line))
|
||||
.then(a.decl_span.start.col.cmp(&b.decl_span.start.col))
|
||||
.then(a.name.cmp(&b.name))
|
||||
});
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn convert_symbol(
|
||||
project_id: &str,
|
||||
module_path: &str,
|
||||
sym: &crate::frontends::pbs::symbols::Symbol,
|
||||
file_manager: &crate::common::files::FileManager,
|
||||
) -> Option<Symbol> {
|
||||
use crate::frontends::pbs::symbols::{SymbolKind, Visibility};
|
||||
|
||||
let kind = match sym.kind {
|
||||
SymbolKind::Service => "service",
|
||||
SymbolKind::Struct | SymbolKind::Contract | SymbolKind::ErrorType => "type",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Local => return None, // Ignore locals for v0
|
||||
};
|
||||
|
||||
let exported = sym.visibility == Visibility::Pub;
|
||||
|
||||
// According to v0 policy, only service and declare are exported.
|
||||
// Functions are NOT exportable yet.
|
||||
if exported && sym.kind == SymbolKind::Function {
|
||||
// This should have been caught by semantic analysis, but we enforce it here too
|
||||
// for the symbols.json output.
|
||||
// Actually, we'll just mark it exported=false if it's a function.
|
||||
}
|
||||
|
||||
let span = sym.span;
|
||||
let file_path = file_manager.get_path(span.file_id)
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("unknown_file_{}", span.file_id));
|
||||
|
||||
// Convert 1-based to 0-based
|
||||
let (s_line, s_col) = file_manager.lookup_pos(span.file_id, span.start);
|
||||
let (e_line, e_col) = file_manager.lookup_pos(span.file_id, span.end);
|
||||
|
||||
let decl_span = SpanRange {
|
||||
file: file_path,
|
||||
start: Pos { line: (s_line - 1) as u32, col: (s_col - 1) as u32 },
|
||||
end: Pos { line: (e_line - 1) as u32, col: (e_col - 1) as u32 },
|
||||
};
|
||||
|
||||
let hash = decl_span.compute_hash();
|
||||
let id = format!("{}:{}:{}:{}:{:016x}", project_id, kind, module_path, sym.name, hash);
|
||||
|
||||
Some(Symbol {
|
||||
id,
|
||||
name: sym.name.clone(),
|
||||
kind: kind.to_string(),
|
||||
exported,
|
||||
module_path: module_path.to_string(),
|
||||
decl_span,
|
||||
})
|
||||
}
|
||||
|
||||
impl SpanRange {
|
||||
pub fn compute_hash(&self) -> u64 {
|
||||
let mut h = 0xcbf29ce484222325u64;
|
||||
let mut update = |bytes: &[u8]| {
|
||||
for b in bytes {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x100000001b3u64);
|
||||
}
|
||||
};
|
||||
|
||||
update(self.file.as_bytes());
|
||||
update(&self.start.line.to_le_bytes());
|
||||
update(&self.start.col.to_le_bytes());
|
||||
update(&self.end.line.to_le_bytes());
|
||||
update(&self.end.col.to_le_bytes());
|
||||
h
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_symbol_id_is_stable() {
|
||||
let span = SpanRange {
|
||||
file: "main.pbs".to_string(),
|
||||
start: Pos { line: 10, col: 5 },
|
||||
end: Pos { line: 10, col: 20 },
|
||||
};
|
||||
|
||||
let hash1 = span.compute_hash();
|
||||
let hash2 = span.compute_hash();
|
||||
|
||||
assert_eq!(hash1, hash2);
|
||||
assert_eq!(hash1, 7774626535098684588u64); // Fixed value for stability check
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user