added domains into crates

This commit is contained in:
2026-03-24 13:40:34 +00:00
parent 1135514508
commit bddd588464
222 changed files with 751 additions and 790 deletions
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "language-api"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "Canonical language 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"]
+11
View File
@@ -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::*;
+23
View File
@@ -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;
}
+341
View File
@@ -0,0 +1,341 @@
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-Za-z] (types/services typically use UpperCamel; functions may be lowerCamel)
/// - 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_alphabetic() => {}
_ => 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 }
}
/// Parse a PBS-style import `from` string and an `item` into an `ImportRef`.
///
/// Expected `from_str` format: "@<alias>:<module_path>", e.g., "@sdk:input/testing".
/// `item_str` must be a single symbol name like "Test" or "ServiceName".
pub fn parse_pbs_import<S1: AsRef<str>, S2: AsRef<str>>(from_str: S1, item_str: S2) -> Result<Self, CanonError> {
let (project, module) = parse_pbs_from_string(from_str)?;
let item = ItemName::new(item_str)?;
Ok(ImportRef { project, module, item })
}
}
/// Parse the PBS `from` string in the canonical format `@<alias>:<module_path>`.
/// Returns `(ProjectAlias, ModulePath)` or a `CanonError` if invalid.
pub fn parse_pbs_from_string<S: AsRef<str>>(from_str: S) -> Result<(ProjectAlias, ModulePath), CanonError> {
let s = from_str.as_ref().trim();
// Must start with '@' and contain a ':' separating alias and module path
let rest = s.strip_prefix('@').ok_or(CanonError::InvalidStart("ImportFrom"))?;
let mut parts = rest.splitn(2, ':');
let alias = parts.next().unwrap_or("");
let module = parts.next().unwrap_or("");
if alias.is_empty() || module.is_empty() {
return Err(CanonError::Empty("ImportFrom"));
}
let project = ProjectAlias::new(alias)?;
let module = ModulePath::parse(module)?;
Ok((project, module))
}
/// 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,
}
/// Canonical export item (FE-owned, BE-agnostic, no string protocols).
///
/// This surface is stable even if display formatting changes.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum ExportItem {
/// A declared canonical type (struct/enum/etc.)
Type { name: ItemName },
/// A declared service owner (method container)
Service { name: ItemName },
/// A function export (free fn or method) identified by canonical key
Function { fn_key: CanonicalFnKey },
}
/// 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 identity.
///
/// JVM-like canonical pieces to uniquely identify an overload across projects:
/// - `owner`: optional service/type name for methods (e.g., `Some("Log")`) or `None` for free fns
/// - `name`: unqualified function/method name (e.g., `"debug"`)
/// - `sig`: canonical signature id produced by the frontend
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct CanonicalFnKey {
pub owner: Option<ItemName>,
pub name: ItemName,
pub sig: SignatureRef,
}
impl CanonicalFnKey {
pub fn new(owner: Option<ItemName>, name: ItemName, sig: SignatureRef) -> Self {
Self { owner, name, sig }
}
/// Returns a human-friendly display name like "Log.debug" or just "debug".
pub fn debug_name(&self) -> String {
match &self.owner {
Some(o) => format!("{}.{}", o.as_str(), self.name.as_str()),
None => self.name.as_str().to_string(),
}
}
}
/// Opaque canonical reference to a type known to the Frontend.
/// Backend must not rely on its internal representation.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct TypeRef(pub u32);
/// Opaque canonical reference to a function signature (overload identity).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct SignatureRef(pub u32);
/// 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_ok());
assert!(ItemName::new("_Test").is_err());
assert!(ItemName::new("Te-st").is_err());
}
#[test]
fn parse_pbs_from_string_valid_and_normalization() {
let (proj, module) = parse_pbs_from_string("@sdk:input/testing").unwrap();
assert_eq!(proj.as_str(), "sdk");
assert_eq!(module.as_str(), "input/testing");
// Normalization of module path
let (_, module2) = parse_pbs_from_string("@sdk:/Input/./Testing/").unwrap();
assert_eq!(module2.as_str(), "input/testing");
// Windows-style separators normalize
let (_, module3) = parse_pbs_from_string("@abc:foo\\bar").unwrap();
assert_eq!(module3.as_str(), "foo/bar");
}
#[test]
fn parse_pbs_from_string_invalid_forms() {
assert!(parse_pbs_from_string("").is_err());
assert!(parse_pbs_from_string("sdk:input/testing").is_err()); // missing '@'
assert!(parse_pbs_from_string("@Sdk:input/testing").is_err()); // invalid alias
assert!(parse_pbs_from_string("@sdk:").is_err()); // empty module
assert!(parse_pbs_from_string("@sdk:..").is_err()); // parent segments forbidden
}
}