pr 03.01
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "frontend-api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "Canonical frontend contract for Prometeu Backend: identifiers, references, and strict Frontend trait."
|
||||
repository = "https://github.com/prometeu/runtime"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
thiserror = "1"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
serde = ["dep:serde"]
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Frontend API (canonical contract between Frontend and Backend)
|
||||
//!
|
||||
//! Policy: no strings-as-protocol. All identifiers use canonical newtypes with
|
||||
//! clear invariants and normalization helpers. No PBS- (or any FE-) specific
|
||||
//! types are allowed in this crate.
|
||||
|
||||
pub mod types;
|
||||
pub mod traits;
|
||||
|
||||
pub use crate::types::*;
|
||||
pub use crate::traits::*;
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Strict frontend contract owned by the Backend.
|
||||
//!
|
||||
//! Implementations must not expose FE-specific types through this boundary.
|
||||
|
||||
use crate::{Diagnostic, ExportItem, ImportRef, LoweredIr};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FrontendUnit {
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
pub imports: Vec<ImportRef>,
|
||||
pub exports: Vec<ExportItem>,
|
||||
pub lowered_ir: LoweredIr,
|
||||
}
|
||||
|
||||
/// Frontend entrypoint that parses and analyzes a single compilation unit
|
||||
/// and produces a `FrontendUnit` for the Backend.
|
||||
pub trait Frontend {
|
||||
/// Parse and analyze the provided sources according to the FE's language,
|
||||
/// returning only canonical artifacts required by the Backend.
|
||||
///
|
||||
/// No strings-as-protocol allowed in the output; use canonical types.
|
||||
fn parse_and_analyze(&self, entry_path: &str) -> FrontendUnit;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use core::fmt;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// A project alias (canonical lowercase name).
|
||||
/// Invariants:
|
||||
/// - lowercase ASCII
|
||||
/// - must start with [a-z]
|
||||
/// - remaining chars: [a-z0-9_-]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ProjectAlias(String);
|
||||
|
||||
impl ProjectAlias {
|
||||
pub fn new<S: AsRef<str>>(s: S) -> Result<Self, CanonError> {
|
||||
let s = s.as_ref().trim();
|
||||
if s.is_empty() {
|
||||
return Err(CanonError::Empty("ProjectAlias"));
|
||||
}
|
||||
if !s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') {
|
||||
return Err(CanonError::InvalidChars("ProjectAlias"));
|
||||
}
|
||||
let mut chars = s.chars();
|
||||
match chars.next() {
|
||||
Some(c) if c.is_ascii_lowercase() => {}
|
||||
_ => return Err(CanonError::InvalidStart("ProjectAlias")),
|
||||
}
|
||||
Ok(Self(s.to_string()))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str { &self.0 }
|
||||
}
|
||||
|
||||
impl fmt::Display for ProjectAlias {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) }
|
||||
}
|
||||
|
||||
/// Canonical module path with '/' separators and lowercase segments.
|
||||
/// Invariants:
|
||||
/// - uses '/' only; '\\' normalized to '/'
|
||||
/// - no leading/trailing '/'
|
||||
/// - no empty segments, no duplicate '//'
|
||||
/// - segments are lowercase ASCII [a-z0-9_-]
|
||||
/// - '.' segments are removed; '..' is forbidden
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ModulePath(String);
|
||||
|
||||
impl ModulePath {
|
||||
pub fn parse<S: AsRef<str>>(s: S) -> Result<Self, CanonError> {
|
||||
let raw = s.as_ref().trim();
|
||||
if raw.is_empty() {
|
||||
return Err(CanonError::Empty("ModulePath"));
|
||||
}
|
||||
let raw = raw.replace('\\', "/");
|
||||
let raw = raw.trim_matches('/');
|
||||
if raw.is_empty() {
|
||||
return Err(CanonError::Empty("ModulePath"));
|
||||
}
|
||||
let mut out: Vec<&str> = Vec::new();
|
||||
for seg in raw.split('/') {
|
||||
if seg.is_empty() { return Err(CanonError::EmptySegment("ModulePath")); }
|
||||
if seg == "." { continue; }
|
||||
if seg == ".." { return Err(CanonError::ParentSegmentsForbidden); }
|
||||
let seg_lc = seg.to_ascii_lowercase();
|
||||
if !seg_lc.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') {
|
||||
return Err(CanonError::InvalidChars("ModulePath"));
|
||||
}
|
||||
out.push(Box::leak(seg_lc.into_boxed_str()));
|
||||
}
|
||||
if out.is_empty() { return Err(CanonError::Empty("ModulePath")); }
|
||||
Ok(Self(out.join("/")))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str { &self.0 }
|
||||
}
|
||||
|
||||
impl fmt::Display for ModulePath {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) }
|
||||
}
|
||||
|
||||
/// Canonical exported/declared item name.
|
||||
/// Invariants:
|
||||
/// - must start with [A-Z]
|
||||
/// - remaining chars: [A-Za-z0-9_]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ItemName(String);
|
||||
|
||||
impl ItemName {
|
||||
pub fn new<S: AsRef<str>>(s: S) -> Result<Self, CanonError> {
|
||||
let s = s.as_ref().trim();
|
||||
if s.is_empty() { return Err(CanonError::Empty("ItemName")); }
|
||||
let mut chars = s.chars();
|
||||
match chars.next() {
|
||||
Some(c) if c.is_ascii_uppercase() => {}
|
||||
_ => return Err(CanonError::InvalidStart("ItemName")),
|
||||
}
|
||||
if !s[1..].chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
|
||||
return Err(CanonError::InvalidChars("ItemName"));
|
||||
}
|
||||
Ok(Self(s.to_string()))
|
||||
}
|
||||
pub fn as_str(&self) -> &str { &self.0 }
|
||||
}
|
||||
|
||||
impl fmt::Display for ItemName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) }
|
||||
}
|
||||
|
||||
/// A fully-qualified import reference: project + module + item.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ImportRef {
|
||||
pub project: ProjectAlias,
|
||||
pub module: ModulePath,
|
||||
pub item: ItemName,
|
||||
}
|
||||
|
||||
impl ImportRef {
|
||||
pub fn new(project: ProjectAlias, module: ModulePath, item: ItemName) -> Self {
|
||||
Self { project, module, item }
|
||||
}
|
||||
}
|
||||
|
||||
/// Export kind — generic, FE-agnostic.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub enum ExportKind {
|
||||
Function,
|
||||
Service,
|
||||
Type,
|
||||
Const,
|
||||
}
|
||||
|
||||
/// An export item description (opaque for BE logic, except name/kind).
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ExportItem {
|
||||
pub name: ItemName,
|
||||
pub kind: ExportKind,
|
||||
}
|
||||
|
||||
impl ExportItem {
|
||||
pub fn new(name: ItemName, kind: ExportKind) -> Self { Self { name, kind } }
|
||||
}
|
||||
|
||||
/// A fully-qualified export reference: project + module + item + kind.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct ExportRef {
|
||||
pub project: ProjectAlias,
|
||||
pub module: ModulePath,
|
||||
pub item: ItemName,
|
||||
pub kind: ExportKind,
|
||||
}
|
||||
|
||||
impl ExportRef {
|
||||
pub fn new(project: ProjectAlias, module: ModulePath, item: ItemName, kind: ExportKind) -> Self {
|
||||
Self { project, module, item, kind }
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical function key, identifying an overload by arity only (for now).
|
||||
/// This will be extended in PR-03.04 with types and calling convention.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub struct CanonicalFnKey {
|
||||
pub import: ImportRef,
|
||||
pub arity: u16,
|
||||
}
|
||||
|
||||
impl CanonicalFnKey {
|
||||
pub fn new(import: ImportRef, arity: u16) -> Self { Self { import, arity } }
|
||||
}
|
||||
|
||||
/// Diagnostic severity.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Severity { Error, Warning, Info }
|
||||
|
||||
/// A simple diagnostic message produced by the frontend.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Diagnostic {
|
||||
pub message: String,
|
||||
pub severity: Severity,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn error<M: Into<String>>(m: M) -> Self { Self { message: m.into(), severity: Severity::Error } }
|
||||
pub fn warning<M: Into<String>>(m: M) -> Self { Self { message: m.into(), severity: Severity::Warning } }
|
||||
pub fn info<M: Into<String>>(m: M) -> Self { Self { message: m.into(), severity: Severity::Info } }
|
||||
}
|
||||
|
||||
/// Opaque lowered IR payload.
|
||||
/// The backend owns the meaning of these bytes for a given `format` tag.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
pub struct LoweredIr {
|
||||
pub format: Cow<'static, str>,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl LoweredIr {
|
||||
pub fn new<S: Into<Cow<'static, str>>>(format: S, bytes: Vec<u8>) -> Self { Self { format: format.into(), bytes } }
|
||||
}
|
||||
|
||||
/// Errors raised while constructing canonical identifiers.
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum CanonError {
|
||||
#[error("{0} cannot be empty")] Empty(&'static str),
|
||||
#[error("{0} has invalid starting character")] InvalidStart(&'static str),
|
||||
#[error("{0} contains invalid characters")] InvalidChars(&'static str),
|
||||
#[error("{0} contains empty segment")] EmptySegment(&'static str),
|
||||
#[error("parent segments ('..') are forbidden in ModulePath")] ParentSegmentsForbidden,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn module_path_normalization_basic() {
|
||||
assert_eq!(ModulePath::parse("input/testing").unwrap().as_str(), "input/testing");
|
||||
assert_eq!(ModulePath::parse("/input/testing/").unwrap().as_str(), "input/testing");
|
||||
assert_eq!(ModulePath::parse("INPUT/Testing").unwrap().as_str(), "input/testing");
|
||||
assert_eq!(ModulePath::parse("input/./testing").unwrap().as_str(), "input/testing");
|
||||
assert_eq!(ModulePath::parse("input\\testing").unwrap().as_str(), "input/testing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_path_rejects_invalid() {
|
||||
assert!(ModulePath::parse("").is_err());
|
||||
assert!(ModulePath::parse("/").is_err());
|
||||
assert!(ModulePath::parse("input//testing").is_err());
|
||||
assert!(ModulePath::parse("input/../testing").is_err());
|
||||
assert!(ModulePath::parse("in$put/testing").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_alias_rules() {
|
||||
assert!(ProjectAlias::new("main").is_ok());
|
||||
assert!(ProjectAlias::new("_main").is_err());
|
||||
assert!(ProjectAlias::new("Main").is_err());
|
||||
assert!(ProjectAlias::new("main-1").is_ok());
|
||||
assert!(ProjectAlias::new("main/1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_name_rules() {
|
||||
assert!(ItemName::new("Test").is_ok());
|
||||
assert!(ItemName::new("Log2").is_ok());
|
||||
assert!(ItemName::new("test").is_err());
|
||||
assert!(ItemName::new("_Test").is_err());
|
||||
assert!(ItemName::new("Te-st").is_err());
|
||||
}
|
||||
}
|
||||
@@ -400,16 +400,9 @@ pub fn compile_project(
|
||||
|
||||
let name_simple = interner.resolve(sym.name).to_string();
|
||||
|
||||
// For service methods, VM function name is "Service.method"
|
||||
let expected_vm_name = if let Some(origin) = &sym.origin {
|
||||
if let Some(svc) = origin.strip_prefix("svc:") {
|
||||
format!("{}.{}", svc, name_simple)
|
||||
} else {
|
||||
name_simple.clone()
|
||||
}
|
||||
} else {
|
||||
name_simple.clone()
|
||||
};
|
||||
// VM function names are currently simple for both free functions and service methods (method name only).
|
||||
// We still export service methods using qualified names, but we match VM functions by simple name.
|
||||
let expected_vm_name = name_simple.clone();
|
||||
|
||||
// Find VM functions that originated in this module_path and match expected name
|
||||
for (i, f) in combined_vm.functions.iter().enumerate() {
|
||||
@@ -420,7 +413,20 @@ pub fn compile_project(
|
||||
continue;
|
||||
}
|
||||
|
||||
let sig_name = format!("{}#sig{}", name_simple, f.sig.0);
|
||||
// Canonical export key name:
|
||||
// - Free function: "name#sig<id>"
|
||||
// - Service method: "Service.method#sig<id>"
|
||||
let canonical_base = if let Some(origin) = &sym.origin {
|
||||
if let Some(svc) = origin.strip_prefix("svc:") {
|
||||
format!("{}.{}", svc, name_simple)
|
||||
} else {
|
||||
name_simple.clone()
|
||||
}
|
||||
} else {
|
||||
name_simple.clone()
|
||||
};
|
||||
|
||||
let sig_name = format!("{}#sig{}", canonical_base, f.sig.0);
|
||||
|
||||
let ty = sym.ty.clone().ok_or_else(|| {
|
||||
CompileError::Internal(format!(
|
||||
@@ -581,4 +587,51 @@ mod tests {
|
||||
};
|
||||
assert!(compiled.exports.contains_key(&vec2_key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service_method_export_qualified() {
|
||||
let dir = tempdir().unwrap();
|
||||
let project_dir = dir.path().to_path_buf();
|
||||
|
||||
fs::create_dir_all(project_dir.join("src/main/modules")).unwrap();
|
||||
|
||||
let main_code = r#"
|
||||
pub service Log {
|
||||
fn debug(msg: string): void {
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
fs::write(project_dir.join("src/main/modules/main.pbs"), main_code).unwrap();
|
||||
|
||||
let project_key = ProjectKey {
|
||||
name: "root".to_string(),
|
||||
version: "0.1.0".to_string(),
|
||||
};
|
||||
let project_id = ProjectId(0);
|
||||
|
||||
let step = BuildStep {
|
||||
project_id,
|
||||
project_key: project_key.clone(),
|
||||
project_dir: project_dir.clone(),
|
||||
target: BuildTarget::Main,
|
||||
sources: vec![PathBuf::from("src/main/modules/main.pbs")],
|
||||
deps: BTreeMap::new(),
|
||||
};
|
||||
|
||||
let mut file_manager = FileManager::new();
|
||||
let compiled = compile_project(step, &HashMap::new(), &mut file_manager)
|
||||
.expect("Failed to compile project");
|
||||
|
||||
// Find a function export with qualified method name prefix "Log.debug#sig"
|
||||
let mut found = false;
|
||||
for (key, _meta) in &compiled.exports {
|
||||
if key.kind == ExportSurfaceKind::Function && key.symbol_name.starts_with("Log.debug#sig") {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(found, "Expected an export with qualified name 'Log.debug#sigX' but not found. Exports: {:?}", compiled.exports.keys().collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1330,13 +1330,17 @@ impl<'a> Lowerer<'a> {
|
||||
];
|
||||
|
||||
// Find candidates among imported value symbols matching:
|
||||
// - name in the new canonical form: "member#sigN" (prefix match on member_name)
|
||||
// - name in the new canonical form: "Service.member#sigN" (prefix match on qualified base)
|
||||
// - origin equals the bound synthetic module path
|
||||
let mut candidates: Vec<&Symbol> = Vec::new();
|
||||
for list in self.imported_symbols.value_symbols.symbols.values() {
|
||||
for s in list {
|
||||
let sname = self.interner.resolve(s.name);
|
||||
if sname.starts_with(&format!("{}#sig", member_name)) {
|
||||
// Accept both canonical qualified form and legacy simple form for compatibility
|
||||
let qualified_base = format!("{}.{}", obj_name, member_name);
|
||||
let matches_qualified = sname.starts_with(&format!("{}#sig", &qualified_base));
|
||||
let matches_legacy = sname.starts_with(&format!("{}#sig", member_name));
|
||||
if matches_qualified || matches_legacy {
|
||||
if let Some(orig) = &s.origin {
|
||||
if synthetic_paths.iter().any(|p| p == orig) {
|
||||
candidates.push(s);
|
||||
@@ -1384,10 +1388,11 @@ impl<'a> Lowerer<'a> {
|
||||
};
|
||||
|
||||
if let Some(sig) = sig_opt {
|
||||
let base_name = format!("{}.{}", obj_name, member_name);
|
||||
self.emit(InstrKind::ImportCall {
|
||||
dep_alias,
|
||||
module_path,
|
||||
base_name: member_name.to_string(),
|
||||
base_name,
|
||||
sig,
|
||||
arg_count: n.args.len() as u32,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user