use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use crate::parsing::{
ParsedFile, Span,
ast::{
ContractAccessPath, ContractDeclarationKind, ContractSource, FunctionContractDeclaration,
FunctionContractDeclarationSelfArgumentKind, GenericDeclarationItem,
GenericDeclarationList, GenericItem, ValueType,
},
};
use crate::semantic::{
CanonicalSymbolPath, CollectedAliasArgument, CollectedAliasTarget, CollectedGenericParameter,
CollectedGenericParameterKind, CollectedSymbolKind, ExtensionEnvironment, MethodLookupError,
MethodTable, ModuleGraph, ModuleGraphError,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SemanticType {
Void,
SelfType,
Parameter(SemanticGenericParameter),
Associated {
owner: Box<SemanticType>,
name: String,
},
Named(SemanticNamedType),
Array {
item: Box<SemanticType>,
size: Option<usize>,
},
Tuple(Vec<SemanticType>),
Function(Box<SemanticFunctionType>),
Reference {
lifetime: Option<SemanticLifetime>,
mutable: bool,
target: Box<SemanticType>,
},
Pointer {
mutable: bool,
target: Box<SemanticType>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticNamedType {
pub path: CanonicalSymbolPath,
pub generic_arguments: Vec<SemanticGenericArgument>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SemanticGenericArgument {
Type(SemanticType),
Lifetime(SemanticLifetime),
}
impl SemanticGenericArgument {
pub fn type_(type_: impl Into<SemanticType>) -> Self {
Self::Type(type_.into())
}
pub fn lifetime(lifetime: SemanticLifetime) -> Self {
Self::Lifetime(lifetime)
}
pub fn named_lifetime(name: impl Into<String>) -> Self {
Self::Lifetime(SemanticLifetime::Named(name.into()))
}
}
impl SemanticNamedType {
pub fn new(path: CanonicalSymbolPath) -> Self {
Self {
path,
generic_arguments: Vec::new(),
}
}
pub fn from_parts(module: impl Into<String>, local: impl Into<String>) -> Self {
Self::new(CanonicalSymbolPath {
module: module.into(),
local: local.into(),
})
}
pub fn with_argument(mut self, argument: SemanticGenericArgument) -> Self {
self.generic_arguments.push(argument);
self
}
pub fn with_type_argument(self, argument: impl Into<SemanticType>) -> Self {
self.with_argument(SemanticGenericArgument::type_(argument))
}
pub fn with_lifetime_argument(self, lifetime: SemanticLifetime) -> Self {
self.with_argument(SemanticGenericArgument::lifetime(lifetime))
}
pub fn with_named_lifetime_argument(self, name: impl Into<String>) -> Self {
self.with_argument(SemanticGenericArgument::named_lifetime(name))
}
}
impl SemanticType {
pub fn named(path: CanonicalSymbolPath) -> Self {
Self::Named(SemanticNamedType::new(path))
}
pub fn named_from_parts(module: impl Into<String>, local: impl Into<String>) -> Self {
Self::Named(SemanticNamedType::from_parts(module, local))
}
}
impl From<SemanticNamedType> for SemanticType {
fn from(type_: SemanticNamedType) -> Self {
Self::Named(type_)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GenericParameterId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemanticGenericParameterKind {
Type,
Lifetime,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticGenericParameter {
pub id: GenericParameterId,
pub name: String,
pub kind: SemanticGenericParameterKind,
pub constraints: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SemanticLifetime {
Named(String),
Parameter(SemanticGenericParameter),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticFunctionType {
pub receiver: Option<SemanticReceiver>,
pub arguments: Vec<SemanticFunctionArgument>,
pub return_type: Box<SemanticType>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticReceiver {
pub borrow: bool,
pub lifetime: Option<SemanticLifetime>,
pub mutable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticFunctionArgument {
pub name: String,
pub mutable: bool,
pub type_: SemanticType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeLoweringError {
Resolution(ModuleGraphError),
InvalidStringId {
id: u32,
},
InvalidTypeSource {
span: Span,
},
ExpectedType {
module: String,
path: String,
span: Span,
},
DuplicateGenericParameter {
name: String,
span: Span,
},
GenericParameterKindMismatch {
name: String,
expected: SemanticGenericParameterKind,
span: Span,
},
GenericArityMismatch {
alias: String,
expected: usize,
actual: usize,
span: Span,
},
GenericArgumentKindMismatch {
alias: String,
parameter: String,
span: Span,
},
}
impl fmt::Display for TypeLoweringError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Resolution(error) => error.fmt(formatter),
Self::InvalidStringId { id } => write!(formatter, "invalid StringId({id}) in AST"),
Self::InvalidTypeSource { .. } => {
formatter.write_str("type position requires a named type path")
}
Self::ExpectedType { module, path, .. } => {
write!(formatter, "`{module}::{path}` does not name a type")
}
Self::DuplicateGenericParameter { name, .. } => {
write!(formatter, "duplicate generic parameter `{name}`")
}
Self::GenericParameterKindMismatch { name, expected, .. } => {
write!(
formatter,
"generic parameter `{name}` is not a {expected:?} parameter"
)
}
Self::GenericArityMismatch {
alias,
expected,
actual,
..
} => write!(
formatter,
"generic alias `{alias}` expects {expected} arguments, got {actual}"
),
Self::GenericArgumentKindMismatch {
alias, parameter, ..
} => write!(
formatter,
"generic argument for `{alias}::{parameter}` has the wrong kind"
),
}
}
}
impl Error for TypeLoweringError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeNormalizationError {
MissingSubstitution(SemanticGenericParameter),
AssociatedOwnerIsNotNamed(SemanticType),
ExtensionEnvironment,
MethodLookup(MethodLookupError),
}
impl fmt::Display for TypeNormalizationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingSubstitution(parameter) => {
write!(formatter, "missing substitution for `{}`", parameter.name)
}
Self::AssociatedOwnerIsNotNamed(owner) => write!(
formatter,
"associated type owner remains non-concrete after substitution: {owner:?}"
),
Self::ExtensionEnvironment => {
formatter.write_str("failed to build the visible extension environment")
}
Self::MethodLookup(error) => error.fmt(formatter),
}
}
}
impl Error for TypeNormalizationError {}
impl From<MethodLookupError> for TypeNormalizationError {
fn from(value: MethodLookupError) -> Self {
Self::MethodLookup(value)
}
}
pub fn normalize_type(
type_: &SemanticType,
substitutions: &BTreeMap<GenericParameterId, SemanticType>,
graph: &ModuleGraph,
requesting_module: &str,
) -> Result<SemanticType, TypeNormalizationError> {
match type_ {
SemanticType::Void | SemanticType::SelfType => Ok(type_.clone()),
SemanticType::Parameter(parameter) => substitutions
.get(¶meter.id)
.cloned()
.ok_or_else(|| TypeNormalizationError::MissingSubstitution(parameter.clone())),
SemanticType::Associated { owner, name } => {
let constraints = match owner.as_ref() {
SemanticType::Parameter(parameter) => parameter.constraints.as_slice(),
_ => &[],
};
let owner = normalize_type(owner, substitutions, graph, requesting_module)?;
let SemanticType::Named(named) = owner else {
return Err(TypeNormalizationError::AssociatedOwnerIsNotNamed(owner));
};
let environment = ExtensionEnvironment::build(graph, requesting_module)
.map_err(|_| TypeNormalizationError::ExtensionEnvironment)?;
let table = MethodTable::build(graph, &named.path, &environment)?;
let binding = table.resolve_associated_type(
graph,
&named.path,
requesting_module,
constraints,
name,
)?;
Ok(SemanticType::Named(SemanticNamedType {
path: binding,
generic_arguments: Vec::new(),
}))
}
SemanticType::Named(named) => Ok(SemanticType::Named(SemanticNamedType {
path: named.path.clone(),
generic_arguments: named
.generic_arguments
.iter()
.map(|argument| match argument {
SemanticGenericArgument::Type(type_) => {
normalize_type(type_, substitutions, graph, requesting_module)
.map(SemanticGenericArgument::Type)
}
SemanticGenericArgument::Lifetime(lifetime) => {
Ok(SemanticGenericArgument::Lifetime(lifetime.clone()))
}
})
.collect::<Result<_, _>>()?,
})),
SemanticType::Array { item, size } => Ok(SemanticType::Array {
item: Box::new(normalize_type(
item,
substitutions,
graph,
requesting_module,
)?),
size: *size,
}),
SemanticType::Tuple(items) => Ok(SemanticType::Tuple(
items
.iter()
.map(|item| normalize_type(item, substitutions, graph, requesting_module))
.collect::<Result<_, _>>()?,
)),
SemanticType::Function(function) => {
Ok(SemanticType::Function(Box::new(SemanticFunctionType {
receiver: function.receiver.clone(),
arguments: function
.arguments
.iter()
.map(|argument| {
Ok(SemanticFunctionArgument {
name: argument.name.clone(),
mutable: argument.mutable,
type_: normalize_type(
&argument.type_,
substitutions,
graph,
requesting_module,
)?,
})
})
.collect::<Result<_, TypeNormalizationError>>()?,
return_type: Box::new(normalize_type(
&function.return_type,
substitutions,
graph,
requesting_module,
)?),
})))
}
SemanticType::Reference {
lifetime,
mutable,
target,
} => Ok(SemanticType::Reference {
lifetime: lifetime.clone(),
mutable: *mutable,
target: Box::new(normalize_type(
target,
substitutions,
graph,
requesting_module,
)?),
}),
SemanticType::Pointer { mutable, target } => Ok(SemanticType::Pointer {
mutable: *mutable,
target: Box::new(normalize_type(
target,
substitutions,
graph,
requesting_module,
)?),
}),
}
}
impl From<ModuleGraphError> for TypeLoweringError {
fn from(value: ModuleGraphError) -> Self {
Self::Resolution(value)
}
}
pub struct TypeLowerer<'a> {
graph: &'a ModuleGraph,
file: &'a ParsedFile,
module: &'a str,
generic_parameters: BTreeMap<String, SemanticGenericParameter>,
}
impl<'a> TypeLowerer<'a> {
pub fn new(graph: &'a ModuleGraph, file: &'a ParsedFile, module: &'a str) -> Self {
Self {
graph,
file,
module,
generic_parameters: BTreeMap::new(),
}
}
pub fn with_generic_parameters(
mut self,
parameters: Option<&GenericDeclarationList>,
) -> Result<Self, TypeLoweringError> {
let Some(parameters) = parameters else {
return Ok(self);
};
for (index, parameter) in std::iter::once(¶meters.items.0)
.chain(parameters.items.1.iter())
.enumerate()
{
let (name, kind, constraints, span) = match parameter {
GenericDeclarationItem::Lifetime(lifetime) => (
self.string(lifetime.string.0)?,
SemanticGenericParameterKind::Lifetime,
Vec::new(),
lifetime.span,
),
GenericDeclarationItem::Type(type_) => {
let constraints = type_
.constraints
.iter()
.filter_map(|constraint| match constraint {
crate::parsing::ast::GenericDeclarationTypeItemConstraint::Type(
path,
) => Some(self.path_text(path)),
crate::parsing::ast::GenericDeclarationTypeItemConstraint::Lifetime(
_,
) => None,
})
.collect::<Result<Vec<_>, _>>()?;
(
self.string(type_.ident.string.0)?,
SemanticGenericParameterKind::Type,
constraints,
type_.span,
)
}
};
let semantic = SemanticGenericParameter {
id: GenericParameterId(
u32::try_from(index).expect("generic parameter count exceeds u32"),
),
name: name.clone(),
kind,
constraints,
};
if self
.generic_parameters
.insert(name.clone(), semantic)
.is_some()
{
return Err(TypeLoweringError::DuplicateGenericParameter { name, span });
}
}
Ok(self)
}
pub fn generic_parameters(&self) -> Vec<SemanticGenericParameter> {
let mut parameters = self
.generic_parameters
.values()
.cloned()
.collect::<Vec<_>>();
parameters.sort_by_key(|parameter| parameter.id);
parameters
}
pub fn lower(&self, value_type: &ValueType) -> Result<SemanticType, TypeLoweringError> {
match value_type {
ValueType::Void(_) => Ok(SemanticType::Void),
ValueType::Array(array) => Ok(SemanticType::Array {
item: Box::new(self.lower(&array.value_type)?),
size: array.size.as_ref().map(|size| size.size),
}),
ValueType::Tuple(tuple) => {
let mut items = Vec::with_capacity(tuple.value_types.1.len() + 1);
items.push(self.lower(&tuple.value_types.0)?);
for item in &tuple.value_types.1 {
items.push(self.lower(item)?);
}
Ok(SemanticType::Tuple(items))
}
ValueType::ContractSource(source) => self.lower_contract_source(source),
ValueType::Function(function) => self
.lower_function(function)
.map(|function| SemanticType::Function(Box::new(function))),
ValueType::Reference(reference) => Ok(SemanticType::Reference {
lifetime: reference
.borrow
.lifetime
.as_ref()
.map(|lifetime| self.lower_lifetime(lifetime.string.0, lifetime.span))
.transpose()?,
mutable: reference.borrow.mutable.is_some(),
target: Box::new(self.lower(&reference.value_type)?),
}),
ValueType::Pointer(pointer) => Ok(SemanticType::Pointer {
mutable: pointer.mutable.is_some(),
target: Box::new(self.lower(&pointer.value_type)?),
}),
}
}
pub fn lower_function(
&self,
function: &FunctionContractDeclaration,
) -> Result<SemanticFunctionType, TypeLoweringError> {
let receiver = function
.argument_list
.self_argument
.as_ref()
.map(|receiver| -> Result<SemanticReceiver, TypeLoweringError> {
match &receiver.kind {
FunctionContractDeclarationSelfArgumentKind::Borrow(borrow) => {
Ok(SemanticReceiver {
borrow: true,
lifetime: borrow
.lifetime
.as_ref()
.map(|lifetime| {
self.lower_lifetime(lifetime.string.0, lifetime.span)
})
.transpose()?,
mutable: borrow.mutable.is_some(),
})
}
FunctionContractDeclarationSelfArgumentKind::Consume(mutable) => {
Ok(SemanticReceiver {
borrow: false,
lifetime: None,
mutable: mutable.is_some(),
})
}
}
})
.transpose()?;
let mut arguments = Vec::with_capacity(function.argument_list.other.len());
for argument in &function.argument_list.other {
arguments.push(SemanticFunctionArgument {
name: self.string(argument.ident.string.0)?,
mutable: argument.mutable.is_some(),
type_: self.lower(&argument.value_type)?,
});
}
let return_type = function
.output
.as_ref()
.map(|type_| self.lower(type_))
.transpose()?
.unwrap_or(SemanticType::Void);
Ok(SemanticFunctionType {
receiver,
arguments,
return_type: Box::new(return_type),
})
}
fn lower_contract_source(
&self,
source: &ContractSource,
) -> Result<SemanticType, TypeLoweringError> {
let ContractSource::Access(path) = source else {
return Err(TypeLoweringError::InvalidTypeSource {
span: source.span(),
});
};
let local_path = self.path_text(path)?;
if path.parts.1.is_empty()
&& path.parts.0.generic_list.is_none()
&& matches!(local_path.as_str(), "Self" | "self")
{
return Ok(SemanticType::SelfType);
}
if path.parts.1.len() == 1
&& path.parts.0.generic_list.is_none()
&& path.parts.1[0].generic_list.is_none()
{
let owner_name = self.string(path.parts.0.ident.string.0)?;
if matches!(owner_name.as_str(), "Self" | "self") {
let associated_name = self.string(path.parts.1[0].ident.string.0)?;
return Ok(SemanticType::Associated {
owner: Box::new(SemanticType::SelfType),
name: associated_name,
});
}
if let Some(parameter) = self.generic_parameters.get(&owner_name) {
if parameter.kind != SemanticGenericParameterKind::Type {
return Err(TypeLoweringError::GenericParameterKindMismatch {
name: owner_name,
expected: SemanticGenericParameterKind::Type,
span: path.parts.0.span,
});
}
let associated_name = self.string(path.parts.1[0].ident.string.0)?;
return Ok(SemanticType::Associated {
owner: Box::new(SemanticType::Parameter(parameter.clone())),
name: associated_name,
});
}
}
if path.parts.1.is_empty()
&& path.parts.0.generic_list.is_none()
&& let Some(parameter) = self.generic_parameters.get(&local_path)
{
if parameter.kind != SemanticGenericParameterKind::Type {
return Err(TypeLoweringError::GenericParameterKindMismatch {
name: local_path,
expected: SemanticGenericParameterKind::Type,
span: path.span,
});
}
return Ok(SemanticType::Parameter(parameter.clone()));
}
if let Ok(alias) = self.graph.resolve_declaration(self.module, &local_path)
&& let CollectedSymbolKind::Alias { parameters, target } = &alias.symbol.kind
{
let alias_lowerer = TypeLowerer {
graph: self.graph,
file: self.file,
module: alias.module_path,
generic_parameters: self.generic_parameters.clone(),
};
return alias_lowerer.lower_type_alias(path, alias.local_path, parameters, target);
}
let resolved = self.graph.resolve(self.module, &local_path)?;
let is_type = match &resolved.symbol.kind {
CollectedSymbolKind::Namespace => true,
CollectedSymbolKind::Declaration(ids) => ids.type_.is_some(),
_ => false,
};
if !is_type {
return Err(TypeLoweringError::ExpectedType {
module: resolved.module_path.to_owned(),
path: resolved.local_path.to_owned(),
span: path.span,
});
}
let mut generic_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 generic in std::iter::once(&generics.items.0).chain(generics.items.1.iter()) {
generic_arguments.push(match generic {
GenericItem::Lifetime(lifetime) => SemanticGenericArgument::Lifetime(
self.lower_lifetime(lifetime.string.0, lifetime.span)?,
),
GenericItem::ValueType(type_) => {
SemanticGenericArgument::Type(self.lower(type_)?)
}
});
}
}
}
Ok(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath::from_resolved(&resolved),
generic_arguments,
}))
}
fn lower_type_alias(
&self,
use_path: &ContractAccessPath,
alias: &str,
parameters: &[CollectedGenericParameter],
target: &CollectedAliasTarget,
) -> Result<SemanticType, TypeLoweringError> {
let arguments = self.lower_path_arguments(use_path)?;
if arguments.len() != parameters.len() {
return Err(TypeLoweringError::GenericArityMismatch {
alias: alias.to_owned(),
expected: parameters.len(),
actual: arguments.len(),
span: use_path.span,
});
}
let mut substitutions = BTreeMap::new();
for (parameter, argument) in parameters.iter().zip(arguments) {
let valid = matches!(
(¶meter.kind, &argument),
(
CollectedGenericParameterKind::Type { .. },
SemanticGenericArgument::Type(_)
) | (
CollectedGenericParameterKind::Lifetime,
SemanticGenericArgument::Lifetime(_)
)
);
if !valid {
return Err(TypeLoweringError::GenericArgumentKindMismatch {
alias: alias.to_owned(),
parameter: parameter.name.clone(),
span: use_path.span,
});
}
substitutions.insert(parameter.name.clone(), argument);
}
let mut target_arguments = Vec::with_capacity(target.arguments.len());
for argument in &target.arguments {
target_arguments.push(match argument {
CollectedAliasArgument::TypeParameter(name)
| CollectedAliasArgument::LifetimeParameter(name) => substitutions
.get(name)
.cloned()
.ok_or_else(|| TypeLoweringError::GenericArgumentKindMismatch {
alias: alias.to_owned(),
parameter: name.clone(),
span: use_path.span,
})?,
CollectedAliasArgument::TypePath(path) => {
SemanticGenericArgument::Type(self.lower_named_text(path, use_path.span)?)
}
CollectedAliasArgument::Lifetime(name) => {
SemanticGenericArgument::Lifetime(SemanticLifetime::Named(name.clone()))
}
});
}
let resolved = self.graph.resolve(self.module, &target.path)?;
self.ensure_type(&resolved, use_path.span)?;
Ok(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath::from_resolved(&resolved),
generic_arguments: target_arguments,
}))
}
fn lower_path_arguments(
&self,
path: &ContractAccessPath,
) -> Result<Vec<SemanticGenericArgument>, TypeLoweringError> {
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 generic in std::iter::once(&generics.items.0).chain(generics.items.1.iter()) {
arguments.push(match generic {
GenericItem::Lifetime(lifetime) => SemanticGenericArgument::Lifetime(
self.lower_lifetime(lifetime.string.0, lifetime.span)?,
),
GenericItem::ValueType(type_) => {
SemanticGenericArgument::Type(self.lower(type_)?)
}
});
}
}
}
Ok(arguments)
}
fn lower_named_text(&self, path: &str, span: Span) -> Result<SemanticType, TypeLoweringError> {
if let Some(parameter) = self.generic_parameters.get(path) {
if parameter.kind == SemanticGenericParameterKind::Type {
return Ok(SemanticType::Parameter(parameter.clone()));
}
}
let resolved = self.graph.resolve(self.module, path)?;
self.ensure_type(&resolved, span)?;
Ok(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath::from_resolved(&resolved),
generic_arguments: Vec::new(),
}))
}
fn ensure_type(
&self,
resolved: &crate::semantic::ResolvedSymbol<'_>,
span: Span,
) -> Result<(), TypeLoweringError> {
let is_type = match &resolved.symbol.kind {
CollectedSymbolKind::Namespace => true,
CollectedSymbolKind::Declaration(ids) => ids.type_.is_some(),
_ => false,
};
if is_type {
Ok(())
} else {
Err(TypeLoweringError::ExpectedType {
module: resolved.module_path.to_owned(),
path: resolved.local_path.to_owned(),
span,
})
}
}
fn lower_lifetime(&self, id: u32, span: Span) -> Result<SemanticLifetime, TypeLoweringError> {
let name = self.string(id)?;
match self.generic_parameters.get(&name) {
Some(parameter) if parameter.kind == SemanticGenericParameterKind::Lifetime => {
Ok(SemanticLifetime::Parameter(parameter.clone()))
}
Some(_) => Err(TypeLoweringError::GenericParameterKindMismatch {
name,
expected: SemanticGenericParameterKind::Lifetime,
span,
}),
None => Ok(SemanticLifetime::Named(name)),
}
}
fn path_text(&self, path: &ContractAccessPath) -> Result<String, TypeLoweringError> {
let mut parts = Vec::with_capacity(path.parts.1.len() + 1);
parts.push(self.string(path.parts.0.ident.string.0)?);
for part in &path.parts.1 {
parts.push(self.string(part.ident.string.0)?);
}
Ok(parts.join("."))
}
fn string(&self, id: u32) -> Result<String, TypeLoweringError> {
self.file
.data
.strings
.get(id as usize)
.cloned()
.ok_or(TypeLoweringError::InvalidStringId { id })
}
}
pub fn function_contract(source: &ContractSource) -> Option<&FunctionContractDeclaration> {
let ContractSource::Declaration(declaration) = source else {
return None;
};
match &declaration.kind {
ContractDeclarationKind::FunctionOnly(function) => Some(function),
ContractDeclarationKind::FunctionAndLayout(function) => Some(&function.function),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::{SourceFile, parse_file};
use crate::semantic::DeclarationIndex;
fn graph_with_app(path: &str, source: &str) -> (ModuleGraph, ParsedFile) {
let mut graph = ModuleGraph::default();
for (module_path, text) in [
("core://ops.lt", crate::core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", crate::core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
crate::core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
(
"core://prelude.lt",
crate::core_lib::PRELUDE_MODULE_FILE_CONTENT,
),
] {
let parsed = parse_file(SourceFile {
path: module_path,
text,
})
.unwrap();
graph
.insert(module_path, DeclarationIndex::collect(&parsed).unwrap())
.unwrap();
}
graph
.set_prelude(crate::core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let app = parse_file(SourceFile { path, text: source }).unwrap();
graph
.insert(path, DeclarationIndex::collect(&app).unwrap())
.unwrap();
(graph, app)
}
fn first_function(file: &ParsedFile) -> &FunctionContractDeclaration {
function_contract(&file.ast.contract_definition_content.contract_accesses[0].source)
.expect("first declaration must be a function")
}
#[test]
fn lowers_function_signature_and_preserves_pointer_qualifiers() {
let path = "app://types.lt";
let (graph, app) = graph_with_app(
path,
"acs check: fn(value: &'a mut i32, pointer: *const u8) -> [bool; 4]",
);
let signature = TypeLowerer::new(&graph, &app, path)
.lower_function(first_function(&app))
.unwrap();
assert_eq!(signature.arguments.len(), 2);
let SemanticType::Reference {
lifetime,
mutable,
target,
} = &signature.arguments[0].type_
else {
panic!("first argument must be a reference")
};
assert_eq!(lifetime, &Some(SemanticLifetime::Named("a".into())));
assert!(*mutable);
let SemanticType::Named(named) = target.as_ref() else {
panic!("reference target must be named")
};
assert_eq!(named.path.module, "core://primitive.lt");
assert_eq!(named.path.local, "i32");
assert!(matches!(
signature.arguments[1].type_,
SemanticType::Pointer { mutable: false, .. }
));
assert!(matches!(
signature.return_type.as_ref(),
SemanticType::Array { size: Some(4), .. }
));
}
#[test]
fn generic_scope_resolves_type_and_lifetime_parameters_before_modules() {
let path = "app://generic.lt";
let source = "pub acs Pair<X>: struct acs ext<'a, T>: extension for Pair<T> { acs use_ref: fn(value: &'a T) }";
let (graph, app) = graph_with_app(path, source);
let extension_access = &app.ast.contract_definition_content.contract_accesses[1];
let ContractSource::Declaration(declaration) = &extension_access.source else {
panic!("expected extension declaration")
};
let ContractDeclarationKind::ExtensionOnly(extension) = &declaration.kind else {
panic!("expected extension kind")
};
let lowerer = TypeLowerer::new(&graph, &app, path)
.with_generic_parameters(extension_access.generic_declaration_list.as_ref())
.unwrap();
let target = lowerer.lower(&extension.target).unwrap();
let SemanticType::Named(target) = target else {
panic!("extension target must be named")
};
assert!(matches!(
target.generic_arguments.as_slice(),
[SemanticGenericArgument::Type(SemanticType::Parameter(
SemanticGenericParameter {
kind: SemanticGenericParameterKind::Type,
..
}
))]
));
let definition = declaration.definition.as_ref().unwrap();
let function = function_contract(&definition.content.contract_accesses[0].source).unwrap();
let signature = lowerer.lower_function(function).unwrap();
let SemanticType::Reference {
lifetime: Some(SemanticLifetime::Parameter(lifetime)),
target,
..
} = &signature.arguments[0].type_
else {
panic!("argument must use generic lifetime")
};
assert_eq!(lifetime.name, "a");
assert!(
matches!(target.as_ref(), SemanticType::Parameter(parameter) if parameter.name == "T")
);
}
#[test]
fn lowers_an_associated_type_projection_from_a_generic_parameter() {
let path = "app://associated.lt";
let source = "pub acs ZeroablePrimitive: trait { acs NonZeroInner: type }
pub acs Wrapper<T: ZeroablePrimitive>: struct {
pub fld value: T.NonZeroInner
}";
let (graph, app) = graph_with_app(path, source);
let declaration = &app.ast.contract_definition_content.contract_accesses[1];
let ContractSource::Declaration(contract) = &declaration.source else {
panic!("structure declaration expected")
};
let field = &contract
.definition
.as_ref()
.expect("structure body")
.content
.field_declarations[0];
let lowerer = TypeLowerer::new(&graph, &app, path)
.with_generic_parameters(declaration.generic_declaration_list.as_ref())
.unwrap();
assert!(matches!(
lowerer.lower(&field.value_type).unwrap(),
SemanticType::Associated { owner, name }
if name == "NonZeroInner"
&& matches!(
*owner,
SemanticType::Parameter(ref parameter)
if parameter.name == "T"
&& parameter.constraints == ["ZeroablePrimitive"]
)
));
}
#[test]
fn normalizes_an_associated_type_through_a_visible_extension() {
let mut graph = ModuleGraph::default();
let insert = |graph: &mut ModuleGraph, path: &str, text: &str| {
let parsed = parse_file(SourceFile { path, text }).unwrap();
graph
.insert(path, DeclarationIndex::collect(&parsed).unwrap())
.unwrap();
};
insert(
&mut graph,
"lib://types.lt",
"pub acs ZeroablePrimitive: trait { acs NonZeroInner: type }
pub acs U32: struct
pub acs NonZeroU32: struct",
);
insert(
&mut graph,
"lib://extension.lt",
"acs types: \"lib://types.lt\"
pub acs ext: extension for types.U32 {
impl types.ZeroablePrimitive {
acs NonZeroInner: type = types.NonZeroU32
}
}",
);
insert(
&mut graph,
"app://main.lt",
"acs types: \"lib://types.lt\"
acs extensions: \"lib://extension.lt\"
acs u32_ext: extensions.ext",
);
let parameter = SemanticGenericParameter {
id: GenericParameterId(0),
name: "T".into(),
kind: SemanticGenericParameterKind::Type,
constraints: vec!["types.ZeroablePrimitive".into()],
};
let projection = SemanticType::Associated {
owner: Box::new(SemanticType::Parameter(parameter)),
name: "NonZeroInner".into(),
};
let concrete = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "lib://types.lt".into(),
local: "U32".into(),
},
generic_arguments: Vec::new(),
});
let normalized = normalize_type(
&projection,
&BTreeMap::from([(GenericParameterId(0), concrete)]),
&graph,
"app://main.lt",
)
.unwrap();
assert!(matches!(
normalized,
SemanticType::Named(SemanticNamedType { path, generic_arguments })
if path.module == "lib://types.lt"
&& path.local == "NonZeroU32"
&& generic_arguments.is_empty()
));
}
#[test]
fn expands_generic_and_concrete_type_aliases() {
let path = "app://aliases.lt";
let source = "pub acs Type: struct pub acs Option<T>: struct acs Optional<T>: Option<T> acs OptionType: Option<Type> acs generic_use: extension for Optional<Type> acs concrete_use: extension for OptionType";
let (graph, app) = graph_with_app(path, source);
let lowerer = TypeLowerer::new(&graph, &app, path);
let lower_target = |index: usize| {
let ContractSource::Declaration(declaration) =
&app.ast.contract_definition_content.contract_accesses[index].source
else {
panic!("expected extension declaration")
};
let ContractDeclarationKind::ExtensionOnly(extension) = &declaration.kind else {
panic!("expected extension")
};
lowerer.lower(&extension.target).unwrap()
};
let generic = lower_target(4);
let concrete = lower_target(5);
assert_eq!(generic, concrete);
let SemanticType::Named(option) = generic else {
panic!("aliases must expand to Option")
};
assert_eq!(option.path.local, "Option");
assert!(matches!(
option.generic_arguments.as_slice(),
[SemanticGenericArgument::Type(SemanticType::Named(type_))]
if type_.path.local == "Type"
));
}
#[test]
fn validates_generic_alias_arity() {
let path = "app://arity.lt";
let source = "pub acs Option<T>: struct acs Optional<T>: Option<T> acs invalid: extension for Optional";
let (graph, app) = graph_with_app(path, source);
let ContractSource::Declaration(declaration) =
&app.ast.contract_definition_content.contract_accesses[2].source
else {
panic!("expected extension")
};
let ContractDeclarationKind::ExtensionOnly(extension) = &declaration.kind else {
panic!("expected extension")
};
let error = TypeLowerer::new(&graph, &app, path)
.lower(&extension.target)
.unwrap_err();
assert!(matches!(
error,
TypeLoweringError::GenericArityMismatch {
expected: 1,
actual: 0,
..
}
));
}
#[test]
fn builds_nested_runtime_type_descriptors_without_manual_semantic_fields() {
let u32_type = SemanticType::named_from_parts("core://primitive.lt", "u32");
let boxed = SemanticNamedType::from_parts("core://box.lt", "Box")
.with_type_argument(u32_type.clone());
let option = SemanticNamedType::from_parts("core://option.lt", "Option")
.with_type_argument(boxed.clone());
assert_eq!(boxed.path.local, "Box");
assert!(matches!(
option.generic_arguments.as_slice(),
[SemanticGenericArgument::Type(SemanticType::Named(argument))]
if argument == &boxed
));
assert_eq!(
SemanticType::from(boxed),
SemanticType::Named(
SemanticNamedType::from_parts("core://box.lt", "Box").with_type_argument(u32_type)
)
);
}
#[test]
fn rejects_traits_in_type_position() {
let path = "app://invalid-type.lt";
let (graph, app) = graph_with_app(path, "acs invalid: fn(value: Add)");
let error = TypeLowerer::new(&graph, &app, path)
.lower_function(first_function(&app))
.unwrap_err();
assert!(matches!(error, TypeLoweringError::ExpectedType { .. }));
}
}