use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;
use crate::parsing::{
ParsedFile, Span,
ast::{
ContractAccessPath, ContractDeclarationKind, ContractDefinitionContent, ContractSource,
GenericDeclarationItem, GenericDeclarationTypeItemConstraint, GenericItem,
LayoutContractDeclaration, ValueType,
},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TraitId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ConstantId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclarationIds {
pub function: Option<crate::semantic::metadata::FunctionId>,
pub type_: Option<crate::semantic::metadata::TypeId>,
pub trait_: Option<TraitId>,
pub constant: Option<ConstantId>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollectedSymbolKind {
Declaration(DeclarationIds),
Namespace,
Alias {
parameters: Vec<CollectedGenericParameter>,
target: CollectedAliasTarget,
},
ModuleAlias {
source: String,
},
Extension {
target: String,
},
AssociatedType {
binding: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollectedGenericParameterKind {
Type { constraints: Vec<String> },
Lifetime,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectedGenericParameter {
pub name: String,
pub kind: CollectedGenericParameterKind,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectedAliasTarget {
pub path: String,
pub arguments: Vec<CollectedAliasArgument>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollectedAliasArgument {
TypeParameter(String),
LifetimeParameter(String),
TypePath(String),
Lifetime(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectedSymbol {
pub path: String,
pub span: Span,
pub public: bool,
pub generic_parameters: Vec<CollectedGenericParameter>,
pub kind: CollectedSymbolKind,
}
#[derive(Debug, Clone)]
pub struct CollectedExtension {
pub symbol: Option<String>,
pub target: String,
pub parameters: Vec<CollectedGenericParameter>,
pub target_arguments: Vec<CollectedAliasArgument>,
pub span: Span,
}
#[derive(Debug, Clone)]
pub struct CollectedTraitImplementation {
pub owner: String,
pub trait_path: String,
pub span: Span,
}
#[derive(Debug, Clone, Default)]
pub struct DeclarationIndex {
pub symbols: BTreeMap<String, CollectedSymbol>,
pub dependencies: BTreeSet<String>,
pub extensions: Vec<CollectedExtension>,
pub trait_implementations: Vec<CollectedTraitImplementation>,
next_function_id: u32,
next_type_id: u32,
next_trait_id: u32,
next_constant_id: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeclarationCollectionError {
Duplicate {
path: String,
first_span: Span,
duplicate_span: Span,
},
InvalidStringId {
id: u32,
},
InvalidExtensionTarget {
span: Span,
},
InvalidAliasArgument {
span: Span,
},
DuplicateGenericParameter {
name: String,
first_span: Span,
duplicate_span: Span,
},
InvalidAssociatedTypeContext {
path: String,
span: Span,
},
AssociatedTypeRequirementHasBinding {
path: String,
span: Span,
},
AssociatedTypeImplementationMissingBinding {
path: String,
span: Span,
},
MissingAssociatedTypeImplementation {
implementation: String,
name: String,
span: Span,
},
UnknownAssociatedTypeImplementation {
path: String,
span: Span,
},
}
impl fmt::Display for DeclarationCollectionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Duplicate { path, .. } => write!(formatter, "duplicate declaration `{path}`"),
Self::InvalidStringId { id } => {
write!(formatter, "AST contains invalid StringId({id})")
}
Self::InvalidExtensionTarget { .. } => {
formatter.write_str("extension target must be a named type path")
}
Self::InvalidAliasArgument { .. } => {
formatter.write_str("generic alias argument is not supported")
}
Self::DuplicateGenericParameter { name, .. } => {
write!(formatter, "duplicate generic parameter `{name}`")
}
Self::InvalidAssociatedTypeContext { path, .. } => write!(
formatter,
"associated type `{path}` must be declared in a trait or trait implementation"
),
Self::AssociatedTypeRequirementHasBinding { path, .. } => write!(
formatter,
"associated type requirement `{path}` cannot have a binding"
),
Self::AssociatedTypeImplementationMissingBinding { path, .. } => write!(
formatter,
"associated type implementation `{path}` requires a binding"
),
Self::MissingAssociatedTypeImplementation {
implementation,
name,
..
} => write!(
formatter,
"trait implementation `{implementation}` is missing associated type `{name}`"
),
Self::UnknownAssociatedTypeImplementation { path, .. } => write!(
formatter,
"associated type binding `{path}` is not declared by the implemented trait"
),
}
}
}
impl Error for DeclarationCollectionError {}
impl DeclarationIndex {
pub fn collect(file: &ParsedFile) -> Result<Self, Vec<DeclarationCollectionError>> {
let mut collector = Collector {
file,
index: Self::default(),
errors: Vec::new(),
};
collector.collect_file_extensions();
collector.collect_content("", &file.ast.contract_definition_content);
collector.validate_associated_types();
if collector.errors.is_empty() {
Ok(collector.index)
} else {
Err(collector.errors)
}
}
pub fn symbol(&self, path: &str) -> Option<&CollectedSymbol> {
self.symbols.get(path)
}
}
struct Collector<'a> {
file: &'a ParsedFile,
index: DeclarationIndex,
errors: Vec<DeclarationCollectionError>,
}
impl Collector<'_> {
fn validate_associated_types(&mut self) {
let implementation_parents = self
.index
.trait_implementations
.iter()
.map(|implementation| join_path(&implementation.owner, &implementation.trait_path))
.collect::<BTreeSet<_>>();
for symbol in self.index.symbols.values() {
let CollectedSymbolKind::AssociatedType { binding } = &symbol.kind else {
continue;
};
let Some((parent, _)) = symbol.path.rsplit_once('.') else {
self.errors
.push(DeclarationCollectionError::InvalidAssociatedTypeContext {
path: symbol.path.clone(),
span: symbol.span,
});
continue;
};
let trait_parent = self.index.symbols.get(parent).is_some_and(|parent| {
matches!(
parent.kind,
CollectedSymbolKind::Declaration(DeclarationIds {
trait_: Some(_),
..
})
)
});
if trait_parent {
if binding.is_some() {
self.errors.push(
DeclarationCollectionError::AssociatedTypeRequirementHasBinding {
path: symbol.path.clone(),
span: symbol.span,
},
);
}
} else if implementation_parents.contains(parent) {
if binding.is_none() {
self.errors.push(
DeclarationCollectionError::AssociatedTypeImplementationMissingBinding {
path: symbol.path.clone(),
span: symbol.span,
},
);
}
} else {
self.errors
.push(DeclarationCollectionError::InvalidAssociatedTypeContext {
path: symbol.path.clone(),
span: symbol.span,
});
}
}
for implementation in &self.index.trait_implementations {
let Some(CollectedSymbol {
kind:
CollectedSymbolKind::Declaration(DeclarationIds {
trait_: Some(_), ..
}),
..
}) = self.index.symbols.get(&implementation.trait_path)
else {
continue;
};
let trait_prefix = format!("{}.", implementation.trait_path);
let requirements = self
.index
.symbols
.values()
.filter_map(|symbol| {
let name = symbol.path.strip_prefix(&trait_prefix)?;
(!name.contains('.')
&& matches!(
symbol.kind,
CollectedSymbolKind::AssociatedType { binding: None }
))
.then_some((name.to_owned(), symbol.span))
})
.collect::<BTreeMap<_, _>>();
let implementation_path = join_path(&implementation.owner, &implementation.trait_path);
let implementation_prefix = format!("{implementation_path}.");
let bindings = self
.index
.symbols
.values()
.filter_map(|symbol| {
let name = symbol.path.strip_prefix(&implementation_prefix)?;
(!name.contains('.')
&& matches!(
symbol.kind,
CollectedSymbolKind::AssociatedType { binding: Some(_) }
))
.then_some((name.to_owned(), symbol))
})
.collect::<BTreeMap<_, _>>();
for (name, requirement_span) in &requirements {
if !bindings.contains_key(name) {
self.errors.push(
DeclarationCollectionError::MissingAssociatedTypeImplementation {
implementation: implementation_path.clone(),
name: name.clone(),
span: *requirement_span,
},
);
}
}
for (name, binding) in bindings {
if !requirements.contains_key(&name) {
self.errors.push(
DeclarationCollectionError::UnknownAssociatedTypeImplementation {
path: binding.path.clone(),
span: binding.span,
},
);
}
}
}
}
fn collect_file_extensions(&mut self) {
for declaration in &self.file.ast.file_contract_declarations {
if let ContractDeclarationKind::ExtensionOnly(extension) = &declaration.kind {
if let Some((target, target_arguments)) =
self.extension_target_template(&extension.target, &[])
{
self.index.extensions.push(CollectedExtension {
symbol: None,
target,
parameters: Vec::new(),
target_arguments,
span: extension.span,
});
}
}
}
}
fn collect_content(&mut self, prefix: &str, content: &ContractDefinitionContent) {
for declaration in &content.contract_accesses {
let Some(name) = self.string(declaration.ident.string.0) else {
continue;
};
let path = join_path(prefix, name);
let public = declaration.pub_visible.is_some();
let Some(parameters) =
self.generic_parameters(declaration.generic_declaration_list.as_ref())
else {
continue;
};
let kind = match &declaration.source {
ContractSource::Access(target) => {
let Some(target) = self.alias_target(target, ¶meters) else {
continue;
};
CollectedSymbolKind::Alias {
parameters: parameters.clone(),
target,
}
}
ContractSource::File(source) => {
let Some(source) = self.string(source.string.0).map(str::to_owned) else {
continue;
};
self.index.dependencies.insert(source.clone());
CollectedSymbolKind::ModuleAlias { source }
}
ContractSource::Definition(definition) => {
self.collect_content(&path, &definition.content);
CollectedSymbolKind::Namespace
}
ContractSource::Declaration(declaration) => {
if let ContractDeclarationKind::AssociatedTypeOnly(type_) = &declaration.kind {
let binding = type_
.value_type
.as_ref()
.and_then(|value_type| self.extension_target(value_type));
CollectedSymbolKind::AssociatedType { binding }
} else if let ContractDeclarationKind::ExtensionOnly(extension) =
&declaration.kind
{
let Some((target, target_arguments)) =
self.extension_target_template(&extension.target, ¶meters)
else {
continue;
};
self.index.extensions.push(CollectedExtension {
symbol: Some(path.clone()),
target: target.clone(),
parameters: parameters.clone(),
target_arguments,
span: extension.span,
});
if let Some(definition) = &declaration.definition {
self.collect_content(&path, &definition.content);
}
CollectedSymbolKind::Extension { target }
} else {
let ids = self.ids_for(&declaration.kind);
if let Some(definition) = &declaration.definition {
self.collect_content(&path, &definition.content);
}
CollectedSymbolKind::Declaration(ids)
}
}
};
self.insert(CollectedSymbol {
path,
span: declaration.span,
public,
generic_parameters: parameters,
kind,
});
}
for implementation in &content.trait_implementations {
let Some(trait_path) = self.access_path(&implementation.trait_path) else {
continue;
};
self.index
.trait_implementations
.push(CollectedTraitImplementation {
owner: prefix.to_owned(),
trait_path: trait_path.clone(),
span: implementation.span,
});
if let Some(definition) = &implementation.definition {
let implementation_path = join_path(prefix, &trait_path);
self.collect_content(&implementation_path, &definition.content);
}
}
}
fn ids_for(&mut self, kind: &ContractDeclarationKind) -> DeclarationIds {
let mut ids = DeclarationIds::default();
match kind {
ContractDeclarationKind::FunctionOnly(_) => ids.function = Some(self.function_id()),
ContractDeclarationKind::ConstantOnly(_) => ids.constant = Some(self.constant_id()),
ContractDeclarationKind::AssociatedTypeOnly(_)
| ContractDeclarationKind::ExtensionOnly(_) => {}
ContractDeclarationKind::LayoutOnly(layout) => self.assign_layout(layout, &mut ids),
ContractDeclarationKind::FunctionAndLayout(declaration) => {
ids.function = Some(self.function_id());
self.assign_layout(&declaration.layout, &mut ids);
}
}
ids
}
fn assign_layout(&mut self, layout: &LayoutContractDeclaration, ids: &mut DeclarationIds) {
if matches!(layout, LayoutContractDeclaration::Trait(_)) {
ids.trait_ = Some(self.trait_id());
} else {
ids.type_ = Some(self.type_id());
}
}
fn insert(&mut self, symbol: CollectedSymbol) {
if let Some(first) = self.index.symbols.get(&symbol.path) {
self.errors.push(DeclarationCollectionError::Duplicate {
path: symbol.path,
first_span: first.span,
duplicate_span: symbol.span,
});
} else {
self.index.symbols.insert(symbol.path.clone(), symbol);
}
}
fn generic_parameters(
&mut self,
list: Option<&crate::parsing::ast::GenericDeclarationList>,
) -> Option<Vec<CollectedGenericParameter>> {
let Some(list) = list else {
return Some(Vec::new());
};
let mut parameters = Vec::new();
let mut seen = BTreeMap::<String, Span>::new();
for item in std::iter::once(&list.items.0).chain(list.items.1.iter()) {
let parameter = match item {
GenericDeclarationItem::Lifetime(lifetime) => CollectedGenericParameter {
name: self.string(lifetime.string.0)?.to_owned(),
kind: CollectedGenericParameterKind::Lifetime,
span: lifetime.span,
},
GenericDeclarationItem::Type(type_) => {
let mut constraints = Vec::new();
for constraint in &type_.constraints {
constraints.push(match constraint {
GenericDeclarationTypeItemConstraint::Lifetime(lifetime) => {
format!("'{}", self.string(lifetime.string.0)?)
}
GenericDeclarationTypeItemConstraint::Type(path) => {
self.access_path(path)?
}
});
}
CollectedGenericParameter {
name: self.string(type_.ident.string.0)?.to_owned(),
kind: CollectedGenericParameterKind::Type { constraints },
span: type_.span,
}
}
};
if let Some(first_span) = seen.insert(parameter.name.clone(), parameter.span) {
self.errors
.push(DeclarationCollectionError::DuplicateGenericParameter {
name: parameter.name,
first_span,
duplicate_span: parameter.span,
});
return None;
}
parameters.push(parameter);
}
Some(parameters)
}
fn alias_target(
&mut self,
path: &ContractAccessPath,
parameters: &[CollectedGenericParameter],
) -> Option<CollectedAliasTarget> {
let parameter_kinds = parameters
.iter()
.map(|parameter| (parameter.name.as_str(), ¶meter.kind))
.collect::<BTreeMap<_, _>>();
let mut arguments = Vec::new();
for part in std::iter::once(&path.parts.0).chain(path.parts.1.iter()) {
if let Some(generics) = &part.generic_list {
for argument in std::iter::once(&generics.items.0).chain(generics.items.1.iter()) {
let collected = match argument {
GenericItem::Lifetime(lifetime) => {
let name = self.string(lifetime.string.0)?.to_owned();
if matches!(
parameter_kinds.get(name.as_str()),
Some(CollectedGenericParameterKind::Lifetime)
) {
CollectedAliasArgument::LifetimeParameter(name)
} else {
CollectedAliasArgument::Lifetime(name)
}
}
GenericItem::ValueType(ValueType::ContractSource(source)) => {
let ContractSource::Access(type_path) = source.as_ref() else {
self.errors.push(
DeclarationCollectionError::InvalidAliasArgument {
span: argument.span(),
},
);
return None;
};
let type_path_text = self.access_path(type_path)?;
if type_path.parts.1.is_empty()
&& type_path.parts.0.generic_list.is_none()
&& matches!(
parameter_kinds.get(type_path_text.as_str()),
Some(CollectedGenericParameterKind::Type { .. })
)
{
CollectedAliasArgument::TypeParameter(type_path_text)
} else {
CollectedAliasArgument::TypePath(type_path_text)
}
}
_ => {
self.errors
.push(DeclarationCollectionError::InvalidAliasArgument {
span: argument.span(),
});
return None;
}
};
arguments.push(collected);
}
}
}
Some(CollectedAliasTarget {
path: self.access_path(path)?,
arguments,
})
}
fn extension_target_template(
&mut self,
value_type: &ValueType,
parameters: &[CollectedGenericParameter],
) -> Option<(String, Vec<CollectedAliasArgument>)> {
if let ValueType::ContractSource(source) = value_type
&& let ContractSource::Access(path) = source.as_ref()
{
let target = self.alias_target(path, parameters)?;
return Some((target.path, target.arguments));
}
self.errors
.push(DeclarationCollectionError::InvalidExtensionTarget {
span: value_type.span(),
});
None
}
fn extension_target(&mut self, value_type: &ValueType) -> Option<String> {
if let ValueType::ContractSource(source) = value_type
&& let ContractSource::Access(path) = source.as_ref()
{
return self.access_path(path);
}
self.errors
.push(DeclarationCollectionError::InvalidExtensionTarget {
span: value_type.span(),
});
None
}
fn access_path(&mut self, path: &ContractAccessPath) -> Option<String> {
let mut names = Vec::with_capacity(path.parts.1.len() + 1);
names.push(self.string(path.parts.0.ident.string.0)?.to_owned());
for part in &path.parts.1 {
names.push(self.string(part.ident.string.0)?.to_owned());
}
Some(names.join("."))
}
fn string(&mut self, id: u32) -> Option<&str> {
match self.file.data.strings.get(id as usize) {
Some(value) => Some(value),
None => {
self.errors
.push(DeclarationCollectionError::InvalidStringId { id });
None
}
}
}
fn function_id(&mut self) -> u32 {
let id = self.index.next_function_id;
self.index.next_function_id = id.checked_add(1).expect("too many functions");
id
}
fn type_id(&mut self) -> u32 {
let id = self.index.next_type_id;
self.index.next_type_id = id.checked_add(1).expect("too many types");
id
}
fn trait_id(&mut self) -> TraitId {
let id = self.index.next_trait_id;
self.index.next_trait_id = id.checked_add(1).expect("too many traits");
TraitId(id)
}
fn constant_id(&mut self) -> ConstantId {
let id = self.index.next_constant_id;
self.index.next_constant_id = id.checked_add(1).expect("too many constants");
ConstantId(id)
}
}
fn join_path(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_owned()
} else {
format!("{prefix}.{name}")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::{SourceFile, parse_file};
#[test]
fn collects_core_dependencies_and_nested_declarations() {
let parsed = parse_file(SourceFile {
path: "core://primitive.lt",
text: crate::core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
assert_eq!(
index.dependencies,
BTreeSet::from([
"core://clone.lt".into(),
"core://cmp.lt".into(),
"core://ops.lt".into(),
])
);
assert!(matches!(
index.symbol("i8").map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::Namespace)
));
assert!(matches!(
index.symbol("i8.Add.add").map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::Declaration(DeclarationIds {
function: Some(_),
..
}))
));
}
#[test]
fn assigns_trait_ids() {
let parsed = parse_file(SourceFile {
path: "core://ops.lt",
text: crate::core_lib::OPS_MODULE_FILE_CONTENT,
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
assert!(matches!(
index.symbol("Add").map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::Declaration(DeclarationIds {
trait_: Some(TraitId(0)),
..
}))
));
assert!(index.symbol("Add.add").is_some());
}
#[test]
fn preserves_generic_alias_parameters_and_arguments() {
let parsed = parse_file(SourceFile {
path: "test://aliases.lt",
text: "acs function<'a, T>: module.function<'a, T> acs OptionType: Option<Type>",
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
let CollectedSymbolKind::Alias { parameters, target } =
&index.symbol("function").unwrap().kind
else {
panic!("function must be a generic alias")
};
assert_eq!(parameters.len(), 2);
assert!(matches!(
parameters[0].kind,
CollectedGenericParameterKind::Lifetime
));
assert!(matches!(
parameters[1].kind,
CollectedGenericParameterKind::Type { .. }
));
assert_eq!(target.path, "module.function");
assert_eq!(
target.arguments,
vec![
CollectedAliasArgument::LifetimeParameter("a".into()),
CollectedAliasArgument::TypeParameter("T".into()),
]
);
let CollectedSymbolKind::Alias { parameters, target } =
&index.symbol("OptionType").unwrap().kind
else {
panic!("OptionType must be an alias")
};
assert!(parameters.is_empty());
assert_eq!(target.path, "Option");
assert_eq!(
target.arguments,
vec![CollectedAliasArgument::TypePath("Type".into())]
);
}
#[test]
fn collects_associated_type_requirements_and_bindings_without_type_ids() {
let parsed = parse_file(SourceFile {
path: "test://associated-types.lt",
text: "pub acs ZeroablePrimitive: trait {
acs NonZeroInner: type
}
acs ext: extension for U32 {
impl ZeroablePrimitive {
acs NonZeroInner: type = NonZeroU32
}
}",
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
assert!(matches!(
index
.symbol("ZeroablePrimitive.NonZeroInner")
.map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::AssociatedType { binding: None })
));
assert!(matches!(
index
.symbol("ext.ZeroablePrimitive.NonZeroInner")
.map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::AssociatedType { binding: Some(binding) })
if binding == "NonZeroU32"
));
}
#[test]
fn rejects_associated_types_outside_their_required_contexts() {
let global = parse_file(SourceFile {
path: "test://global-associated.lt",
text: "acs Item: type",
})
.unwrap();
assert!(matches!(
&DeclarationIndex::collect(&global).unwrap_err()[0],
DeclarationCollectionError::InvalidAssociatedTypeContext { path, .. }
if path == "Item"
));
let trait_binding = parse_file(SourceFile {
path: "test://trait-associated-binding.lt",
text: "acs Trait: trait { acs Item: type = Value }",
})
.unwrap();
assert!(matches!(
&DeclarationIndex::collect(&trait_binding).unwrap_err()[0],
DeclarationCollectionError::AssociatedTypeRequirementHasBinding { path, .. }
if path == "Trait.Item"
));
let missing_binding = parse_file(SourceFile {
path: "test://missing-associated-binding.lt",
text: "acs ext: extension for Value { impl Trait { acs Item: type } }",
})
.unwrap();
assert!(matches!(
&DeclarationIndex::collect(&missing_binding).unwrap_err()[0],
DeclarationCollectionError::AssociatedTypeImplementationMissingBinding { path, .. }
if path == "ext.Trait.Item"
));
let incomplete = parse_file(SourceFile {
path: "test://incomplete-associated.lt",
text: "acs Trait: trait { acs Item: type }
acs ext: extension for Value { impl Trait { } }",
})
.unwrap();
assert!(
DeclarationIndex::collect(&incomplete)
.unwrap_err()
.iter()
.any(|error| matches!(
error,
DeclarationCollectionError::MissingAssociatedTypeImplementation {
implementation,
name,
..
} if implementation == "ext.Trait" && name == "Item"
))
);
let unknown = parse_file(SourceFile {
path: "test://unknown-associated.lt",
text: "acs Trait: trait
acs ext: extension for Value {
impl Trait { acs Item: type = Bound }
}",
})
.unwrap();
assert!(
DeclarationIndex::collect(&unknown)
.unwrap_err()
.iter()
.any(|error| matches!(
error,
DeclarationCollectionError::UnknownAssociatedTypeImplementation { path, .. }
if path == "ext.Trait.Item"
))
);
}
#[test]
fn rejects_duplicate_generic_parameters() {
let parsed = parse_file(SourceFile {
path: "test://duplicate-generics.lt",
text: "acs duplicate<T, T>: Target<T>",
})
.unwrap();
let errors = DeclarationIndex::collect(&parsed).unwrap_err();
assert!(matches!(
&errors[0],
DeclarationCollectionError::DuplicateGenericParameter { name, .. } if name == "T"
));
}
#[test]
fn collects_named_and_file_wide_extensions() {
let parsed = parse_file(SourceFile {
path: "test://extensions.lt",
text: "as extension for Target acs ext: extension for Target { acs method: fn() }",
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
assert_eq!(index.extensions.len(), 2);
assert_eq!(index.extensions[0].symbol, None);
assert_eq!(index.extensions[0].target, "Target");
assert_eq!(index.extensions[1].symbol.as_deref(), Some("ext"));
assert!(matches!(
index.symbol("ext").map(|symbol| &symbol.kind),
Some(CollectedSymbolKind::Extension { target }) if target == "Target"
));
assert!(index.symbol("ext.method").is_some());
}
#[test]
fn preserves_generic_parameter_kinds_for_type_declarations() {
let parsed = parse_file(SourceFile {
path: "test://generic-metadata.lt",
text: "acs Value<'a, T>: struct { fld value: T }",
})
.unwrap();
let index = DeclarationIndex::collect(&parsed).unwrap();
let parameters = &index.symbol("Value").unwrap().generic_parameters;
assert_eq!(parameters.len(), 2);
assert!(matches!(
parameters[0].kind,
CollectedGenericParameterKind::Lifetime
));
assert!(matches!(
parameters[1].kind,
CollectedGenericParameterKind::Type { .. }
));
}
#[test]
fn rejects_duplicate_paths() {
let parsed = parse_file(SourceFile {
path: "test://duplicates.lt",
text: "acs same: fn() acs same: fn()",
})
.unwrap();
let errors = DeclarationIndex::collect(&parsed).unwrap_err();
assert_eq!(errors.len(), 1);
assert!(matches!(
&errors[0],
DeclarationCollectionError::Duplicate { path, .. } if path == "same"
));
}
}