use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;
use crate::parsing::Span;
use crate::semantic::{
CollectedAliasArgument, CollectedExtension, CollectedSymbolKind, ModuleGraph, ModuleGraphError,
ResolvedSymbol,
};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CanonicalSymbolPath {
pub module: String,
pub local: String,
}
impl CanonicalSymbolPath {
pub(crate) fn from_resolved(symbol: &ResolvedSymbol<'_>) -> Self {
Self {
module: symbol.module_path.to_owned(),
local: symbol.local_path.to_owned(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveExtensionFunction {
pub relative_path: String,
pub declaration: CanonicalSymbolPath,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveTraitImplementation {
pub trait_path: String,
pub span: Span,
pub associated_types: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveExtension {
pub origin_module: String,
pub symbol: Option<String>,
pub target: CanonicalSymbolPath,
pub generic_parameters: Vec<String>,
pub target_arguments: Vec<CollectedAliasArgument>,
pub functions: Vec<ActiveExtensionFunction>,
pub trait_implementations: Vec<ActiveTraitImplementation>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExtensionEnvironment {
pub extensions: Vec<ActiveExtension>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExtensionActivationError {
Resolution(ModuleGraphError),
MissingImportedModule {
requested_by: String,
path: String,
},
MissingExtensionMetadata {
module: String,
symbol: String,
},
FunctionConflict {
target: CanonicalSymbolPath,
relative_path: String,
first_extension: String,
second_extension: String,
},
TraitImplementationConflict {
target: CanonicalSymbolPath,
trait_path: String,
first_extension: String,
second_extension: String,
},
}
impl fmt::Display for ExtensionActivationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Resolution(error) => error.fmt(formatter),
Self::MissingImportedModule { requested_by, path } => {
write!(
formatter,
"module `{requested_by}` imports missing module `{path}`"
)
}
Self::MissingExtensionMetadata { module, symbol } => {
write!(
formatter,
"missing metadata for extension `{module}::{symbol}`"
)
}
Self::FunctionConflict {
target,
relative_path,
..
} => write!(
formatter,
"multiple visible extensions define `{relative_path}` for `{}::{}`",
target.module, target.local
),
Self::TraitImplementationConflict {
target, trait_path, ..
} => write!(
formatter,
"multiple visible extensions implement `{trait_path}` for `{}::{}`",
target.module, target.local
),
}
}
}
impl Error for ExtensionActivationError {}
impl From<ModuleGraphError> for ExtensionActivationError {
fn from(value: ModuleGraphError) -> Self {
Self::Resolution(value)
}
}
impl ExtensionEnvironment {
pub fn build(
graph: &ModuleGraph,
requesting_module: &str,
) -> Result<Self, Vec<ExtensionActivationError>> {
let Some(module) = graph.module(requesting_module) else {
return Err(vec![ExtensionActivationError::Resolution(
ModuleGraphError::UnknownModule {
path: requesting_module.to_owned(),
},
)]);
};
let mut candidates = BTreeSet::<(String, Option<String>)>::new();
for extension in &module.declarations.extensions {
candidates.insert((module.path.clone(), extension.symbol.clone()));
}
for symbol in module.declarations.symbols.values() {
match &symbol.kind {
CollectedSymbolKind::ModuleAlias { source } => {
let Some(imported) = graph.module(source) else {
continue;
};
for extension in &imported.declarations.extensions {
if extension.symbol.is_none() {
candidates.insert((imported.path.clone(), None));
}
}
}
CollectedSymbolKind::Alias { .. } => {
if let Ok(resolved) = graph.resolve(requesting_module, &symbol.path)
&& matches!(resolved.symbol.kind, CollectedSymbolKind::Extension { .. })
{
candidates.insert((
resolved.module_path.to_owned(),
Some(resolved.local_path.to_owned()),
));
}
}
_ => {}
}
}
if let Some(prelude_path) = graph.prelude()
&& let Some(prelude) = graph.module(prelude_path)
{
for extension in &prelude.declarations.extensions {
if extension.symbol.is_none() {
candidates.insert((prelude.path.clone(), None));
}
}
for symbol in prelude.declarations.symbols.values() {
if let CollectedSymbolKind::Alias { .. } = &symbol.kind
&& let Ok(resolved) = graph.resolve(prelude_path, &symbol.path)
&& matches!(resolved.symbol.kind, CollectedSymbolKind::Extension { .. })
{
candidates.insert((
resolved.module_path.to_owned(),
Some(resolved.local_path.to_owned()),
));
}
}
}
let mut errors = Vec::new();
let mut extensions = Vec::new();
for (origin, symbol) in candidates {
match activate(graph, &origin, symbol.as_deref()) {
Ok(extension) => extensions.push(extension),
Err(error) => errors.push(error),
}
}
detect_conflicts(&extensions, &mut errors);
if errors.is_empty() {
Ok(Self { extensions })
} else {
Err(errors)
}
}
}
fn activate(
graph: &ModuleGraph,
origin_module: &str,
symbol: Option<&str>,
) -> Result<ActiveExtension, ExtensionActivationError> {
let module = graph.module(origin_module).ok_or_else(|| {
ExtensionActivationError::MissingImportedModule {
requested_by: origin_module.to_owned(),
path: origin_module.to_owned(),
}
})?;
let metadata = find_extension(&module.declarations.extensions, symbol).ok_or_else(|| {
ExtensionActivationError::MissingExtensionMetadata {
module: origin_module.to_owned(),
symbol: symbol.unwrap_or("<file>").to_owned(),
}
})?;
let target =
CanonicalSymbolPath::from_resolved(&graph.resolve(origin_module, &metadata.target)?);
let prefix = metadata.symbol.as_deref();
let mut functions = Vec::new();
for declaration in module.declarations.symbols.values() {
let CollectedSymbolKind::Declaration(ids) = &declaration.kind else {
continue;
};
if ids.function.is_none() {
continue;
}
let Some(relative_path) = relative_to_extension(&declaration.path, prefix) else {
continue;
};
functions.push(ActiveExtensionFunction {
relative_path,
declaration: CanonicalSymbolPath {
module: origin_module.to_owned(),
local: declaration.path.clone(),
},
});
}
let mut trait_implementations = Vec::new();
for implementation in &module.declarations.trait_implementations {
if !belongs_to_extension(&implementation.owner, prefix) {
continue;
}
let implementation_path = if implementation.owner.is_empty() {
implementation.trait_path.clone()
} else {
format!("{}.{}", implementation.owner, implementation.trait_path)
};
let associated_prefix = format!("{implementation_path}.");
let associated_types = module
.declarations
.symbols
.values()
.filter_map(|symbol| {
let CollectedSymbolKind::AssociatedType {
binding: Some(binding),
} = &symbol.kind
else {
return None;
};
let name = symbol.path.strip_prefix(&associated_prefix)?;
(!name.contains('.')).then_some((name.to_owned(), binding.clone()))
})
.collect();
trait_implementations.push(ActiveTraitImplementation {
trait_path: implementation.trait_path.clone(),
span: implementation.span,
associated_types,
});
}
Ok(ActiveExtension {
origin_module: origin_module.to_owned(),
symbol: metadata.symbol.clone(),
target,
generic_parameters: metadata
.parameters
.iter()
.map(|parameter| parameter.name.clone())
.collect(),
target_arguments: metadata.target_arguments.clone(),
functions,
trait_implementations,
})
}
fn find_extension<'a>(
extensions: &'a [CollectedExtension],
symbol: Option<&str>,
) -> Option<&'a CollectedExtension> {
extensions
.iter()
.find(|extension| extension.symbol.as_deref() == symbol)
}
fn belongs_to_extension(path: &str, prefix: Option<&str>) -> bool {
match prefix {
None => true,
Some(prefix) => path == prefix || path.starts_with(&format!("{prefix}.")),
}
}
fn relative_to_extension(path: &str, prefix: Option<&str>) -> Option<String> {
match prefix {
None => Some(path.to_owned()),
Some(prefix) => path
.strip_prefix(prefix)
.and_then(|path| path.strip_prefix('.'))
.map(str::to_owned),
}
}
fn extension_name(extension: &ActiveExtension) -> String {
match &extension.symbol {
Some(symbol) => format!("{}::{symbol}", extension.origin_module),
None => extension.origin_module.clone(),
}
}
fn detect_conflicts(extensions: &[ActiveExtension], errors: &mut Vec<ExtensionActivationError>) {
let mut functions = BTreeMap::<(CanonicalSymbolPath, String), String>::new();
let mut traits = BTreeMap::<(CanonicalSymbolPath, String), String>::new();
for extension in extensions {
let name = extension_name(extension);
for function in &extension.functions {
let key = (extension.target.clone(), function.relative_path.clone());
if let Some(first) = functions.insert(key, name.clone()) {
errors.push(ExtensionActivationError::FunctionConflict {
target: extension.target.clone(),
relative_path: function.relative_path.clone(),
first_extension: first,
second_extension: name.clone(),
});
}
}
for implementation in &extension.trait_implementations {
let key = (extension.target.clone(), implementation.trait_path.clone());
if let Some(first) = traits.insert(key, name.clone()) {
errors.push(ExtensionActivationError::TraitImplementationConflict {
target: extension.target.clone(),
trait_path: implementation.trait_path.clone(),
first_extension: first,
second_extension: name.clone(),
});
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::{SourceFile, parse_file};
use crate::semantic::DeclarationIndex;
fn insert(graph: &mut ModuleGraph, path: &str, source: &str) {
let parsed = parse_file(SourceFile { path, text: source }).unwrap();
graph
.insert(path, DeclarationIndex::collect(&parsed).unwrap())
.unwrap();
}
fn base_graph() -> ModuleGraph {
let mut graph = ModuleGraph::default();
insert(&mut graph, "lib://types.lt", "pub acs Target: struct");
insert(
&mut graph,
"lib://extension.lt",
"acs types: \"lib://types.lt\" as extension for types.Target acs extra: fn()",
);
graph
}
#[test]
fn file_extension_is_active_only_when_its_module_is_imported() {
let mut graph = base_graph();
insert(&mut graph, "app://without.lt", "");
insert(
&mut graph,
"app://with.lt",
"acs ext_module: \"lib://extension.lt\"",
);
assert!(
ExtensionEnvironment::build(&graph, "app://without.lt")
.unwrap()
.extensions
.is_empty()
);
let environment = ExtensionEnvironment::build(&graph, "app://with.lt").unwrap();
assert_eq!(environment.extensions.len(), 1);
assert_eq!(environment.extensions[0].target.module, "lib://types.lt");
assert_eq!(environment.extensions[0].target.local, "Target");
assert_eq!(
environment.extensions[0].functions[0].relative_path,
"extra"
);
}
#[test]
fn named_extension_requires_an_explicit_symbol_import() {
let mut graph = ModuleGraph::default();
insert(&mut graph, "lib://types.lt", "pub acs Target: struct");
insert(
&mut graph,
"lib://named.lt",
"acs types: \"lib://types.lt\" pub acs named: extension for types.Target { acs extra: fn() }",
);
insert(
&mut graph,
"app://module-only.lt",
"acs extensions: \"lib://named.lt\"",
);
insert(
&mut graph,
"app://selected.lt",
"acs extensions: \"lib://named.lt\" acs selected: extensions.named",
);
assert!(
ExtensionEnvironment::build(&graph, "app://module-only.lt")
.unwrap()
.extensions
.is_empty()
);
let selected = ExtensionEnvironment::build(&graph, "app://selected.lt").unwrap();
assert_eq!(selected.extensions.len(), 1);
assert_eq!(selected.extensions[0].symbol.as_deref(), Some("named"));
}
#[test]
fn reports_conflicting_visible_extension_functions() {
let mut graph = base_graph();
insert(
&mut graph,
"lib://other-extension.lt",
"acs types: \"lib://types.lt\" as extension for types.Target acs extra: fn()",
);
insert(
&mut graph,
"app://main.lt",
"acs first: \"lib://extension.lt\" acs second: \"lib://other-extension.lt\"",
);
let errors = ExtensionEnvironment::build(&graph, "app://main.lt").unwrap_err();
assert!(errors.iter().any(|error| matches!(
error,
ExtensionActivationError::FunctionConflict { relative_path, .. }
if relative_path == "extra"
)));
}
}