use std::{
collections::{BTreeMap, BTreeSet},
error::Error,
fmt,
};
use crate::{
parsing::{
ParsedFile, Span,
ast::{
AccessExpression, AccessExpressionAccessor, AccessExpressionEntry,
AccessExpressionSubAccessor, AssignmentOperatorKind, DeclarationStatementItem,
Expression, ExpressionKind, ExpressionSource, Statement, ValueExpression,
},
},
runtime::{TypeMetadataKind, TypeMetadataRegistry, TypeOrigin},
semantic::{
BasicBlockId, CanonicalSymbolPath, ExtensionActivationError, ExtensionEnvironment,
FunctionRegistry, GlobalFunction, IrValueId, LocalId, MethodLookupError, MethodSource,
MethodTable, ModuleGraph, ModuleGraphError, PlaceBase, PlaceId, PlaceProjection,
SemanticFunctionType, SemanticNamedType, SemanticType, TypeLowerer, TypeLoweringError,
TypedBasicBlock, TypedBody, TypedConstant, TypedInstruction, TypedInstructionKind,
TypedLocal, TypedPlace, TypedTerminator, TypedValue, normalize_type,
},
};
#[derive(Debug, Clone)]
pub enum FunctionBody {
Scope(Box<crate::semantic::Scope>),
Typed(Box<TypedBody>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BodyAnalysisError {
InvalidStringId {
id: u32,
span: Span,
},
DuplicateLocal {
name: String,
span: Span,
},
UnknownValue {
name: String,
span: Span,
},
UnknownFunction {
path: String,
span: Span,
},
Resolution {
span: Span,
error: ModuleGraphError,
},
TypeLowering {
span: Span,
error: TypeLoweringError,
},
ExtensionActivation {
span: Span,
errors: Vec<ExtensionActivationError>,
},
MethodLookup {
span: Span,
error: MethodLookupError,
},
TypeMismatch {
expected: SemanticType,
actual: SemanticType,
span: Span,
},
ArgumentCount {
function: CanonicalSymbolPath,
expected: usize,
actual: usize,
span: Span,
},
ImmutableAssignment {
name: String,
span: Span,
},
UninitializedLocal {
name: String,
span: Span,
},
UseAfterMove {
name: String,
span: Span,
},
SuspendedReferenceUse {
name: String,
span: Span,
},
PartiallyMovedValue {
name: String,
span: Span,
},
PartialMoveOfDropType {
type_: SemanticType,
span: Span,
},
CopyTypeHasDrop {
type_: SemanticType,
span: Span,
},
RepeatedArrayElementNotCopy {
type_: SemanticType,
span: Span,
},
InconsistentPlaceStateAcrossBranches {
name: String,
span: Span,
},
CannotBorrowTemporary {
span: Span,
},
MutableBorrowOfImmutablePlace {
span: Span,
},
ConflictingBorrows {
first: PlaceId,
second: PlaceId,
span: Span,
},
BorrowedPlaceMutation {
place: PlaceId,
borrowed: PlaceId,
span: Span,
},
EscapingLocalBorrow {
place: PlaceId,
span: Span,
},
ReturnLifetimeMismatch {
expected: Option<crate::semantic::SemanticLifetime>,
actual: Option<crate::semantic::SemanticLifetime>,
span: Span,
},
MissingInitializer {
name: String,
span: Span,
},
MissingReturn {
expected: SemanticType,
},
MissingElseForValueIf {
span: Span,
},
MissingBlockValue {
expected: SemanticType,
span: Span,
},
UnreachableStatement {
span: Span,
},
MissingTypeMetadata {
type_: SemanticType,
span: Span,
},
UnknownField {
type_: SemanticType,
field: String,
span: Span,
},
DuplicateStructureField {
type_: SemanticType,
field: String,
span: Span,
},
MissingStructureField {
type_: SemanticType,
field: String,
span: Span,
},
StructureLiteralForNonStructure {
type_: SemanticType,
span: Span,
},
PrivateField {
type_: SemanticType,
field: String,
span: Span,
},
Unsupported {
feature: &'static str,
span: Span,
},
}
impl BodyAnalysisError {
pub fn span(&self) -> Option<Span> {
match self {
Self::InvalidStringId { span, .. }
| Self::DuplicateLocal { span, .. }
| Self::UnknownValue { span, .. }
| Self::UnknownFunction { span, .. }
| Self::Resolution { span, .. }
| Self::TypeLowering { span, .. }
| Self::ExtensionActivation { span, .. }
| Self::MethodLookup { span, .. }
| Self::TypeMismatch { span, .. }
| Self::ArgumentCount { span, .. }
| Self::ImmutableAssignment { span, .. }
| Self::UninitializedLocal { span, .. }
| Self::UseAfterMove { span, .. }
| Self::SuspendedReferenceUse { span, .. }
| Self::PartiallyMovedValue { span, .. }
| Self::PartialMoveOfDropType { span, .. }
| Self::CopyTypeHasDrop { span, .. }
| Self::RepeatedArrayElementNotCopy { span, .. }
| Self::InconsistentPlaceStateAcrossBranches { span, .. }
| Self::CannotBorrowTemporary { span }
| Self::MutableBorrowOfImmutablePlace { span }
| Self::ConflictingBorrows { span, .. }
| Self::BorrowedPlaceMutation { span, .. }
| Self::EscapingLocalBorrow { span, .. }
| Self::ReturnLifetimeMismatch { span, .. }
| Self::MissingInitializer { span, .. }
| Self::MissingElseForValueIf { span }
| Self::MissingBlockValue { span, .. }
| Self::UnreachableStatement { span }
| Self::MissingTypeMetadata { span, .. }
| Self::UnknownField { span, .. }
| Self::DuplicateStructureField { span, .. }
| Self::MissingStructureField { span, .. }
| Self::StructureLiteralForNonStructure { span, .. }
| Self::PrivateField { span, .. }
| Self::Unsupported { span, .. } => Some(*span),
Self::MissingReturn { .. } => None,
}
}
}
impl fmt::Display for BodyAnalysisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidStringId { id, .. } => write!(f, "invalid StringId({id}) in AST"),
Self::DuplicateLocal { name, .. } => write!(f, "local `{name}` is already declared"),
Self::UnknownValue { name, .. } => write!(f, "unknown value `{name}`"),
Self::UnknownFunction { path, .. } => write!(f, "`{path}` does not name a function"),
Self::Resolution { error, .. } => error.fmt(f),
Self::TypeLowering { error, .. } => error.fmt(f),
Self::ExtensionActivation { errors, .. } => {
write!(f, "cannot activate extension environment: {:?}", errors)
}
Self::MethodLookup { error, .. } => error.fmt(f),
Self::TypeMismatch {
expected, actual, ..
} => {
write!(f, "type mismatch: expected {expected:?}, got {actual:?}")
}
Self::ArgumentCount {
function,
expected,
actual,
..
} => write!(
f,
"function `{}::{}` expects {expected} arguments, got {actual}",
function.module, function.local
),
Self::ImmutableAssignment { name, .. } => {
write!(f, "cannot assign to immutable local `{name}`")
}
Self::UninitializedLocal { name, .. } => {
write!(f, "local `{name}` may be uninitialized")
}
Self::UseAfterMove { name, .. } => {
write!(f, "local `{name}` was moved")
}
Self::SuspendedReferenceUse { name, .. } => {
write!(
f,
"reference `{name}` is suspended by an active mutable reborrow"
)
}
Self::PartiallyMovedValue { name, .. } => {
write!(
f,
"local `{name}` is only partially initialized after a move"
)
}
Self::PartialMoveOfDropType { type_, .. } => {
write!(f, "cannot partially move value of Drop type `{type_:?}`")
}
Self::CopyTypeHasDrop { type_, .. } => {
write!(f, "Copy type `{type_:?}` cannot also implement Drop")
}
Self::RepeatedArrayElementNotCopy { type_, .. } => {
write!(
f,
"array repetition requires Copy element type, got `{type_:?}`"
)
}
Self::InconsistentPlaceStateAcrossBranches { name, .. } => write!(
f,
"place `{name}` has different initialization or move state across branches"
),
Self::CannotBorrowTemporary { .. } => {
f.write_str("cannot implicitly borrow a non-addressable temporary")
}
Self::MutableBorrowOfImmutablePlace { .. } => {
f.write_str("cannot mutably borrow an immutable place")
}
Self::ConflictingBorrows { first, second, .. } => write!(
f,
"conflicting borrows of overlapping places {first:?} and {second:?}"
),
Self::BorrowedPlaceMutation {
place, borrowed, ..
} => write!(
f,
"cannot move, overwrite, or drop place {place:?} while {borrowed:?} is borrowed"
),
Self::EscapingLocalBorrow { place, .. } => {
write!(f, "cannot return a reference to local place {place:?}")
}
Self::ReturnLifetimeMismatch {
expected, actual, ..
} => write!(
f,
"returned reference lifetime {actual:?} does not satisfy return lifetime {expected:?}"
),
Self::MissingInitializer { name, .. } => {
write!(f, "local `{name}` requires a type or initializer")
}
Self::MissingReturn { expected } => {
write!(
f,
"function can reach its end without returning `{expected:?}`"
)
}
Self::MissingElseForValueIf { .. } => {
f.write_str("a value-producing `if` requires an `else` branch")
}
Self::MissingBlockValue { expected, .. } => {
write!(
f,
"block does not produce the expected `{expected:?}` value"
)
}
Self::UnreachableStatement { .. } => f.write_str("unreachable statement"),
Self::MissingTypeMetadata { type_, .. } => {
write!(f, "type `{type_:?}` has no field metadata")
}
Self::UnknownField { type_, field, .. } => {
write!(f, "type `{type_:?}` has no field `{field}`")
}
Self::DuplicateStructureField { type_, field, .. } => {
write!(
f,
"field `{field}` is specified more than once for `{type_:?}`"
)
}
Self::MissingStructureField { type_, field, .. } => {
write!(f, "missing field `{field}` when constructing `{type_:?}`")
}
Self::StructureLiteralForNonStructure { type_, .. } => {
write!(f, "type `{type_:?}` is not a structure")
}
Self::PrivateField { type_, field, .. } => {
write!(f, "field `{field}` of type `{type_:?}` is private")
}
Self::Unsupported { feature, .. } => write!(f, "{feature} is not supported yet"),
}
}
}
impl Error for BodyAnalysisError {}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ActiveLoan {
holder: LocalId,
place: PlaceId,
mutable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SuspendedLoanSet {
holder: LocalId,
suspended_by: LocalId,
loans: Vec<ActiveLoan>,
}
#[derive(Debug, Default)]
struct BasicBlockDraft {
parameters: Vec<TypedValue>,
instructions: Vec<TypedInstruction>,
terminator: Option<TypedTerminator>,
}
pub struct BodyAnalyzer<'a> {
graph: &'a ModuleGraph,
functions: &'a FunctionRegistry,
file: &'a ParsedFile,
module: &'a str,
signature: &'a SemanticFunctionType,
type_metadata: Option<&'a TypeMetadataRegistry>,
locals: Vec<TypedLocal>,
local_places: Vec<PlaceId>,
initialized: Vec<bool>,
initialized_places: Vec<PlaceId>,
moved: Vec<bool>,
moved_places: Vec<PlaceId>,
active_loans: Vec<ActiveLoan>,
suspended_loans: Vec<SuspendedLoanSet>,
places: Vec<TypedPlace>,
local_scopes: Vec<BTreeMap<String, LocalId>>,
blocks: Vec<BasicBlockDraft>,
current_block: BasicBlockId,
next_value: u32,
}
impl<'a> BodyAnalyzer<'a> {
pub fn new(
graph: &'a ModuleGraph,
functions: &'a FunctionRegistry,
file: &'a ParsedFile,
module: &'a str,
signature: &'a SemanticFunctionType,
) -> Result<Self, BodyAnalysisError> {
let mut analyzer = Self {
graph,
functions,
file,
module,
signature,
type_metadata: None,
locals: Vec::new(),
local_places: Vec::new(),
initialized: Vec::new(),
initialized_places: Vec::new(),
moved: Vec::new(),
moved_places: Vec::new(),
active_loans: Vec::new(),
suspended_loans: Vec::new(),
places: Vec::new(),
local_scopes: vec![BTreeMap::new()],
blocks: vec![BasicBlockDraft::default()],
current_block: BasicBlockId(0),
next_value: 0,
};
for argument in &signature.arguments {
analyzer.add_local(
argument.name.clone(),
argument.type_.clone(),
argument.mutable,
true,
true,
Span::new(0, 0),
)?;
}
Ok(analyzer)
}
pub fn new_with_metadata(
graph: &'a ModuleGraph,
functions: &'a FunctionRegistry,
type_metadata: &'a TypeMetadataRegistry,
file: &'a ParsedFile,
module: &'a str,
signature: &'a SemanticFunctionType,
) -> Result<Self, BodyAnalysisError> {
let mut analyzer = Self::new(graph, functions, file, module, signature)?;
analyzer.type_metadata = Some(type_metadata);
Ok(analyzer)
}
pub fn analyze(
mut self,
statements: &[Statement],
) -> Result<TypedBody, Vec<BodyAnalysisError>> {
let mut errors = Vec::new();
for statement in statements {
if self.current_terminated() {
errors.push(BodyAnalysisError::UnreachableStatement {
span: statement_span(statement),
});
continue;
}
if let Err(error) = self.analyze_statement(statement) {
errors.push(error);
}
}
if !self.current_terminated() {
if matches!(self.signature.return_type.as_ref(), SemanticType::Void) {
self.emit_live_drops(Span::new(0, 0));
self.terminate(TypedTerminator::Return(None));
} else {
errors.push(BodyAnalysisError::MissingReturn {
expected: self.signature.return_type.as_ref().clone(),
});
}
}
for block in &self.blocks {
if block.terminator.is_none() {
errors.push(BodyAnalysisError::Unsupported {
feature: "unterminated basic block",
span: Span::new(0, 0),
});
}
}
if !errors.is_empty() {
return Err(errors);
}
let entry = BasicBlockId(0);
let mut return_drops = Vec::new();
self.collect_return_drop_actions(
self.signature.return_type.as_ref(),
&mut Vec::new(),
&mut Vec::new(),
&mut return_drops,
);
let return_cleanup = crate::semantic::ReturnCleanupPlan {
drops: return_drops,
};
let blocks = self
.blocks
.into_iter()
.enumerate()
.map(|(index, block)| TypedBasicBlock {
id: BasicBlockId(index as u32),
parameters: block.parameters,
instructions: block.instructions,
terminator: block.terminator.expect("terminators were checked above"),
})
.collect();
Ok(TypedBody {
locals: self.locals,
places: self.places,
entry,
blocks,
return_type: self.signature.return_type.as_ref().clone(),
return_cleanup,
})
}
fn analyze_statement(&mut self, statement: &Statement) -> Result<(), BodyAnalysisError> {
match statement {
Statement::Expression(expression) => {
let value = self.expression(expression, None)?;
self.consume_value(&value, expression.span)?;
Ok(())
}
Statement::Return(return_) => {
let expected = self.signature.return_type.as_ref().clone();
let value = return_
.expression
.as_ref()
.map(|expression| self.coerce_expression(expression, &expected))
.transpose()?;
if self.current_terminated() {
return Ok(());
}
let actual = value
.as_ref()
.map_or(SemanticType::Void, |value| value.type_.clone());
self.require_type(&expected, &actual, return_.span)?;
if let Some(value) = &value {
self.ensure_reference_does_not_escape(value, return_.span)?;
self.consume_value(value, return_.span)?;
}
self.emit_live_drops(return_.span);
self.terminate(TypedTerminator::Return(value.map(|value| value.id)));
Ok(())
}
Statement::Declaration(declaration) => {
let DeclarationStatementItem::Ident(item) = &declaration.item else {
return Err(BodyAnalysisError::Unsupported {
feature: "destructuring declarations",
span: declaration.span,
});
};
let name = self
.string(item.ident.string.0, item.ident.span)?
.to_owned();
let annotated = item
.value_type
.as_ref()
.map(|type_| {
TypeLowerer::new(self.graph, self.file, self.module)
.lower(type_)
.map_err(|error| BodyAnalysisError::TypeLowering {
span: item.span,
error,
})
})
.transpose()?;
let value = declaration
.expression
.as_ref()
.map(|expression| match &annotated {
Some(expected) => self.coerce_expression(expression, expected),
None => self.expression(expression, None),
})
.transpose()?;
let type_ = annotated
.or_else(|| value.as_ref().map(|value| value.type_.clone()))
.ok_or_else(|| BodyAnalysisError::MissingInitializer {
name: name.clone(),
span: item.span,
})?;
let initialized = value.is_some();
let local = self.add_local(
name,
type_,
item.mutable.is_some(),
false,
initialized,
item.span,
)?;
if let Some(value) = value {
let transferred_loans = self.reference_loan_targets(&value);
let holder = place_local_id(&self.places[local.0 as usize]);
let reborrowed_holder = match (&value.type_, value.storage_place) {
(SemanticType::Reference { mutable: true, .. }, Some(place)) => {
Some(place_local_id(&self.places[place.0 as usize]))
}
_ => None,
};
if let Some(parent) = reborrowed_holder {
self.suspend_holder_loans(parent, holder);
} else {
self.consume_value(&value, declaration.span)?;
}
for (borrowed, mutable) in transferred_loans {
self.ensure_loan_compatible(borrowed, mutable, declaration.span)?;
self.active_loans.push(ActiveLoan {
holder,
place: borrowed,
mutable,
});
}
self.emit_instruction(TypedInstruction {
span: declaration.span,
result: None,
kind: TypedInstructionKind::Store {
place: local,
value: value.id,
},
});
}
Ok(())
}
Statement::Assignment(assignment) => {
let (place, name) = if assignment.dereference_count > 0 {
let operand = Expression {
span: assignment.access.span,
kind: ExpressionKind::Source(ExpressionSource::Access(Box::new(
assignment.access.clone(),
))),
};
let mut value = self.expression(&operand, None)?;
for _ in 0..assignment.dereference_count {
value =
self.dereference_value(value, assignment.access.span, None, true)?;
}
let place = value.storage_place.ok_or(BodyAnalysisError::Unsupported {
feature: "dereference assignment without addressable storage",
span: assignment.span,
})?;
(place, "*".repeat(assignment.dereference_count))
} else {
self.place_access(&assignment.access, true)?
};
let type_ = self.places[place.0 as usize].type_.clone();
if !self.places[place.0 as usize].mutable {
return Err(BodyAnalysisError::ImmutableAssignment {
name,
span: assignment.span,
});
}
let projected = !self.places[place.0 as usize].projections.is_empty();
let replacing_initialized = self.place_has_live_contents(place);
let value = match assignment.operator.kind {
AssignmentOperatorKind::Set => {
if projected {
self.require_projection_storage(place, assignment.span)?;
}
self.coerce_expression(&assignment.expression, &type_)?
}
mode => {
self.require_initialized(place, assignment.span)?;
let method = match mode {
AssignmentOperatorKind::Add => "add",
AssignmentOperatorKind::Sub => "sub",
AssignmentOperatorKind::Multiply => "mul",
AssignmentOperatorKind::Divide => "div",
AssignmentOperatorKind::ShiftLeft => "shl",
AssignmentOperatorKind::ShiftRight => "shr",
AssignmentOperatorKind::Set => unreachable!(),
};
let receiver = self.emit_value(
assignment.access.span,
type_.clone(),
TypedInstructionKind::Load(place),
);
self.method_call(
assignment.span,
receiver,
method,
std::slice::from_ref(&assignment.expression),
Some(&type_),
)?
}
};
let transferred_loans = self.reference_loan_targets(&value);
self.consume_value(&value, assignment.span)?;
self.ensure_not_borrowed(place, assignment.span)?;
if replacing_initialized {
if !projected {
let holder = place_local_id(&self.places[place.0 as usize]);
self.release_holder_loans(holder);
}
self.emit_drop(place, assignment.span);
}
self.emit_instruction(TypedInstruction {
span: assignment.span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: value.id,
},
});
if projected {
self.mark_place_initialized(place);
self.moved_places = self
.moved_places
.iter()
.copied()
.filter(|moved| !self.place_contains(place, *moved))
.collect();
} else {
let local = place_local_id(&self.places[place.0 as usize]);
for (borrowed, mutable) in transferred_loans {
self.ensure_loan_compatible(borrowed, mutable, assignment.span)?;
self.active_loans.push(ActiveLoan {
holder: local,
place: borrowed,
mutable,
});
}
self.initialized[local.0 as usize] = true;
self.initialized_places.retain(|initialized| {
place_local_id(&self.places[initialized.0 as usize]) != local
});
self.moved[local.0 as usize] = false;
self.moved_places
.retain(|moved| place_local_id(&self.places[moved.0 as usize]) != local);
}
Ok(())
}
}
}
fn expression(
&mut self,
expression: &Expression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
match &expression.kind {
ExpressionKind::Source(ExpressionSource::Value(value)) => self.value(value, expected),
ExpressionKind::Source(ExpressionSource::Access(access)) => {
self.access(access, expected)
}
ExpressionKind::Source(ExpressionSource::Structure(structure)) => {
self.structure_expression(structure, expected)
}
ExpressionKind::Source(ExpressionSource::Match(match_expression)) => {
self.match_expression(match_expression, expected)
}
ExpressionKind::Unary {
operator,
expression: operand,
} => match operator.kind {
crate::parsing::ast::UnaryExpressionOperatorKind::Borrow
| crate::parsing::ast::UnaryExpressionOperatorKind::BorrowMut => {
let mutable = matches!(
operator.kind,
crate::parsing::ast::UnaryExpressionOperatorKind::BorrowMut
);
let value = if mutable
&& let ExpressionKind::Unary {
operator,
expression: dereferenced,
} = &operand.kind
&& operator.kind
== crate::parsing::ast::UnaryExpressionOperatorKind::Dereference
{
self.dereference_expression(dereferenced, operand.span, None, true)?
} else {
self.expression(operand, None)?
};
if mutable
&& matches!(value.type_, SemanticType::Reference { mutable: true, .. })
{
let mut reborrow = value.clone();
if let Some(expected) = expected {
self.require_type(expected, &reborrow.type_, expression.span)?;
reborrow.type_ = expected.clone();
}
return Ok(reborrow);
}
let inferred = SemanticType::Reference {
lifetime: None,
mutable,
target: Box::new(value.type_.clone()),
};
let reference_type = if let Some(expected) = expected {
let compatible = match (expected, &inferred) {
(
SemanticType::Reference {
mutable: expected_mutable,
target: expected_target,
..
},
SemanticType::Reference {
mutable: actual_mutable,
target: actual_target,
..
},
) => {
expected_mutable == actual_mutable
&& expected_target == actual_target
}
_ => expected == &inferred,
};
if !compatible {
self.require_type(expected, &inferred, expression.span)?;
}
expected.clone()
} else {
inferred
};
self.borrow_value(expression.span, value, reference_type, mutable)
}
crate::parsing::ast::UnaryExpressionOperatorKind::Dereference => {
self.dereference_expression(operand, expression.span, expected, false)
}
crate::parsing::ast::UnaryExpressionOperatorKind::Negate
| crate::parsing::ast::UnaryExpressionOperatorKind::Not => {
Err(BodyAnalysisError::Unsupported {
feature: "arithmetic/logical unary operator lowering",
span: expression.span,
})
}
},
ExpressionKind::Binary {
left,
operator,
right,
} => {
let method = match operator.kind {
crate::parsing::ast::BinaryExpressionOperatorKind::Multiply => "mul",
crate::parsing::ast::BinaryExpressionOperatorKind::Divide => "div",
crate::parsing::ast::BinaryExpressionOperatorKind::Add => "add",
crate::parsing::ast::BinaryExpressionOperatorKind::Subtract => "sub",
crate::parsing::ast::BinaryExpressionOperatorKind::ShiftLeft => "shl",
crate::parsing::ast::BinaryExpressionOperatorKind::ShiftRight => "shr",
crate::parsing::ast::BinaryExpressionOperatorKind::Equal => "eq",
crate::parsing::ast::BinaryExpressionOperatorKind::NotEqual => "ne",
crate::parsing::ast::BinaryExpressionOperatorKind::Less
| crate::parsing::ast::BinaryExpressionOperatorKind::LessOrEqual
| crate::parsing::ast::BinaryExpressionOperatorKind::Greater
| crate::parsing::ast::BinaryExpressionOperatorKind::GreaterOrEqual => {
return Err(BodyAnalysisError::Unsupported {
feature: "ordering operator traits",
span: operator.span,
});
}
};
let receiver = self.expression(left, None)?;
self.method_call(
expression.span,
receiver,
method,
std::slice::from_ref(right),
expected,
)
}
}
}
fn value(
&mut self,
value: &ValueExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
if let ValueExpression::Array(array) = value {
return self.array_expression(array, expected);
}
if let ValueExpression::Tuple(tuple) = value {
return self.tuple_expression(tuple, expected);
}
if let ValueExpression::If(if_) = value {
return self.if_expression(if_, expected);
}
if let ValueExpression::While(while_) = value {
return self.while_expression(while_, expected);
}
if let ValueExpression::Loop(loop_) = value {
return self.loop_expression(loop_, expected);
}
if let ValueExpression::Contract(block) = value {
return self.block_expression(block, expected);
}
let (constant, inferred, span) = match value {
ValueExpression::Void(value) => (TypedConstant::Void, SemanticType::Void, value.span),
ValueExpression::Bool(value) => (
TypedConstant::Bool(value.value),
self.primitive("bool", value.span)?,
value.span,
),
ValueExpression::Char(value) => (
TypedConstant::Char(value.value),
self.primitive("char", value.span)?,
value.span,
),
ValueExpression::IntAny(value) => (
TypedConstant::Signed(value.value),
expected
.cloned()
.unwrap_or(self.primitive("i32", value.span)?),
value.span,
),
ValueExpression::Int8(value) => (
TypedConstant::Signed(value.value.into()),
self.primitive("i8", value.span)?,
value.span,
),
ValueExpression::Int16(value) => (
TypedConstant::Signed(value.value.into()),
self.primitive("i16", value.span)?,
value.span,
),
ValueExpression::Int32(value) => (
TypedConstant::Signed(value.value.into()),
self.primitive("i32", value.span)?,
value.span,
),
ValueExpression::Int64(value) => (
TypedConstant::Signed(value.value.into()),
self.primitive("i64", value.span)?,
value.span,
),
ValueExpression::Uint8(value) => (
TypedConstant::Unsigned(value.value.into()),
self.primitive("u8", value.span)?,
value.span,
),
ValueExpression::Uint16(value) => (
TypedConstant::Unsigned(value.value.into()),
self.primitive("u16", value.span)?,
value.span,
),
ValueExpression::Uint32(value) => (
TypedConstant::Unsigned(value.value.into()),
self.primitive("u32", value.span)?,
value.span,
),
ValueExpression::Uint64(value) => (
TypedConstant::Unsigned(value.value.into()),
self.primitive("u64", value.span)?,
value.span,
),
ValueExpression::FloatAny(value) => (
TypedConstant::Float(value.value),
expected
.cloned()
.unwrap_or(self.primitive("f64", value.span)?),
value.span,
),
ValueExpression::Float32(value) => (
TypedConstant::Float(value.value.into()),
self.primitive("f32", value.span)?,
value.span,
),
ValueExpression::Float64(value) => (
TypedConstant::Float(value.value),
self.primitive("f64", value.span)?,
value.span,
),
ValueExpression::String(value) => (
TypedConstant::String(self.string(value.string.0, value.span)?.to_owned()),
self.primitive("str", value.span)?,
value.span,
),
ValueExpression::Isize(value) => (
TypedConstant::Signed(value.value as i128),
self.primitive("isize", value.span)?,
value.span,
),
ValueExpression::Usize(value) => (
TypedConstant::Unsigned(value.value as u128),
self.primitive("usize", value.span)?,
value.span,
),
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "composite/control-flow expression lowering",
span: value_span(value),
});
}
};
if let Some(expected) = expected {
self.require_type(expected, &inferred, span)?;
}
Ok(self.emit_value(span, inferred, TypedInstructionKind::Constant(constant)))
}
fn array_expression(
&mut self,
array: &crate::parsing::ast::ArrayValueExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let Some(SemanticType::Array {
item,
size: Some(size),
}) = expected
else {
return Err(BodyAnalysisError::Unsupported {
feature: "array literal type inference",
span: array.span,
});
};
let type_ = expected.expect("matched above").clone();
let initializers = match &array.kind {
crate::parsing::ast::ArrayValueExpressionKind::ExpressionList(list) => {
if *size != list.expressions.len() {
return Err(BodyAnalysisError::TypeMismatch {
expected: type_.clone(),
actual: SemanticType::Array {
item: item.clone(),
size: Some(list.expressions.len()),
},
span: array.span,
});
}
let mut values = Vec::with_capacity(list.expressions.len());
for expression in &list.expressions {
let value = self.coerce_expression(expression, item)?;
if self.current_terminated() {
return Ok(self.detached_value(type_));
}
values.push((value, expression.span));
}
values
}
crate::parsing::ast::ArrayValueExpressionKind::DefaultSized(repeated) => {
let actual_size = constant_usize(&repeated.size_expression).ok_or(
BodyAnalysisError::Unsupported {
feature: "non-constant repeated array size",
span: repeated.size_expression.span,
},
)?;
if actual_size != *size {
return Err(BodyAnalysisError::TypeMismatch {
expected: type_.clone(),
actual: SemanticType::Array {
item: item.clone(),
size: Some(actual_size),
},
span: array.span,
});
}
if actual_size > 1 && !self.is_copy_type(item) {
return Err(BodyAnalysisError::RepeatedArrayElementNotCopy {
type_: item.as_ref().clone(),
span: repeated.default_expression.span,
});
}
if actual_size == 0 {
Vec::new()
} else {
let value = self.coerce_expression(&repeated.default_expression, item)?;
if self.current_terminated() {
return Ok(self.detached_value(type_));
}
std::iter::repeat_n((value, repeated.default_expression.span), actual_size)
.collect()
}
}
};
let temporary = self.add_local(
format!("$array{}", self.locals.len()),
type_.clone(),
true,
false,
false,
array.span,
)?;
for (index, (value, span)) in initializers.into_iter().enumerate() {
self.consume_value(&value, span)?;
let place = self.child_place(
temporary,
PlaceProjection::ConstantIndex(index),
item.as_ref().clone(),
);
self.emit_instruction(TypedInstruction {
span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: value.id,
},
});
}
let temporary_local = place_local_id(&self.places[temporary.0 as usize]);
self.initialized[temporary_local.0 as usize] = true;
Ok(self.emit_value(array.span, type_, TypedInstructionKind::Load(temporary)))
}
fn tuple_expression(
&mut self,
tuple: &crate::parsing::ast::TupleValueExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let expressions = std::iter::once(&tuple.item_expressions.0)
.chain(tuple.item_expressions.1.iter())
.collect::<Vec<_>>();
let expected_items = match expected {
Some(SemanticType::Tuple(items)) if items.len() == expressions.len() => Some(items),
Some(expected) => {
return Err(BodyAnalysisError::TypeMismatch {
expected: expected.clone(),
actual: SemanticType::Tuple(Vec::new()),
span: tuple.span,
});
}
None => None,
};
let mut values = Vec::with_capacity(expressions.len());
for (index, expression) in expressions.iter().enumerate() {
let value = match expected_items {
Some(items) => self.coerce_expression(expression, &items[index])?,
None => self.expression(expression, None)?,
};
if self.current_terminated() {
let type_ = expected.cloned().unwrap_or_else(|| {
SemanticType::Tuple(
values
.iter()
.map(|value: &TypedValue| value.type_.clone())
.collect(),
)
});
return Ok(self.detached_value(type_));
}
values.push(value);
}
let type_ = expected.cloned().unwrap_or_else(|| {
SemanticType::Tuple(values.iter().map(|value| value.type_.clone()).collect())
});
let temporary = self.add_local(
format!("$tuple{}", self.locals.len()),
type_.clone(),
true,
false,
false,
tuple.span,
)?;
for (index, value) in values.iter().enumerate() {
self.consume_value(value, expressions[index].span)?;
let item_type = value.type_.clone();
let place = self.child_place(temporary, PlaceProjection::TupleField(index), item_type);
self.emit_instruction(TypedInstruction {
span: expressions[index].span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: value.id,
},
});
}
let temporary_local = place_local_id(&self.places[temporary.0 as usize]);
self.initialized[temporary_local.0 as usize] = true;
Ok(self.emit_value(tuple.span, type_, TypedInstructionKind::Load(temporary)))
}
fn structure_expression(
&mut self,
structure: &crate::parsing::ast::StructureExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let path = self.named_access_path(&structure.type_path)?;
let resolved = self.graph.resolve(self.module, &path).map_err(|error| {
BodyAnalysisError::Resolution {
span: structure.type_path.span,
error,
}
})?;
let canonical = CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
};
let type_ = match expected {
Some(SemanticType::Named(expected)) if expected.path == canonical => {
SemanticType::Named(expected.clone())
}
_ => SemanticType::Named(SemanticNamedType {
path: canonical,
generic_arguments: Vec::new(),
}),
};
if let Some(expected) = expected {
self.require_type(expected, &type_, structure.span)?;
}
let registry =
self.type_metadata
.ok_or_else(|| BodyAnalysisError::MissingTypeMetadata {
type_: type_.clone(),
span: structure.span,
})?;
let metadata = match &type_ {
SemanticType::Named(named) => registry.get_named(named),
_ => None,
};
let Some(metadata) = metadata else {
return Err(if registry.layout_of(&type_).is_some() {
BodyAnalysisError::StructureLiteralForNonStructure {
type_,
span: structure.span,
}
} else {
BodyAnalysisError::MissingTypeMetadata {
type_,
span: structure.span,
}
});
};
let TypeMetadataKind::Structure { fields } = &metadata.kind else {
return Err(BodyAnalysisError::StructureLiteralForNonStructure {
type_,
span: structure.span,
});
};
let fields = fields.clone();
let mut provided = BTreeMap::new();
for field in &structure.fields {
let name = self.string(field.name.string.0, field.span)?.to_owned();
if provided.insert(name.clone(), field).is_some() {
return Err(BodyAnalysisError::DuplicateStructureField {
type_: type_.clone(),
field: name,
span: field.span,
});
}
}
for field in &fields {
if !provided.contains_key(&field.name) {
return Err(BodyAnalysisError::MissingStructureField {
type_: type_.clone(),
field: field.name.clone(),
span: structure.span,
});
}
}
if let Some((name, field)) = provided.iter().find(|(name, _)| {
!fields
.iter()
.any(|metadata| metadata.name.as_str() == name.as_str())
}) {
return Err(BodyAnalysisError::UnknownField {
type_: type_.clone(),
field: name.clone(),
span: field.span,
});
}
let temporary = self.add_local(
format!("$structure{}", self.locals.len()),
type_.clone(),
true,
false,
false,
structure.span,
)?;
for field in fields {
let initializer = provided[&field.name];
if !field.public
&& matches!(&type_, SemanticType::Named(named) if named.path.module != self.module)
{
return Err(BodyAnalysisError::PrivateField {
type_: type_.clone(),
field: field.name,
span: initializer.span,
});
}
let value = self.coerce_expression(&initializer.expression, &field.type_)?;
if self.current_terminated() {
return Ok(self.detached_value(type_));
}
self.consume_value(&value, initializer.span)?;
let place =
self.child_place(temporary, PlaceProjection::Field(field.name), field.type_);
self.emit_instruction(TypedInstruction {
span: initializer.span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: value.id,
},
});
}
let temporary_local = place_local_id(&self.places[temporary.0 as usize]);
self.initialized[temporary_local.0 as usize] = true;
Ok(self.emit_value(structure.span, type_, TypedInstructionKind::Load(temporary)))
}
fn named_access_path(&self, access: &AccessExpression) -> Result<String, BodyAnalysisError> {
let AccessExpressionEntry::Ident(entry) = &access.entry else {
return Err(BodyAnalysisError::Unsupported {
feature: "structure literal type path",
span: access.span,
});
};
let mut parts = vec![self.string(entry.ident.string.0, entry.span)?.to_owned()];
for accessor in &access.accessors {
let AccessExpressionAccessor::Next(next) = accessor else {
return Err(BodyAnalysisError::Unsupported {
feature: "structure literal type path",
span: access.span,
});
};
let crate::parsing::ast::AccessExpressionNextAccessor::Ident(ident) = next.as_ref()
else {
return Err(BodyAnalysisError::Unsupported {
feature: "structure literal tuple type path",
span: access.span,
});
};
parts.push(self.string(ident.ident.string.0, ident.span)?.to_owned());
}
Ok(parts.join("."))
}
fn access(
&mut self,
access: &AccessExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
if let AccessExpressionEntry::ValueExpression(value) = &access.entry
&& access.accessors.is_empty()
{
return self.value(value, expected);
}
let entry_is_value = match &access.entry {
AccessExpressionEntry::Ident(entry) => {
let name = self.string(entry.ident.string.0, entry.span)?;
self.resolve_local(name).is_some()
}
AccessExpressionEntry::ValueExpression(_)
| AccessExpressionEntry::Parenthesized(_)
| AccessExpressionEntry::Self_(_) => true,
};
if entry_is_value && let Some((method, arguments)) = self.method_access(access)? {
let receiver = self.access_entry_value(access)?;
return self.method_call(access.span, receiver, &method, arguments, expected);
}
if entry_is_value {
let (place, _) = self.place_access(access, false)?;
self.require_initialized(place, access.span)?;
let type_ = self.places[place.0 as usize].type_.clone();
if let Some(expected) = expected {
self.require_type(expected, &type_, access.span)?;
}
return Ok(self.emit_value(access.span, type_, TypedInstructionKind::Load(place)));
}
if let Some(value) = self.enum_constructor(access, expected)? {
return Ok(value);
}
let (path, arguments) = self.function_call(access)?;
let resolved = self.graph.resolve(self.module, &path).map_err(|error| {
BodyAnalysisError::Resolution {
span: access.span,
error,
}
})?;
let canonical = CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
};
let function = self
.functions
.function_by_path(&canonical)
.ok_or_else(|| BodyAnalysisError::UnknownFunction {
path: path.clone(),
span: access.span,
})?
.clone();
self.call(access.span, &function, arguments, expected)
}
fn block_expression(
&mut self,
block: &crate::parsing::ast::ContractDefinition,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let first_scope_local = self.locals.len();
self.local_scopes.push(BTreeMap::new());
let result = (|| {
let expects_value = expected.is_some_and(|type_| !matches!(type_, SemanticType::Void));
let (value_statement, preceding) = if expects_value {
let Some((last, preceding)) = block.content.statements.split_last() else {
return Err(BodyAnalysisError::MissingBlockValue {
expected: expected.expect("checked above").clone(),
span: block.span,
});
};
(Some(last), preceding)
} else {
(None, block.content.statements.as_slice())
};
for statement in preceding {
if self.current_terminated() {
return Err(BodyAnalysisError::UnreachableStatement {
span: statement_span(statement),
});
}
self.analyze_statement(statement)?;
}
if let Some(statement) = value_statement {
let Statement::Expression(expression) = statement else {
return Err(BodyAnalysisError::MissingBlockValue {
expected: expected.expect("checked above").clone(),
span: statement_span(statement),
});
};
if let Some(expected) = expected {
self.coerce_expression(expression, expected)
} else {
self.expression(expression, None)
}
} else if self.current_terminated() {
Ok(self.detached_value(SemanticType::Void))
} else {
Ok(self.emit_value(
block.span,
SemanticType::Void,
TypedInstructionKind::Constant(TypedConstant::Void),
))
}
})();
if !self.current_terminated()
&& let Ok(value) = &result
{
if value.borrow_origins.iter().any(|place| {
place_local_id(&self.places[place.0 as usize]).0 as usize >= first_scope_local
}) {
self.consume_value(value, block.span)?;
}
self.emit_scope_drops(first_scope_local, block.span);
}
for index in (first_scope_local..self.locals.len()).rev() {
self.release_holder_loans(LocalId(index as u32));
}
self.suspended_loans
.retain(|suspended| (suspended.holder.0 as usize) < first_scope_local);
self.local_scopes.pop();
result
}
fn match_expression(
&mut self,
match_: &crate::parsing::ast::MatchExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let value = self.expression(&match_.value, None)?;
let SemanticType::Named(named) = &value.type_ else {
return Err(BodyAnalysisError::Unsupported {
feature: "match value must be an enum",
span: match_.value.span,
});
};
let registry =
self.type_metadata
.ok_or_else(|| BodyAnalysisError::MissingTypeMetadata {
type_: value.type_.clone(),
span: match_.span,
})?;
let metadata =
registry
.get_named(named)
.ok_or_else(|| BodyAnalysisError::MissingTypeMetadata {
type_: value.type_.clone(),
span: match_.span,
})?;
let TypeMetadataKind::Enum {
tag_bits, variants, ..
} = &metadata.kind
else {
return Err(BodyAnalysisError::Unsupported {
feature: "match value must be an enum",
span: match_.value.span,
});
};
let tag_bits = *tag_bits;
let variants = variants.clone();
let enum_path = named.path.clone();
let Some(value_place) = value.storage_place else {
return Err(BodyAnalysisError::Unsupported {
feature: "match value without addressable enum storage",
span: match_.value.span,
});
};
self.consume_value(&value, match_.value.span)?;
let mut selected = Vec::with_capacity(match_.arms.len());
let mut covered = BTreeSet::new();
for arm in &match_.arms {
let names = arm
.pattern
.path
.iter()
.map(|ident| {
self.string(ident.string.0, arm.pattern.span)
.map(str::to_owned)
})
.collect::<Result<Vec<_>, _>>()?;
let Some((variant_name, type_parts)) = names.split_last() else {
unreachable!("parser requires enum variant paths")
};
let resolved = self
.graph
.resolve(self.module, &type_parts.join("."))
.map_err(|error| BodyAnalysisError::Resolution {
span: arm.pattern.span,
error,
})?;
if resolved.module_path != enum_path.module || resolved.local_path != enum_path.local {
return Err(BodyAnalysisError::Unsupported {
feature: "match arm belongs to another enum",
span: arm.pattern.span,
});
}
let variant = variants
.iter()
.find(|variant| variant.name == *variant_name)
.cloned()
.ok_or(BodyAnalysisError::Unsupported {
feature: "unknown enum variant in match",
span: arm.pattern.span,
})?;
if variant.payload_type.is_some() != arm.pattern.binding.is_some() {
return Err(BodyAnalysisError::Unsupported {
feature: "enum match payload binding does not match variant payload",
span: arm.pattern.span,
});
}
if !covered.insert(variant.index) {
return Err(BodyAnalysisError::Unsupported {
feature: "duplicate enum match arm",
span: arm.pattern.span,
});
}
let binding = arm
.pattern
.binding
.as_ref()
.map(|binding| {
self.string(binding.string.0, binding.span)
.map(str::to_owned)
})
.transpose()?;
selected.push((variant, binding));
}
if covered.len() != variants.len() {
return Err(BodyAnalysisError::Unsupported {
feature: "non-exhaustive enum match",
span: match_.span,
});
}
let mut binding_places = Vec::with_capacity(selected.len());
for (variant, binding) in &selected {
let place = match (&variant.payload_type, binding) {
(Some(type_), Some(_)) => Some(self.add_local(
format!("$match_payload{}", self.locals.len()),
type_.clone(),
false,
false,
false,
match_.span,
)?),
_ => None,
};
binding_places.push(place);
}
let result_type = expected.cloned().unwrap_or(SemanticType::Void);
let produces_value = !matches!(result_type, SemanticType::Void);
let merge_block = self.create_block();
let merge_value = if produces_value {
let value = TypedValue {
id: IrValueId(self.next_value),
type_: result_type.clone(),
storage_place: None,
borrow_origins: Vec::new(),
};
self.next_value += 1;
self.blocks[merge_block.0 as usize]
.parameters
.push(value.clone());
Some(value)
} else {
None
};
let arm_blocks = match_
.arms
.iter()
.map(|_| self.create_block())
.collect::<Vec<_>>();
let tag_type = self.primitive(
match tag_bits {
8 => "u8",
16 => "u16",
32 => "u32",
64 => "u64",
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "unsupported enum tag width",
span: match_.span,
});
}
},
match_.span,
)?;
let tag_place = self.child_place(value_place, PlaceProjection::EnumTag, tag_type.clone());
let fallback_arms = selected
.iter()
.enumerate()
.filter_map(|(index, (variant, _))| variant.fallback.then_some(index))
.collect::<Vec<_>>();
if fallback_arms.len() > 1 {
return Err(BodyAnalysisError::Unsupported {
feature: "enum metadata has multiple fallback variants",
span: match_.span,
});
}
let fallback_arm = fallback_arms
.first()
.copied()
.unwrap_or_else(|| selected.len().saturating_sub(1));
let dispatch_tags = selected
.iter()
.enumerate()
.filter(|(arm_index, _)| *arm_index != fallback_arm)
.flat_map(|(arm_index, (variant, _))| {
variant
.matching_tags
.iter()
.copied()
.map(move |tag| (arm_index, tag))
})
.collect::<Vec<_>>();
for (arm_index, physical_tag) in dispatch_tags {
let tag = self.emit_value(
match_.span,
tag_type.clone(),
TypedInstructionKind::Load(tag_place),
);
let expected_tag = self.emit_value(
match_.arms[arm_index].pattern.span,
tag_type.clone(),
TypedInstructionKind::Constant(TypedConstant::Unsigned(physical_tag)),
);
let bool_type = self.primitive("bool", match_.span)?;
let condition = self.emit_value(
match_.arms[arm_index].pattern.span,
bool_type,
TypedInstructionKind::IntegerEqual {
left: tag.id,
right: expected_tag.id,
},
);
let next_test = self.create_block();
self.terminate(TypedTerminator::Branch {
condition: condition.id,
then_block: arm_blocks[arm_index],
else_block: next_test,
});
self.switch_to(next_test);
}
self.terminate(TypedTerminator::Jump {
target: arm_blocks[fallback_arm],
arguments: Vec::new(),
});
let initial_state = self.initialized.clone();
let initial_initialized_places = self.initialized_places.clone();
let initial_moved = self.moved.clone();
let initial_moved_places = self.moved_places.clone();
let initial_loans = self.active_loans.clone();
let initial_suspended = self.suspended_loans.clone();
let mut completed_state: Option<(Vec<bool>, Vec<PlaceId>, Vec<PlaceId>)> = None;
for (index, (arm, block)) in match_.arms.iter().zip(arm_blocks).enumerate() {
self.initialized = initial_state.clone();
self.initialized_places = initial_initialized_places.clone();
self.moved = initial_moved.clone();
self.moved_places = initial_moved_places.clone();
self.active_loans = initial_loans.clone();
self.suspended_loans = initial_suspended.clone();
self.switch_to(block);
self.local_scopes.push(BTreeMap::new());
if let (Some(binding), Some(binding_place)) =
(&selected[index].1, binding_places[index])
{
let binding_local = place_local_id(&self.places[binding_place.0 as usize]);
self.local_scopes
.last_mut()
.expect("match arm scope exists")
.insert(binding.clone(), binding_local);
let payload_type = selected[index]
.0
.payload_type
.clone()
.expect("binding requires payload type");
let payload_place = self.child_place(
value_place,
PlaceProjection::EnumPayload(selected[index].0.index),
payload_type.clone(),
);
let payload = self.emit_value(
arm.pattern.span,
payload_type,
TypedInstructionKind::Load(payload_place),
);
self.emit_instruction(TypedInstruction {
span: arm.pattern.span,
result: None,
kind: TypedInstructionKind::Store {
place: binding_place,
value: payload.id,
},
});
self.initialized[binding_local.0 as usize] = true;
}
let arm_value = self.expression(&arm.expression, Some(&result_type))?;
if self.current_terminated() {
self.local_scopes.pop();
return Err(BodyAnalysisError::Unsupported {
feature: "diverging enum match arms",
span: arm.span,
});
}
self.consume_value(&arm_value, arm.span)?;
if let Some(binding_place) = binding_places[index] {
let binding_local = place_local_id(&self.places[binding_place.0 as usize]);
self.emit_drop(binding_place, arm.span);
self.release_holder_loans(binding_local);
self.initialized[binding_local.0 as usize] = false;
self.moved[binding_local.0 as usize] = false;
self.moved_places = self
.moved_places
.iter()
.copied()
.filter(|place| !self.place_contains(binding_place, *place))
.collect();
self.initialized_places = self
.initialized_places
.iter()
.copied()
.filter(|place| !self.place_contains(binding_place, *place))
.collect();
}
self.local_scopes.pop();
if self.current_terminated() {
return Err(BodyAnalysisError::Unsupported {
feature: "diverging enum match arms",
span: arm.span,
});
}
if let Some((state, places, moved_places)) = &completed_state {
self.ensure_branch_place_states_match(
state,
&self.initialized.clone(),
places,
&self.initialized_places.clone(),
moved_places,
&self.moved_places.clone(),
initial_state.len(),
arm.span,
)?;
} else {
completed_state = Some((
self.initialized.clone(),
self.initialized_places.clone(),
self.moved_places.clone(),
));
}
self.terminate(TypedTerminator::Jump {
target: merge_block,
arguments: merge_value
.as_ref()
.map(|_| vec![arm_value.id])
.unwrap_or_default(),
});
}
self.switch_to(merge_block);
Ok(merge_value.unwrap_or_else(|| self.detached_value(SemanticType::Void)))
}
fn if_expression(
&mut self,
if_: &crate::parsing::ast::IfExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
if !if_.else_ifs.is_empty() {
return Err(BodyAnalysisError::Unsupported {
feature: "else-if CFG lowering",
span: if_.span,
});
}
let result_type = expected.cloned().unwrap_or(SemanticType::Void);
let produces_value = !matches!(result_type, SemanticType::Void);
if produces_value && if_.else_.is_none() {
return Err(BodyAnalysisError::MissingElseForValueIf { span: if_.span });
}
let bool_type = self.primitive("bool", if_.declaration.condition.span)?;
let condition = self.expression(&if_.declaration.condition, Some(&bool_type))?;
let then_block = self.create_block();
let else_block = self.create_block();
let merge_block = self.create_block();
let merge_value = if produces_value {
let value = TypedValue {
id: IrValueId(self.next_value),
type_: result_type.clone(),
storage_place: None,
borrow_origins: Vec::new(),
};
self.next_value += 1;
self.blocks[merge_block.0 as usize]
.parameters
.push(value.clone());
Some(value)
} else {
None
};
self.terminate(TypedTerminator::Branch {
condition: condition.id,
then_block,
else_block,
});
let initial_state = self.initialized.clone();
let initial_initialized_places = self.initialized_places.clone();
let initial_moved = self.moved.clone();
let initial_moved_places = self.moved_places.clone();
let initial_loans = self.active_loans.clone();
let initial_suspended = self.suspended_loans.clone();
self.switch_to(then_block);
let then_value = self.expression(&if_.expression, Some(&result_type))?;
let then_terminated = self.current_terminated();
let then_state = self.initialized.clone();
let then_initialized_places = self.initialized_places.clone();
let then_moved = self.moved.clone();
let then_moved_places = self.moved_places.clone();
let then_loans = self.active_loans.clone();
let then_suspended = self.suspended_loans.clone();
if !then_terminated {
self.terminate(TypedTerminator::Jump {
target: merge_block,
arguments: merge_value
.as_ref()
.map(|_| vec![then_value.id])
.unwrap_or_default(),
});
}
self.initialized = initial_state.clone();
self.initialized_places = initial_initialized_places.clone();
self.moved = initial_moved.clone();
self.moved_places = initial_moved_places.clone();
self.active_loans = initial_loans.clone();
self.suspended_loans = initial_suspended.clone();
self.switch_to(else_block);
let else_value = if let Some(else_) = &if_.else_ {
Some(self.expression(&else_.expression, Some(&result_type))?)
} else {
None
};
let else_terminated = self.current_terminated();
let else_state = self.initialized.clone();
let else_initialized_places = self.initialized_places.clone();
let else_moved = self.moved.clone();
let else_moved_places = self.moved_places.clone();
let else_loans = self.active_loans.clone();
let else_suspended = self.suspended_loans.clone();
if !else_terminated {
self.terminate(TypedTerminator::Jump {
target: merge_block,
arguments: merge_value
.as_ref()
.map(|_| {
vec![
else_value
.as_ref()
.expect("value-producing if requires else")
.id,
]
})
.unwrap_or_default(),
});
}
if !then_terminated && !else_terminated {
self.ensure_branch_place_states_match(
&then_state,
&else_state,
&then_initialized_places,
&else_initialized_places,
&then_moved_places,
&else_moved_places,
initial_state.len(),
if_.span,
)?;
}
self.moved = match (then_terminated, else_terminated) {
(false, false) => then_moved
.iter()
.zip(else_moved)
.map(|(then, else_)| *then && else_)
.collect(),
(false, true) => then_moved,
(true, false) => else_moved,
(true, true) => initial_moved,
};
self.moved_places = match (then_terminated, else_terminated) {
(false, false) => {
let mut moved = then_moved_places;
moved.extend(else_moved_places);
moved
}
(false, true) => then_moved_places,
(true, false) => else_moved_places,
(true, true) => initial_moved_places,
};
self.initialized = match (then_terminated, else_terminated) {
(false, false) => then_state
.iter()
.zip(else_state)
.map(|(then, else_)| *then && else_)
.collect(),
(false, true) => then_state,
(true, false) => else_state,
(true, true) => initial_state,
};
self.initialized_places = match (then_terminated, else_terminated) {
(false, false) => then_initialized_places
.into_iter()
.filter(|then| {
else_initialized_places
.iter()
.any(|else_| self.same_place(*then, *else_))
})
.collect(),
(false, true) => then_initialized_places,
(true, false) => else_initialized_places,
(true, true) => initial_initialized_places,
};
self.active_loans = match (then_terminated, else_terminated) {
(false, false) => then_loans
.into_iter()
.filter(|loan| else_loans.contains(loan))
.collect(),
(false, true) => then_loans,
(true, false) => else_loans,
(true, true) => initial_loans,
};
self.suspended_loans = match (then_terminated, else_terminated) {
(false, false) => then_suspended
.into_iter()
.filter(|loan| else_suspended.contains(loan))
.collect(),
(false, true) => then_suspended,
(true, false) => else_suspended,
(true, true) => initial_suspended,
};
self.switch_to(merge_block);
if let Some(mut value) = merge_value {
let mut borrow_origins = Vec::new();
if !then_terminated {
borrow_origins.extend(then_value.borrow_origins);
}
if !else_terminated && let Some(else_value) = else_value {
borrow_origins.extend(else_value.borrow_origins);
}
borrow_origins.sort_by_key(|place| place.0);
borrow_origins.dedup();
value.borrow_origins = borrow_origins;
Ok(value)
} else {
Ok(self.emit_value(
if_.span,
SemanticType::Void,
TypedInstructionKind::Constant(TypedConstant::Void),
))
}
}
fn while_expression(
&mut self,
while_: &crate::parsing::ast::WhileExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
if let Some(expected) = expected {
self.require_type(expected, &SemanticType::Void, while_.span)?;
}
let initial_state = self.initialized.clone();
let initial_initialized_places = self.initialized_places.clone();
let initial_moved = self.moved.clone();
let initial_moved_places = self.moved_places.clone();
let initial_loans = self.active_loans.clone();
let initial_suspended = self.suspended_loans.clone();
let condition_block = self.create_block();
let body_block = self.create_block();
let exit_block = self.create_block();
self.terminate(TypedTerminator::Jump {
target: condition_block,
arguments: Vec::new(),
});
self.switch_to(condition_block);
let bool_type = self.primitive("bool", while_.condition.span)?;
let condition = self.expression(&while_.condition, Some(&bool_type))?;
self.terminate(TypedTerminator::Branch {
condition: condition.id,
then_block: body_block,
else_block: exit_block,
});
self.switch_to(body_block);
self.expression(&while_.expression, Some(&SemanticType::Void))?;
let body_terminated = self.current_terminated();
if !body_terminated {
self.ensure_branch_place_states_match(
&initial_state,
&self.initialized,
&initial_initialized_places,
&self.initialized_places,
&initial_moved_places,
&self.moved_places,
initial_state.len(),
while_.span,
)?;
self.terminate(TypedTerminator::Jump {
target: condition_block,
arguments: Vec::new(),
});
}
self.initialized = initial_state;
self.initialized_places = initial_initialized_places;
self.moved = initial_moved;
self.moved_places = initial_moved_places;
self.active_loans = initial_loans;
self.suspended_loans = initial_suspended;
self.switch_to(exit_block);
Ok(self.emit_value(
while_.span,
SemanticType::Void,
TypedInstructionKind::Constant(TypedConstant::Void),
))
}
fn loop_expression(
&mut self,
loop_: &crate::parsing::ast::LoopExpression,
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let body_block = self.create_block();
self.terminate(TypedTerminator::Jump {
target: body_block,
arguments: Vec::new(),
});
self.switch_to(body_block);
if let Some(expression) = &loop_.expression {
self.expression(expression, Some(&SemanticType::Void))?;
}
if !self.current_terminated() {
self.terminate(TypedTerminator::Jump {
target: body_block,
arguments: Vec::new(),
});
}
Ok(self.detached_value(expected.cloned().unwrap_or(SemanticType::Void)))
}
fn coerce_expression(
&mut self,
expression: &Expression,
expected: &SemanticType,
) -> Result<TypedValue, BodyAnalysisError> {
if let SemanticType::Reference { .. } = expected {
let contextual_reference = match &expression.kind {
ExpressionKind::Source(ExpressionSource::Value(value)) => is_control_value(value),
ExpressionKind::Source(ExpressionSource::Access(access)) => {
matches!(
&access.entry,
AccessExpressionEntry::ValueExpression(value) if is_control_value(value)
)
}
_ => false,
};
let mut value =
self.expression(expression, contextual_reference.then_some(expected))?;
if value.type_ == *expected {
return Ok(value);
}
if let SemanticType::Reference {
mutable: actual_mutable,
target: actual_target,
..
} = &value.type_
&& matches!(expected, SemanticType::Reference { mutable, target, .. }
if actual_mutable == mutable && actual_target == target)
{
value.type_ = expected.clone();
return Ok(value);
}
self.require_type(expected, &value.type_, expression.span)?;
return Ok(value);
}
let value = self.expression(expression, Some(expected))?;
self.consume_value(&value, expression.span)?;
Ok(value)
}
fn coerce_method_argument(
&mut self,
expression: &Expression,
expected: &SemanticType,
) -> Result<TypedValue, BodyAnalysisError> {
if let SemanticType::Reference {
mutable, target, ..
} = expected
&& !matches!(expression.kind, ExpressionKind::Unary { .. })
{
let value = self.expression(expression, Some(target))?;
return self.borrow_value(expression.span, value, expected.clone(), *mutable);
}
self.coerce_expression(expression, expected)
}
fn borrow_value(
&mut self,
span: Span,
value: TypedValue,
reference_type: SemanticType,
mutable: bool,
) -> Result<TypedValue, BodyAnalysisError> {
let place = if let Some(place) = value.storage_place {
place
} else {
let name = format!("<temporary:{}>", self.locals.len());
let place = self.add_local(name, value.type_.clone(), mutable, false, true, span)?;
self.emit_instruction(TypedInstruction {
span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: value.id,
},
});
place
};
if mutable && !self.places[place.0 as usize].mutable {
return Err(BodyAnalysisError::MutableBorrowOfImmutablePlace { span });
}
Ok(self.emit_value(
span,
reference_type,
TypedInstructionKind::Borrow { place, mutable },
))
}
fn dereference_expression(
&mut self,
operand: &Expression,
span: Span,
expected: Option<&SemanticType>,
mutable: bool,
) -> Result<TypedValue, BodyAnalysisError> {
let value = self.expression(operand, None)?;
self.dereference_value(value, span, expected, mutable)
}
fn dereference_value(
&mut self,
value: TypedValue,
span: Span,
expected: Option<&SemanticType>,
mutable: bool,
) -> Result<TypedValue, BodyAnalysisError> {
let Some(mut place) = value.storage_place else {
return Err(BodyAnalysisError::Unsupported {
feature: "dereference of a non-addressable temporary",
span,
});
};
let target = match &value.type_ {
SemanticType::Pointer {
mutable: pointer_mutable,
target,
}
| SemanticType::Reference {
mutable: pointer_mutable,
target,
..
} => {
if mutable && !pointer_mutable {
return Err(BodyAnalysisError::MutableBorrowOfImmutablePlace { span });
}
target.as_ref().clone()
}
SemanticType::Named(named)
if named.path.module == crate::core_lib::BOX_MODULE_FILE_PATH
&& named.path.local == "Box" =>
{
let [crate::semantic::SemanticGenericArgument::Type(target)] =
named.generic_arguments.as_slice()
else {
return Err(BodyAnalysisError::Unsupported {
feature: "Box dereference without a concrete item type",
span,
});
};
if self.visible_deref_target(named, span, mutable)?.as_ref() != Some(target) {
return Err(BodyAnalysisError::Unsupported {
feature: if mutable {
"mutable dereference requires a visible DerefMut implementation"
} else {
"dereference requires a visible Deref implementation"
},
span,
});
}
let pointer_type = SemanticType::Pointer {
mutable: true,
target: Box::new(target.clone()),
};
place = self.child_place(
place,
PlaceProjection::Field("pointer".into()),
pointer_type,
);
target.clone()
}
SemanticType::Named(named) => {
let named = named.clone();
let Some(target) = self.visible_deref_target(&named, span, mutable)? else {
return Err(BodyAnalysisError::Unsupported {
feature: if mutable {
"mutable dereference requires a visible DerefMut implementation"
} else {
"dereference requires a visible Deref implementation"
},
span,
});
};
let reference_type = SemanticType::Reference {
lifetime: None,
mutable,
target: Box::new(target.clone()),
};
let reference = self.method_call(
span,
value,
if mutable { "deref_mut" } else { "deref" },
&[],
Some(&reference_type),
)?;
let reference_place = if let Some(place) = reference.storage_place {
place
} else {
let place = self.add_local(
format!("<deref:{}>", self.locals.len()),
reference_type,
mutable,
false,
true,
span,
)?;
self.emit_instruction(TypedInstruction {
span,
result: None,
kind: TypedInstructionKind::Store {
place,
value: reference.id,
},
});
let local = place_local_id(&self.places[place.0 as usize]);
self.initialized[local.0 as usize] = true;
place
};
place = reference_place;
target
}
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "dereference of a non-pointer value",
span,
});
}
};
let place = self.child_place(place, PlaceProjection::Dereference, target.clone());
if mutable {
self.places[place.0 as usize].mutable = true;
}
if let Some(expected) = expected {
self.require_type(expected, &target, span)?;
}
Ok(self.emit_value(span, target, TypedInstructionKind::Load(place)))
}
fn visible_deref_target(
&self,
target: &SemanticNamedType,
span: Span,
mutable: bool,
) -> Result<Option<SemanticType>, BodyAnalysisError> {
let environment = ExtensionEnvironment::build(self.graph, self.module)
.map_err(|errors| BodyAnalysisError::ExtensionActivation { span, errors })?;
let table = MethodTable::build_named(self.graph, target, &environment)
.map_err(|error| BodyAnalysisError::MethodLookup { span, error })?;
let trait_name = if mutable { "DerefMut" } else { "Deref" };
let has_capability = table.trait_implementations.iter().any(|implementation| {
let origin = match &implementation.source {
MethodSource::Inherent => target.path.module.as_str(),
MethodSource::Extension { origin_module, .. } => origin_module.as_str(),
};
self.graph
.resolve(origin, &implementation.trait_path)
.is_ok_and(|resolved| {
resolved.module_path == crate::core_lib::DEREF_MODULE_FILE_PATH
&& resolved.local_path == trait_name
})
});
if !has_capability {
return Ok(None);
}
Ok(table
.trait_implementations
.iter()
.find_map(|implementation| {
implementation
.concrete_associated_types
.get("Target")
.cloned()
}))
}
fn method_call(
&mut self,
span: Span,
receiver: TypedValue,
name: &str,
arguments: &[Expression],
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
let (named, receiver_type, receiver_reference) = match &receiver.type_ {
SemanticType::Named(named) => (named, receiver.type_.clone(), None),
SemanticType::Reference {
mutable, target, ..
} => {
let SemanticType::Named(named) = target.as_ref() else {
return Err(BodyAnalysisError::Unsupported {
feature: "methods on references to non-named types",
span,
});
};
(named, target.as_ref().clone(), Some(*mutable))
}
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "methods on non-named types",
span,
});
}
};
let target = named.path.clone();
let environment = ExtensionEnvironment::build(self.graph, self.module)
.map_err(|errors| BodyAnalysisError::ExtensionActivation { span, errors })?;
let table = MethodTable::build(self.graph, &target, &environment)
.map_err(|error| BodyAnalysisError::MethodLookup { span, error })?;
let function_id = table
.resolve_function(self.functions, &target, name)
.map_err(|error| BodyAnalysisError::MethodLookup { span, error })?;
let function = self
.functions
.function(function_id)
.expect("MethodTable returned an invalid GlobalFunctionId")
.clone();
if function.signature.receiver.is_none() {
return Err(BodyAnalysisError::Unsupported {
feature: "static function called with method syntax",
span,
});
}
if arguments.len() != function.signature.arguments.len() {
return Err(BodyAnalysisError::ArgumentCount {
function: function.path,
expected: function.signature.arguments.len(),
actual: arguments.len(),
span,
});
}
let receiver_argument = match &function.signature.receiver {
Some(receiver_kind) if receiver_kind.borrow => {
if let Some(reference_mutable) = receiver_reference {
if receiver_kind.mutable && !reference_mutable {
return Err(BodyAnalysisError::MutableBorrowOfImmutablePlace { span });
}
receiver
} else {
let reference_type = SemanticType::Reference {
lifetime: receiver_kind.lifetime.clone(),
mutable: receiver_kind.mutable,
target: Box::new(receiver_type.clone()),
};
self.borrow_value(span, receiver, reference_type, receiver_kind.mutable)?
}
}
Some(_) if receiver_reference.is_some() => {
return Err(BodyAnalysisError::Unsupported {
feature: "moving an owned receiver through a reference",
span,
});
}
Some(_) => {
self.consume_value(&receiver, span)?;
receiver
}
None => unreachable!("receiver presence was checked above"),
};
let receiver_parameter_type = match function.signature.receiver.as_ref() {
Some(receiver) if receiver.borrow => SemanticType::Reference {
lifetime: receiver.lifetime.clone(),
mutable: receiver.mutable,
target: Box::new(receiver_type.clone()),
},
Some(_) => receiver_type.clone(),
None => unreachable!("receiver presence was checked above"),
};
let mut parameter_types = Vec::with_capacity(arguments.len() + 1);
parameter_types.push(receiver_parameter_type);
let mut argument_values = Vec::with_capacity(arguments.len() + 1);
argument_values.push(receiver_argument);
for (argument, parameter) in arguments.iter().zip(&function.signature.arguments) {
let parameter_type = substitute_self(¶meter.type_, &receiver_type);
argument_values.push(self.coerce_method_argument(argument, ¶meter_type)?);
parameter_types.push(parameter_type);
}
self.validate_call_borrows(&argument_values, span)?;
let values = argument_values.iter().map(|value| value.id).collect();
let return_type = substitute_visible_associated_types(
&substitute_self(function.signature.return_type.as_ref(), &receiver_type),
&table,
);
if let Some(expected) = expected {
self.require_type(expected, &return_type, span)?;
}
let origins =
reference_return_origins(&return_type, parameter_types.iter(), &argument_values);
let cleanup = self.checked_cleanup_plan();
let mut result = self.emit_value(
span,
return_type,
TypedInstructionKind::Call {
function: function.id,
arguments: values,
cleanup,
},
);
result.borrow_origins = origins;
Ok(result)
}
fn method_access<'b>(
&self,
access: &'b AccessExpression,
) -> Result<Option<(String, &'b [Expression])>, BodyAnalysisError> {
let [
AccessExpressionAccessor::Next(next),
AccessExpressionAccessor::Sub(sub),
] = access.accessors.as_slice()
else {
return Ok(None);
};
let crate::parsing::ast::AccessExpressionNextAccessor::Ident(method) = next.as_ref() else {
return Ok(None);
};
let AccessExpressionSubAccessor::Arguments(arguments) = sub.as_ref() else {
return Ok(None);
};
Ok(Some((
self.string(method.ident.string.0, method.span)?.to_owned(),
&arguments.expressions,
)))
}
fn access_entry_value(
&mut self,
access: &AccessExpression,
) -> Result<TypedValue, BodyAnalysisError> {
match &access.entry {
AccessExpressionEntry::Ident(entry) => {
let name = self.string(entry.ident.string.0, entry.span)?.to_owned();
let local = self
.resolve_local(&name)
.ok_or(BodyAnalysisError::UnknownValue {
name,
span: entry.span,
})?;
let place = self.local_places[local.0 as usize];
self.require_initialized(place, access.span)?;
let type_ = self.places[place.0 as usize].type_.clone();
Ok(self.emit_value(access.span, type_, TypedInstructionKind::Load(place)))
}
AccessExpressionEntry::ValueExpression(value) => self.value(value, None),
AccessExpressionEntry::Parenthesized(expression) => self.expression(expression, None),
AccessExpressionEntry::Self_(_) => Err(BodyAnalysisError::Unsupported {
feature: "self value binding",
span: access.span,
}),
}
}
fn call(
&mut self,
span: Span,
function: &GlobalFunction,
arguments: &[Expression],
expected: Option<&SemanticType>,
) -> Result<TypedValue, BodyAnalysisError> {
if function.signature.receiver.is_some() {
return Err(BodyAnalysisError::Unsupported {
feature: "method calls",
span,
});
}
if arguments.len() != function.signature.arguments.len() {
return Err(BodyAnalysisError::ArgumentCount {
function: function.path.clone(),
expected: function.signature.arguments.len(),
actual: arguments.len(),
span,
});
}
let mut substitutions = BTreeMap::new();
if let Some(expected) = expected {
infer_type_substitutions(
function.signature.return_type.as_ref(),
expected,
&mut substitutions,
);
}
let parameter_types = function
.signature
.arguments
.iter()
.map(|parameter| {
if function.generic_parameters.is_empty() {
Ok(parameter.type_.clone())
} else {
normalize_type(¶meter.type_, &substitutions, self.graph, self.module)
.map_err(|_| BodyAnalysisError::Unsupported {
feature: "cannot infer generic function arguments",
span,
})
}
})
.collect::<Result<Vec<_>, _>>()?;
let mut argument_values = Vec::with_capacity(arguments.len());
for (argument, parameter_type) in arguments.iter().zip(¶meter_types) {
argument_values.push(self.coerce_expression(argument, parameter_type)?);
}
self.validate_call_borrows(&argument_values, span)?;
let values = argument_values.iter().map(|value| value.id).collect();
let return_type = if function.generic_parameters.is_empty() {
function.signature.return_type.as_ref().clone()
} else {
normalize_type(
function.signature.return_type.as_ref(),
&substitutions,
self.graph,
self.module,
)
.map_err(|_| BodyAnalysisError::Unsupported {
feature: "cannot infer generic function arguments",
span,
})?
};
if let Some(expected) = expected {
self.require_type(expected, &return_type, span)?;
}
let origins = reference_return_origins(
&return_type,
function
.signature
.arguments
.iter()
.map(|argument| &argument.type_),
&argument_values,
);
let cleanup = self.checked_cleanup_plan();
let mut result = self.emit_value(
span,
return_type,
TypedInstructionKind::Call {
function: function.id,
arguments: values,
cleanup,
},
);
result.borrow_origins = origins;
Ok(result)
}
fn enum_constructor(
&mut self,
access: &AccessExpression,
expected: Option<&SemanticType>,
) -> Result<Option<TypedValue>, BodyAnalysisError> {
let AccessExpressionEntry::Ident(entry) = &access.entry else {
return Ok(None);
};
let mut parts = vec![self.string(entry.ident.string.0, entry.span)?.to_owned()];
let mut arguments: &[Expression] = &[];
for (index, accessor) in access.accessors.iter().enumerate() {
match accessor {
AccessExpressionAccessor::Next(next) => {
let crate::parsing::ast::AccessExpressionNextAccessor::Ident(ident) =
next.as_ref()
else {
return Ok(None);
};
parts.push(self.string(ident.ident.string.0, ident.span)?.to_owned());
}
AccessExpressionAccessor::Sub(sub) if index + 1 == access.accessors.len() => {
let AccessExpressionSubAccessor::Arguments(call) = sub.as_ref() else {
return Ok(None);
};
arguments = &call.expressions;
}
AccessExpressionAccessor::Sub(_) => return Ok(None),
}
}
if parts.len() < 2 {
return Ok(None);
}
let variant_name = parts.pop().expect("variant path has two parts");
let type_path = parts.join(".");
let Ok(resolved) = self.graph.resolve(self.module, &type_path) else {
return Ok(None);
};
let canonical = CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
};
let named = match expected {
Some(SemanticType::Named(expected)) if expected.path == canonical => expected.clone(),
_ => SemanticNamedType {
path: canonical,
generic_arguments: Vec::new(),
},
};
let Some(registry) = self.type_metadata else {
return Ok(None);
};
let Some(metadata) = registry.get_named(&named) else {
return Ok(None);
};
let TypeMetadataKind::Enum {
tag_bits, variants, ..
} = &metadata.kind
else {
return Ok(None);
};
if metadata.origin == TypeOrigin::Rust {
return Err(BodyAnalysisError::Unsupported {
feature: "native enum variants require an imported Rust constructor",
span: access.span,
});
}
let tag_bits = *tag_bits;
let Some(variant) = variants
.iter()
.find(|variant| variant.name == variant_name)
.cloned()
else {
return Err(BodyAnalysisError::Unsupported {
feature: "unknown enum variant",
span: access.span,
});
};
let expected_arguments = usize::from(variant.payload_type.is_some());
if arguments.len() != expected_arguments {
return Err(BodyAnalysisError::Unsupported {
feature: "invalid enum constructor argument count",
span: access.span,
});
}
let type_ = SemanticType::Named(named);
if let Some(expected) = expected {
self.require_type(expected, &type_, access.span)?;
}
let temporary = self.add_local(
format!("$enum{}", self.locals.len()),
type_.clone(),
true,
false,
false,
access.span,
)?;
if variant.writes_tag {
let tag_type = self.primitive(
match tag_bits {
8 => "u8",
16 => "u16",
32 => "u32",
64 => "u64",
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "unsupported enum tag width",
span: access.span,
});
}
},
access.span,
)?;
let tag = self.emit_value(
access.span,
tag_type.clone(),
TypedInstructionKind::Constant(TypedConstant::Unsigned(variant.tag)),
);
let tag_place = self.child_place(temporary, PlaceProjection::EnumTag, tag_type);
self.emit_instruction(TypedInstruction {
span: access.span,
result: None,
kind: TypedInstructionKind::Store {
place: tag_place,
value: tag.id,
},
});
}
if let Some(payload_type) = variant.payload_type {
let value = self.coerce_expression(&arguments[0], &payload_type)?;
if self.current_terminated() {
return Ok(Some(self.detached_value(type_)));
}
self.consume_value(&value, access.span)?;
let payload_place = self.child_place(
temporary,
PlaceProjection::EnumPayload(variant.index),
payload_type,
);
self.emit_instruction(TypedInstruction {
span: access.span,
result: None,
kind: TypedInstructionKind::Store {
place: payload_place,
value: value.id,
},
});
}
let temporary_local = place_local_id(&self.places[temporary.0 as usize]);
self.initialized[temporary_local.0 as usize] = true;
Ok(Some(self.emit_value(
access.span,
type_,
TypedInstructionKind::Load(temporary),
)))
}
fn function_call<'b>(
&self,
access: &'b AccessExpression,
) -> Result<(String, &'b [Expression]), BodyAnalysisError> {
let AccessExpressionEntry::Ident(entry) = &access.entry else {
return Err(BodyAnalysisError::Unsupported {
feature: "call target expression",
span: access.span,
});
};
let mut parts = vec![self.string(entry.ident.string.0, entry.span)?.to_owned()];
let Some((last, prefix)) = access.accessors.split_last() else {
return Err(BodyAnalysisError::UnknownFunction {
path: parts[0].clone(),
span: access.span,
});
};
for accessor in prefix {
match accessor {
AccessExpressionAccessor::Next(next) => match next.as_ref() {
crate::parsing::ast::AccessExpressionNextAccessor::Ident(ident) => {
parts.push(self.string(ident.ident.string.0, ident.span)?.to_owned())
}
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "tuple field call paths",
span: access.span,
});
}
},
_ => {
return Err(BodyAnalysisError::Unsupported {
feature: "postfix operation before a call",
span: access.span,
});
}
}
}
let AccessExpressionAccessor::Sub(sub) = last else {
return Err(BodyAnalysisError::UnknownFunction {
path: parts.join("."),
span: access.span,
});
};
let AccessExpressionSubAccessor::Arguments(arguments) = sub.as_ref() else {
return Err(BodyAnalysisError::Unsupported {
feature: "index expressions",
span: access.span,
});
};
Ok((parts.join("."), &arguments.expressions))
}
fn place_expression(
&mut self,
expression: &Expression,
mutable: bool,
) -> Result<TypedValue, BodyAnalysisError> {
if let ExpressionKind::Unary {
operator,
expression: operand,
} = &expression.kind
&& operator.kind == crate::parsing::ast::UnaryExpressionOperatorKind::Dereference
{
let operand = self.place_expression(operand, mutable)?;
return self.dereference_value(operand, expression.span, None, mutable);
}
self.expression(expression, None)
}
fn place_access(
&mut self,
access: &AccessExpression,
mutable: bool,
) -> Result<(PlaceId, String), BodyAnalysisError> {
let (mut place, name) = match &access.entry {
AccessExpressionEntry::Ident(entry) => {
let name = self.string(entry.ident.string.0, entry.span)?.to_owned();
let local =
self.resolve_local(&name)
.ok_or_else(|| BodyAnalysisError::UnknownValue {
name: name.clone(),
span: access.span,
})?;
(self.local_places[local.0 as usize], name)
}
AccessExpressionEntry::Parenthesized(expression) => {
let value = self.place_expression(expression, mutable)?;
let place = value.storage_place.ok_or(BodyAnalysisError::Unsupported {
feature: "parenthesized assignment root without addressable storage",
span: expression.span,
})?;
(place, "parenthesized place".into())
}
AccessExpressionEntry::ValueExpression(value) => {
let value = self.value(value, None)?;
let place = value.storage_place.ok_or(BodyAnalysisError::Unsupported {
feature: "value assignment root without addressable storage",
span: access.span,
})?;
(place, "value place".into())
}
AccessExpressionEntry::Self_(_) => {
return Err(BodyAnalysisError::Unsupported {
feature: "self value binding",
span: access.span,
});
}
};
for accessor in &access.accessors {
match accessor {
AccessExpressionAccessor::Next(next) => match next.as_ref() {
crate::parsing::ast::AccessExpressionNextAccessor::Ident(ident) => {
let field_name = self.string(ident.ident.string.0, ident.span)?.to_owned();
place = self.project_field(place, field_name, ident.span)?;
}
crate::parsing::ast::AccessExpressionNextAccessor::Item(item) => {
place = self.project_tuple_field(place, item.index, item.span)?;
}
},
AccessExpressionAccessor::Sub(sub) => match sub.as_ref() {
AccessExpressionSubAccessor::Index(index) => {
place = self.project_index(place, index)?;
}
AccessExpressionSubAccessor::Arguments(_) => {
return Err(BodyAnalysisError::Unsupported {
feature: "calls on projected places",
span: access.span,
});
}
},
}
}
Ok((place, name))
}
fn project_index(
&mut self,
base: PlaceId,
index: &Expression,
) -> Result<PlaceId, BodyAnalysisError> {
let mut base_place = self.places[base.0 as usize].clone();
if let SemanticType::Reference {
mutable, target, ..
} = &base_place.type_
{
let mut projections = base_place.projections.clone();
projections.push(PlaceProjection::Dereference);
base_place = TypedPlace {
id: PlaceId(self.places.len() as u32),
base: base_place.base,
projections,
type_: target.as_ref().clone(),
mutable: *mutable,
};
self.places.push(base_place.clone());
}
let SemanticType::Array {
item,
size: Some(length),
} = &base_place.type_
else {
return Err(BodyAnalysisError::Unsupported {
feature: "indexing non-fixed arrays",
span: index.span,
});
};
let item_type = item.as_ref().clone();
let length = *length;
let usize_type = self.primitive("usize", index.span)?;
let index_value = self.expression(index, Some(&usize_type))?;
let cleanup = self.checked_cleanup_plan();
self.emit_instruction(TypedInstruction {
span: index.span,
result: None,
kind: TypedInstructionKind::BoundsCheck {
index: index_value.id,
length,
cleanup,
},
});
let id = PlaceId(self.places.len() as u32);
let mut projections = base_place.projections;
projections.push(match constant_usize(index) {
Some(index) => PlaceProjection::ConstantIndex(index),
None => PlaceProjection::Index(index_value.id),
});
self.places.push(TypedPlace {
id,
base: base_place.base,
projections,
type_: item_type,
mutable: base_place.mutable,
});
Ok(id)
}
fn project_tuple_field(
&mut self,
base: PlaceId,
index: usize,
span: Span,
) -> Result<PlaceId, BodyAnalysisError> {
let mut base_place = self.places[base.0 as usize].clone();
if let SemanticType::Reference {
mutable, target, ..
} = &base_place.type_
{
let mut projections = base_place.projections.clone();
projections.push(PlaceProjection::Dereference);
base_place = TypedPlace {
id: PlaceId(self.places.len() as u32),
base: base_place.base,
projections,
type_: target.as_ref().clone(),
mutable: *mutable,
};
self.places.push(base_place.clone());
}
let SemanticType::Tuple(items) = &base_place.type_ else {
return Err(BodyAnalysisError::MissingTypeMetadata {
type_: base_place.type_,
span,
});
};
let item_type =
items
.get(index)
.cloned()
.ok_or_else(|| BodyAnalysisError::UnknownField {
type_: base_place.type_.clone(),
field: index.to_string(),
span,
})?;
let id = PlaceId(self.places.len() as u32);
let mut projections = base_place.projections;
projections.push(PlaceProjection::TupleField(index));
self.places.push(TypedPlace {
id,
base: base_place.base,
projections,
type_: item_type,
mutable: base_place.mutable,
});
Ok(id)
}
fn project_field(
&mut self,
base: PlaceId,
field_name: String,
span: Span,
) -> Result<PlaceId, BodyAnalysisError> {
let mut base = base;
let mut base_place = self.places[base.0 as usize].clone();
if let SemanticType::Reference {
mutable, target, ..
} = &base_place.type_
{
let id = PlaceId(self.places.len() as u32);
let mut projections = base_place.projections.clone();
projections.push(PlaceProjection::Dereference);
self.places.push(TypedPlace {
id,
base: base_place.base,
projections,
type_: target.as_ref().clone(),
mutable: *mutable,
});
base = id;
base_place = self.places[base.0 as usize].clone();
}
let SemanticType::Named(named) = &base_place.type_ else {
return Err(BodyAnalysisError::MissingTypeMetadata {
type_: base_place.type_,
span,
});
};
let metadata = self
.type_metadata
.and_then(|registry| registry.get_named(named))
.ok_or_else(|| BodyAnalysisError::MissingTypeMetadata {
type_: base_place.type_.clone(),
span,
})?;
let TypeMetadataKind::Structure { fields } = &metadata.kind else {
return Err(BodyAnalysisError::MissingTypeMetadata {
type_: base_place.type_.clone(),
span,
});
};
let field = fields
.iter()
.find(|field| field.name == field_name)
.ok_or_else(|| BodyAnalysisError::UnknownField {
type_: base_place.type_.clone(),
field: field_name.clone(),
span,
})?;
if metadata.path.module != self.module && !field.public {
return Err(BodyAnalysisError::PrivateField {
type_: base_place.type_.clone(),
field: field_name,
span,
});
}
let id = PlaceId(self.places.len() as u32);
let mut projections = base_place.projections;
projections.push(PlaceProjection::Field(field.name.clone()));
self.places.push(TypedPlace {
id,
base: base_place.base,
projections,
type_: field.type_.clone(),
mutable: base_place.mutable,
});
Ok(id)
}
fn emit_scope_drops(&mut self, first_local: usize, span: Span) {
let mut places = self
.locals
.iter()
.skip(first_local)
.rev()
.filter_map(|local| {
self.initialized
.get(local.id.0 as usize)
.copied()
.unwrap_or(false)
.then(|| self.local_places[local.id.0 as usize])
})
.collect::<Vec<_>>();
places.extend(
self.initialized_places
.iter()
.rev()
.copied()
.filter(|place| {
let local = place_local_id(&self.places[place.0 as usize]);
local.0 as usize >= first_local && !self.initialized[local.0 as usize]
}),
);
for place in places {
let local = place_local_id(&self.places[place.0 as usize]);
self.release_holder_loans(local);
let has_drop = self
.drop_function_for(&self.places[place.0 as usize].type_)
.is_some();
self.emit_drop(place, span);
self.initialized_places = self
.initialized_places
.iter()
.copied()
.filter(|initialized| !self.place_contains(place, *initialized))
.collect();
if has_drop {
self.initialized[local.0 as usize] = false;
}
}
}
fn checked_cleanup_plan(&mut self) -> crate::semantic::CheckedCleanupPlan {
let mut places = self
.locals
.iter()
.rev()
.filter_map(|local| {
self.initialized
.get(local.id.0 as usize)
.copied()
.unwrap_or(false)
.then(|| self.local_places[local.id.0 as usize])
})
.collect::<Vec<_>>();
places.extend(
self.initialized_places
.iter()
.rev()
.copied()
.filter(|place| {
let local = place_local_id(&self.places[place.0 as usize]);
!self.initialized[local.0 as usize]
}),
);
let mut drops = Vec::new();
for place in places {
self.collect_checked_drop_actions(place, &[], &mut drops);
}
crate::semantic::CheckedCleanupPlan { drops }
}
fn collect_checked_drop_actions(
&mut self,
place: PlaceId,
conditions: &[crate::semantic::CheckedEnumCondition],
drops: &mut Vec<crate::semantic::CheckedDropAction>,
) {
let local = place_local_id(&self.places[place.0 as usize]);
if self.moved[local.0 as usize]
|| self
.moved_places
.iter()
.any(|moved| self.place_contains(*moved, place))
{
return;
}
let type_ = self.places[place.0 as usize].type_.clone();
if self.is_copy_type(&type_) {
return;
}
if let SemanticType::Named(named) = &type_
&& named.path.module == crate::core_lib::BOX_MODULE_FILE_PATH
&& named.path.local == "Box"
&& let [crate::semantic::SemanticGenericArgument::Type(target)] =
named.generic_arguments.as_slice()
{
let pointer = self.child_place(
place,
PlaceProjection::Field("pointer".into()),
SemanticType::Pointer {
mutable: true,
target: Box::new(target.clone()),
},
);
let payload = self.child_place(pointer, PlaceProjection::Dereference, target.clone());
self.collect_checked_drop_actions(payload, conditions, drops);
if let Some(function) = self.drop_function_for(&type_) {
drops.push(crate::semantic::CheckedDropAction {
place,
function,
conditions: conditions.to_vec(),
});
}
return;
}
if let Some(function) = self.drop_function_for(&type_) {
drops.push(crate::semantic::CheckedDropAction {
place,
function,
conditions: conditions.to_vec(),
});
}
match type_ {
SemanticType::Named(named) if named.generic_arguments.is_empty() => {
let Some(metadata) = self
.type_metadata
.and_then(|registry| registry.get_named(&named))
.cloned()
else {
return;
};
if metadata.origin == TypeOrigin::Rust {
return;
}
match metadata.kind {
TypeMetadataKind::Structure { fields } => {
for field in fields.into_iter().rev() {
let child = self.child_place(
place,
PlaceProjection::Field(field.name),
field.type_.clone(),
);
self.collect_checked_drop_actions(child, conditions, drops);
}
}
TypeMetadataKind::Enum {
tag_bits, variants, ..
} => {
let explicit_tags = variants
.iter()
.flat_map(|variant| variant.matching_tags.iter().copied())
.collect::<Vec<_>>();
for variant in variants.into_iter().rev() {
let Some(payload_type) = variant.payload_type else {
continue;
};
let child = self.child_place(
place,
PlaceProjection::EnumPayload(variant.index),
payload_type,
);
let mut variant_conditions = conditions.to_vec();
variant_conditions.push(crate::semantic::CheckedEnumCondition {
enum_place: place,
tag_bits,
matching_tags: variant.matching_tags,
fallback: variant.fallback,
explicit_tags: explicit_tags.clone(),
});
self.collect_checked_drop_actions(child, &variant_conditions, drops);
}
}
_ => {}
}
}
SemanticType::Tuple(items) => {
for (index, item) in items.into_iter().enumerate().rev() {
let child = self.child_place(place, PlaceProjection::TupleField(index), item);
self.collect_checked_drop_actions(child, conditions, drops);
}
}
SemanticType::Array {
item,
size: Some(size),
} => {
for index in (0..size).rev() {
let child = self.child_place(
place,
PlaceProjection::ConstantIndex(index),
item.as_ref().clone(),
);
self.collect_checked_drop_actions(child, conditions, drops);
}
}
_ => {}
}
}
fn collect_return_drop_actions(
&self,
type_: &SemanticType,
path: &mut Vec<crate::semantic::ReturnPlaceProjection>,
conditions: &mut Vec<crate::semantic::ReturnEnumCondition>,
drops: &mut Vec<crate::semantic::ReturnDropAction>,
) {
if self.is_copy_type(type_) {
return;
}
if let SemanticType::Named(named) = type_
&& named.path.module == crate::core_lib::BOX_MODULE_FILE_PATH
&& named.path.local == "Box"
&& let [crate::semantic::SemanticGenericArgument::Type(payload)] =
named.generic_arguments.as_slice()
{
path.push(crate::semantic::ReturnPlaceProjection::Field(
"pointer".into(),
));
path.push(crate::semantic::ReturnPlaceProjection::Dereference);
self.collect_return_drop_actions(payload, path, conditions, drops);
path.pop();
path.pop();
if let Some(function) = self.drop_function_for(type_) {
drops.push(crate::semantic::ReturnDropAction {
path: path.clone(),
type_: type_.clone(),
function,
conditions: conditions.clone(),
});
}
return;
}
if let Some(function) = self.drop_function_for(type_) {
drops.push(crate::semantic::ReturnDropAction {
path: path.clone(),
type_: type_.clone(),
function,
conditions: conditions.clone(),
});
}
match type_ {
SemanticType::Named(named) => {
let Some(metadata) = self
.type_metadata
.and_then(|registry| registry.get_named(named))
else {
return;
};
if metadata.origin == TypeOrigin::Rust {
return;
}
match &metadata.kind {
TypeMetadataKind::Structure { fields } => {
for field in fields.iter().rev() {
path.push(crate::semantic::ReturnPlaceProjection::Field(
field.name.clone(),
));
self.collect_return_drop_actions(&field.type_, path, conditions, drops);
path.pop();
}
}
TypeMetadataKind::Enum {
tag_bits, variants, ..
} => {
let explicit_tags = variants
.iter()
.flat_map(|variant| variant.matching_tags.iter().copied())
.collect::<Vec<_>>();
for variant in variants.iter().rev() {
let Some(payload_type) = &variant.payload_type else {
continue;
};
conditions.push(crate::semantic::ReturnEnumCondition {
enum_path: path.clone(),
enum_type: type_.clone(),
tag_bits: *tag_bits,
matching_tags: variant.matching_tags.clone(),
fallback: variant.fallback,
explicit_tags: explicit_tags.clone(),
});
path.push(crate::semantic::ReturnPlaceProjection::EnumPayload(
variant.index,
));
self.collect_return_drop_actions(payload_type, path, conditions, drops);
path.pop();
conditions.pop();
}
}
_ => {}
}
}
SemanticType::Tuple(items) => {
for (index, item) in items.iter().enumerate().rev() {
path.push(crate::semantic::ReturnPlaceProjection::TupleField(index));
self.collect_return_drop_actions(item, path, conditions, drops);
path.pop();
}
}
SemanticType::Array {
item,
size: Some(size),
} => {
for index in (0..*size).rev() {
path.push(crate::semantic::ReturnPlaceProjection::ConstantIndex(index));
self.collect_return_drop_actions(item, path, conditions, drops);
path.pop();
}
}
_ => {}
}
}
fn emit_live_drops(&mut self, span: Span) {
let mut places = self
.locals
.iter()
.rev()
.filter_map(|local| {
self.initialized
.get(local.id.0 as usize)
.copied()
.unwrap_or(false)
.then(|| self.local_places[local.id.0 as usize])
})
.collect::<Vec<_>>();
places.extend(
self.initialized_places
.iter()
.rev()
.copied()
.filter(|place| {
let local = place_local_id(&self.places[place.0 as usize]);
!self.initialized[local.0 as usize]
}),
);
for place in places {
let local = place_local_id(&self.places[place.0 as usize]);
self.release_holder_loans(local);
self.emit_drop(place, span);
self.initialized_places = self
.initialized_places
.iter()
.copied()
.filter(|initialized| !self.place_contains(place, *initialized))
.collect();
if self
.drop_function_for(&self.places[place.0 as usize].type_)
.is_some()
{
self.initialized[local.0 as usize] = false;
}
}
}
fn emit_drop(&mut self, place: PlaceId, span: Span) {
let mut actions = Vec::new();
self.collect_checked_drop_actions(place, &[], &mut actions);
for action in actions {
self.emit_instruction(TypedInstruction {
span,
result: None,
kind: TypedInstructionKind::Drop {
place: action.place,
function: action.function,
conditions: action.conditions,
},
});
}
}
fn child_place(
&mut self,
parent: PlaceId,
projection: PlaceProjection,
type_: SemanticType,
) -> PlaceId {
let parent = self.places[parent.0 as usize].clone();
let id = PlaceId(self.places.len() as u32);
let mut projections = parent.projections;
projections.push(projection);
self.places.push(TypedPlace {
id,
base: parent.base,
projections,
type_,
mutable: parent.mutable,
});
id
}
fn drop_function_for(&self, type_: &SemanticType) -> Option<crate::semantic::GlobalFunctionId> {
let SemanticType::Named(named) = type_ else {
return None;
};
let environment = ExtensionEnvironment::build(self.graph, self.module).ok()?;
let table = MethodTable::build_named(self.graph, named, &environment).ok()?;
for implementation in &table.trait_implementations {
let origin = match &implementation.source {
MethodSource::Inherent => named.path.module.as_str(),
MethodSource::Extension { origin_module, .. } => origin_module.as_str(),
};
let resolved = self
.graph
.resolve(origin, &implementation.trait_path)
.ok()?;
if resolved.module_path != crate::core_lib::DROP_MODULE_FILE_PATH
|| resolved.local_path != "Drop"
{
continue;
}
let relative = format!("{}.drop", implementation.trait_path);
let candidate = table
.candidates("drop")
.iter()
.find(|candidate| candidate.relative_path == relative)?;
return self.functions.function_id(&candidate.declaration);
}
None
}
fn consume_value(&mut self, value: &TypedValue, span: Span) -> Result<(), BodyAnalysisError> {
if self.is_copy_type(&value.type_) {
return Ok(());
}
if let Some(place) = value.storage_place {
let local = place_local_id(&self.places[place.0 as usize]);
if matches!(value.type_, SemanticType::Reference { .. }) {
self.release_holder_loans(local);
} else {
self.ensure_not_borrowed(place, span)?;
}
if self.places[place.0 as usize].projections.is_empty() {
self.initialized[local.0 as usize] = false;
self.initialized_places.retain(|initialized| {
place_local_id(&self.places[initialized.0 as usize]) != local
});
self.moved[local.0 as usize] = true;
self.moved_places
.retain(|moved| place_local_id(&self.places[moved.0 as usize]) != local);
} else {
let root_place = self.local_places[local.0 as usize];
let root_type = self.places[root_place.0 as usize].type_.clone();
if self.drop_function_for(&root_type).is_some() {
return Err(BodyAnalysisError::PartialMoveOfDropType {
type_: root_type,
span,
});
}
self.initialized_places = self
.initialized_places
.iter()
.copied()
.filter(|initialized| !self.place_contains(place, *initialized))
.collect();
if !self
.moved_places
.iter()
.any(|moved| self.same_place(*moved, place))
{
self.moved_places.push(place);
}
}
}
Ok(())
}
fn is_copy_type(&self, type_: &SemanticType) -> bool {
match type_ {
SemanticType::Void | SemanticType::Pointer { .. } | SemanticType::Function(_) => true,
SemanticType::Reference { mutable, .. } => !mutable,
SemanticType::Named(named) if named.generic_arguments.is_empty() => {
self.named_type_implements_copy(&named.path)
}
SemanticType::Named(_) => false,
SemanticType::Array {
item,
size: Some(_),
} => self.is_copy_type(item),
SemanticType::Array { size: None, .. } => false,
SemanticType::Tuple(items) => items.iter().all(|item| self.is_copy_type(item)),
SemanticType::SelfType
| SemanticType::Parameter(_)
| SemanticType::Associated { .. } => false,
}
}
fn named_type_implements_copy(&self, target: &CanonicalSymbolPath) -> bool {
let Ok(environment) = ExtensionEnvironment::build(self.graph, self.module) else {
return false;
};
let Ok(table) = MethodTable::build(self.graph, target, &environment) else {
return false;
};
table.trait_implementations.iter().any(|implementation| {
let origin = match &implementation.source {
MethodSource::Inherent => target.module.as_str(),
MethodSource::Extension { origin_module, .. } => origin_module.as_str(),
};
self.graph
.resolve(origin, &implementation.trait_path)
.is_ok_and(|resolved| {
resolved.module_path == crate::core_lib::CLONE_MODULE_FILE_PATH
&& resolved.local_path == "Copy"
})
})
}
fn suspend_holder_loans(&mut self, holder: LocalId, suspended_by: LocalId) {
let mut loans = Vec::new();
self.active_loans.retain(|loan| {
if loan.holder == holder {
loans.push(loan.clone());
false
} else {
true
}
});
if !loans.is_empty() {
self.suspended_loans.push(SuspendedLoanSet {
holder,
suspended_by,
loans,
});
}
}
fn release_holder_loans(&mut self, holder: LocalId) {
self.active_loans.retain(|loan| loan.holder != holder);
let mut restored = Vec::new();
self.suspended_loans.retain(|suspended| {
if suspended.suspended_by == holder {
restored.extend(suspended.loans.clone());
false
} else {
true
}
});
self.active_loans.extend(restored);
}
fn reference_loan_targets(&self, value: &TypedValue) -> Vec<(PlaceId, bool)> {
let SemanticType::Reference { mutable, .. } = value.type_ else {
return Vec::new();
};
let mut borrowed = value
.borrow_origins
.iter()
.map(|origin| (*origin, mutable))
.collect::<Vec<_>>();
borrowed.sort_by_key(|(place, _)| place.0);
borrowed.dedup();
borrowed
}
fn ensure_not_borrowed(&self, place: PlaceId, span: Span) -> Result<(), BodyAnalysisError> {
if let Some(loan) = self
.active_loans
.iter()
.find(|loan| self.places_overlap(place, loan.place))
{
return Err(BodyAnalysisError::BorrowedPlaceMutation {
place,
borrowed: loan.place,
span,
});
}
Ok(())
}
fn ensure_loan_compatible(
&self,
place: PlaceId,
mutable: bool,
span: Span,
) -> Result<(), BodyAnalysisError> {
if let Some(loan) = self
.active_loans
.iter()
.find(|loan| (mutable || loan.mutable) && self.places_overlap(place, loan.place))
{
return Err(BodyAnalysisError::ConflictingBorrows {
first: loan.place,
second: place,
span,
});
}
Ok(())
}
fn ensure_reference_does_not_escape(
&self,
value: &TypedValue,
span: Span,
) -> Result<(), BodyAnalysisError> {
let SemanticType::Reference { .. } = value.type_ else {
return Ok(());
};
let SemanticType::Reference {
lifetime: expected, ..
} = self.signature.return_type.as_ref()
else {
return Ok(());
};
for (borrowed, _) in self.reference_loan_targets(value) {
let borrowed_local = place_local_id(&self.places[borrowed.0 as usize]);
let borrowed_local = &self.locals[borrowed_local.0 as usize];
if !borrowed_local.parameter {
return Err(BodyAnalysisError::EscapingLocalBorrow {
place: borrowed,
span,
});
}
let SemanticType::Reference {
lifetime: actual, ..
} = &borrowed_local.type_
else {
return Err(BodyAnalysisError::EscapingLocalBorrow {
place: borrowed,
span,
});
};
if expected != actual {
return Err(BodyAnalysisError::ReturnLifetimeMismatch {
expected: expected.clone(),
actual: actual.clone(),
span,
});
}
}
Ok(())
}
fn validate_call_borrows(
&self,
values: &[TypedValue],
span: Span,
) -> Result<(), BodyAnalysisError> {
let borrows = values
.iter()
.flat_map(|value| {
let SemanticType::Reference { mutable, .. } = &value.type_ else {
return Vec::new();
};
value
.borrow_origins
.iter()
.map(|origin| (*origin, *mutable))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
for (index, (first, first_mutable)) in borrows.iter().enumerate() {
for (second, second_mutable) in &borrows[index + 1..] {
if (*first_mutable || *second_mutable) && self.places_overlap(*first, *second) {
return Err(BodyAnalysisError::ConflictingBorrows {
first: *first,
second: *second,
span,
});
}
}
}
Ok(())
}
fn places_overlap(&self, first: PlaceId, second: PlaceId) -> bool {
let first = &self.places[first.0 as usize];
let second = &self.places[second.0 as usize];
if first.base != second.base {
return false;
}
for (left, right) in first.projections.iter().zip(&second.projections) {
match (left, right) {
(PlaceProjection::Field(left), PlaceProjection::Field(right)) if left != right => {
return false;
}
(PlaceProjection::TupleField(left), PlaceProjection::TupleField(right))
if left != right =>
{
return false;
}
(PlaceProjection::ConstantIndex(left), PlaceProjection::ConstantIndex(right))
if left != right =>
{
return false;
}
_ => {}
}
}
true
}
fn ensure_branch_place_states_match(
&self,
then_roots: &[bool],
else_roots: &[bool],
then_initialized: &[PlaceId],
else_initialized: &[PlaceId],
then_moved: &[PlaceId],
else_moved: &[PlaceId],
outer_locals: usize,
span: Span,
) -> Result<(), BodyAnalysisError> {
if let Some(index) = (0..outer_locals).find(|index| {
then_roots.get(*index).copied().unwrap_or(false)
!= else_roots.get(*index).copied().unwrap_or(false)
}) {
return Err(BodyAnalysisError::InconsistentPlaceStateAcrossBranches {
name: self.locals[index].name.clone(),
span,
});
}
for (left, right) in [
(then_initialized, else_initialized),
(then_moved, else_moved),
] {
let differs = left
.iter()
.copied()
.filter(|place| {
(place_local_id(&self.places[place.0 as usize]).0 as usize) < outer_locals
})
.find(|place| !right.iter().any(|other| self.same_place(*place, *other)))
.or_else(|| {
right
.iter()
.copied()
.filter(|place| {
(place_local_id(&self.places[place.0 as usize]).0 as usize)
< outer_locals
})
.find(|place| !left.iter().any(|other| self.same_place(*place, *other)))
});
if let Some(place) = differs {
let local = place_local_id(&self.places[place.0 as usize]);
return Err(BodyAnalysisError::InconsistentPlaceStateAcrossBranches {
name: self.locals[local.0 as usize].name.clone(),
span,
});
}
}
Ok(())
}
fn same_place(&self, first: PlaceId, second: PlaceId) -> bool {
let first = &self.places[first.0 as usize];
let second = &self.places[second.0 as usize];
first.base == second.base && first.projections == second.projections
}
fn place_contains(&self, ancestor: PlaceId, descendant: PlaceId) -> bool {
let ancestor = &self.places[ancestor.0 as usize];
let descendant = &self.places[descendant.0 as usize];
ancestor.base == descendant.base
&& descendant.projections.starts_with(&ancestor.projections)
}
fn place_has_live_contents(&self, place: PlaceId) -> bool {
let local = place_local_id(&self.places[place.0 as usize]);
(self.initialized[local.0 as usize]
|| self
.initialized_places
.iter()
.any(|initialized| self.same_place(*initialized, place)))
&& !self
.moved_places
.iter()
.any(|moved| self.place_contains(*moved, place))
}
fn mark_place_initialized(&mut self, place: PlaceId) {
if !self
.initialized_places
.iter()
.any(|initialized| self.same_place(*initialized, place))
{
self.initialized_places.push(place);
}
let local = place_local_id(&self.places[place.0 as usize]);
self.moved[local.0 as usize] = false;
let leaf = self.places[place.0 as usize].clone();
for parent_depth in (0..leaf.projections.len()).rev() {
let parent = self.places.iter().find(|candidate| {
candidate.base == leaf.base
&& candidate.projections == leaf.projections[..parent_depth]
});
let Some(parent) = parent else {
continue;
};
let Some(required) = self.direct_initialization_projections(&parent.type_) else {
continue;
};
let parent_prefix = parent.projections.clone();
let complete = required.iter().all(|projection| {
self.initialized_places.iter().any(|initialized| {
let initialized = &self.places[initialized.0 as usize];
initialized.base == leaf.base
&& initialized.projections.len() == parent_prefix.len() + 1
&& initialized.projections.starts_with(&parent_prefix)
&& initialized.projections.last() == Some(projection)
})
});
if !complete {
continue;
}
self.initialized_places = self
.initialized_places
.iter()
.copied()
.filter(|initialized| {
let initialized = &self.places[initialized.0 as usize];
initialized.base != leaf.base
|| !initialized.projections.starts_with(&parent_prefix)
|| initialized.projections.len() <= parent_prefix.len()
})
.collect();
if parent_depth == 0 {
self.initialized[local.0 as usize] = true;
} else if !self.initialized_places.iter().any(|initialized| {
let initialized = &self.places[initialized.0 as usize];
initialized.base == leaf.base && initialized.projections == parent_prefix
}) {
self.initialized_places.push(parent.id);
}
}
}
fn direct_initialization_projections(
&self,
type_: &SemanticType,
) -> Option<Vec<PlaceProjection>> {
match type_ {
SemanticType::Named(named) => {
let metadata = self.type_metadata?.get_named(named)?;
let TypeMetadataKind::Structure { fields } = &metadata.kind else {
return None;
};
Some(
fields
.iter()
.map(|field| PlaceProjection::Field(field.name.clone()))
.collect(),
)
}
SemanticType::Tuple(items) => {
Some((0..items.len()).map(PlaceProjection::TupleField).collect())
}
SemanticType::Array {
size: Some(size), ..
} => Some((0..*size).map(PlaceProjection::ConstantIndex).collect()),
_ => None,
}
}
fn require_projection_storage(
&self,
place: PlaceId,
span: Span,
) -> Result<(), BodyAnalysisError> {
let local = place_local_id(&self.places[place.0 as usize]);
if !self.initialized[local.0 as usize] {
let projections = &self.places[place.0 as usize].projections;
if !projections.is_empty()
&& projections.iter().all(|projection| {
matches!(
projection,
PlaceProjection::Field(_)
| PlaceProjection::TupleField(_)
| PlaceProjection::ConstantIndex(_)
)
})
{
return Ok(());
}
return self.require_initialized(place, span);
}
if let Some(moved) = self
.moved_places
.iter()
.find(|moved| self.place_contains(**moved, place) && !self.same_place(**moved, place))
{
return Err(BodyAnalysisError::PartiallyMovedValue {
name: self.locals[place_local_id(&self.places[moved.0 as usize]).0 as usize]
.name
.clone(),
span,
});
}
Ok(())
}
fn require_initialized(&self, place: PlaceId, span: Span) -> Result<(), BodyAnalysisError> {
let typed_place = &self.places[place.0 as usize];
let local = place_local_id(typed_place);
if self
.suspended_loans
.iter()
.any(|suspended| suspended.holder == local)
{
return Err(BodyAnalysisError::SuspendedReferenceUse {
name: self.locals[local.0 as usize].name.clone(),
span,
});
}
if self.initialized[local.0 as usize]
|| self
.initialized_places
.iter()
.any(|initialized| self.same_place(*initialized, place))
{
if self
.moved_places
.iter()
.any(|moved| self.place_contains(*moved, place))
{
return Err(BodyAnalysisError::UseAfterMove {
name: self.locals[local.0 as usize].name.clone(),
span,
});
}
if self
.moved_places
.iter()
.any(|moved| self.place_contains(place, *moved))
{
return Err(BodyAnalysisError::PartiallyMovedValue {
name: self.locals[local.0 as usize].name.clone(),
span,
});
}
Ok(())
} else if self.moved[local.0 as usize] {
Err(BodyAnalysisError::UseAfterMove {
name: self.locals[local.0 as usize].name.clone(),
span,
})
} else {
Err(BodyAnalysisError::UninitializedLocal {
name: self.locals[local.0 as usize].name.clone(),
span,
})
}
}
fn resolve_local(&self, name: &str) -> Option<LocalId> {
self.local_scopes
.iter()
.rev()
.find_map(|scope| scope.get(name).copied())
}
fn add_local(
&mut self,
name: String,
type_: SemanticType,
mutable: bool,
parameter: bool,
initialized: bool,
span: Span,
) -> Result<PlaceId, BodyAnalysisError> {
if self.is_copy_type(&type_) && self.drop_function_for(&type_).is_some() {
return Err(BodyAnalysisError::CopyTypeHasDrop { type_, span });
}
let scope = self
.local_scopes
.last_mut()
.expect("BodyAnalyzer must always have a lexical scope");
if scope.contains_key(&name) {
return Err(BodyAnalysisError::DuplicateLocal { name, span });
}
let id = LocalId(self.locals.len() as u32);
scope.insert(name.clone(), id);
self.locals.push(TypedLocal {
id,
name,
type_: type_.clone(),
mutable,
parameter,
});
self.initialized.push(initialized);
self.moved.push(false);
let place = PlaceId(self.places.len() as u32);
self.local_places.push(place);
self.places.push(TypedPlace {
id: place,
base: PlaceBase::Local(id),
projections: Vec::new(),
type_,
mutable,
});
Ok(place)
}
fn current_draft(&self) -> &BasicBlockDraft {
&self.blocks[self.current_block.0 as usize]
}
fn current_draft_mut(&mut self) -> &mut BasicBlockDraft {
&mut self.blocks[self.current_block.0 as usize]
}
fn current_terminated(&self) -> bool {
self.current_draft().terminator.is_some()
}
fn emit_instruction(&mut self, instruction: TypedInstruction) {
debug_assert!(!self.current_terminated());
self.current_draft_mut().instructions.push(instruction);
}
fn terminate(&mut self, terminator: TypedTerminator) {
debug_assert!(!self.current_terminated());
self.current_draft_mut().terminator = Some(terminator);
}
fn create_block(&mut self) -> BasicBlockId {
let id = BasicBlockId(self.blocks.len() as u32);
self.blocks.push(BasicBlockDraft::default());
id
}
fn switch_to(&mut self, block: BasicBlockId) {
self.current_block = block;
}
fn detached_value(&mut self, type_: SemanticType) -> TypedValue {
let value = TypedValue {
id: IrValueId(self.next_value),
type_,
storage_place: None,
borrow_origins: Vec::new(),
};
self.next_value += 1;
value
}
fn emit_value(
&mut self,
span: Span,
type_: SemanticType,
kind: TypedInstructionKind,
) -> TypedValue {
let storage_place = match &kind {
TypedInstructionKind::Load(place) => Some(*place),
_ => None,
};
let borrow_origins = match &kind {
TypedInstructionKind::Borrow { place, .. } => vec![*place],
TypedInstructionKind::Load(place)
if matches!(type_, SemanticType::Reference { .. }) =>
{
let holder = place_local_id(&self.places[place.0 as usize]);
let origins = self
.active_loans
.iter()
.filter(|loan| loan.holder == holder)
.map(|loan| loan.place)
.collect::<Vec<_>>();
if origins.is_empty() {
vec![*place]
} else {
origins
}
}
_ => Vec::new(),
};
let value = TypedValue {
id: IrValueId(self.next_value),
type_,
storage_place,
borrow_origins,
};
self.next_value += 1;
self.emit_instruction(TypedInstruction {
span,
result: Some(value.clone()),
kind,
});
value
}
fn primitive(&self, name: &str, span: Span) -> Result<SemanticType, BodyAnalysisError> {
let resolved = self
.graph
.resolve(self.module, name)
.map_err(|error| BodyAnalysisError::Resolution { span, error })?;
Ok(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
},
generic_arguments: Vec::new(),
}))
}
fn require_type(
&self,
expected: &SemanticType,
actual: &SemanticType,
span: Span,
) -> Result<(), BodyAnalysisError> {
if expected == actual {
Ok(())
} else {
Err(BodyAnalysisError::TypeMismatch {
expected: expected.clone(),
actual: actual.clone(),
span,
})
}
}
fn string(&self, id: u32, span: Span) -> Result<&str, BodyAnalysisError> {
self.file
.data
.strings
.get(id as usize)
.map(String::as_str)
.ok_or(BodyAnalysisError::InvalidStringId { id, span })
}
}
fn place_local_id(place: &TypedPlace) -> LocalId {
match place.base {
PlaceBase::Local(local) => local,
}
}
fn reference_return_origins<'a>(
return_type: &SemanticType,
parameter_types: impl Iterator<Item = &'a SemanticType>,
argument_values: &[TypedValue],
) -> Vec<PlaceId> {
let SemanticType::Reference {
lifetime: return_lifetime,
..
} = return_type
else {
return Vec::new();
};
let mut origins = parameter_types
.zip(argument_values)
.filter_map(|(parameter, value)| {
let SemanticType::Reference {
lifetime: parameter_lifetime,
..
} = parameter
else {
return None;
};
(parameter_lifetime == return_lifetime).then_some(value.borrow_origins.iter().copied())
})
.flatten()
.collect::<Vec<_>>();
origins.sort_by_key(|place| place.0);
origins.dedup();
origins
}
fn infer_type_substitutions(
pattern: &SemanticType,
concrete: &SemanticType,
substitutions: &mut BTreeMap<crate::semantic::GenericParameterId, SemanticType>,
) {
match (pattern, concrete) {
(SemanticType::Parameter(parameter), concrete) => {
substitutions
.entry(parameter.id)
.or_insert_with(|| concrete.clone());
}
(SemanticType::Named(pattern), SemanticType::Named(concrete))
if pattern.path == concrete.path
&& pattern.generic_arguments.len() == concrete.generic_arguments.len() =>
{
for (pattern, concrete) in pattern
.generic_arguments
.iter()
.zip(&concrete.generic_arguments)
{
if let (
crate::semantic::SemanticGenericArgument::Type(pattern),
crate::semantic::SemanticGenericArgument::Type(concrete),
) = (pattern, concrete)
{
infer_type_substitutions(pattern, concrete, substitutions);
}
}
}
(
SemanticType::Reference {
target: pattern, ..
},
SemanticType::Reference {
target: concrete, ..
},
)
| (
SemanticType::Pointer {
target: pattern, ..
},
SemanticType::Pointer {
target: concrete, ..
},
)
| (SemanticType::Array { item: pattern, .. }, SemanticType::Array { item: concrete, .. }) =>
{
infer_type_substitutions(pattern, concrete, substitutions);
}
(SemanticType::Tuple(pattern), SemanticType::Tuple(concrete))
if pattern.len() == concrete.len() =>
{
for (pattern, concrete) in pattern.iter().zip(concrete) {
infer_type_substitutions(pattern, concrete, substitutions);
}
}
_ => {}
}
}
fn substitute_visible_associated_types(type_: &SemanticType, table: &MethodTable) -> SemanticType {
match type_ {
SemanticType::Associated { name, .. } => {
let mut bindings = table
.trait_implementations
.iter()
.filter_map(|implementation| implementation.concrete_associated_types.get(name));
let Some(first) = bindings.next() else {
return type_.clone();
};
if bindings.all(|binding| binding == first) {
first.clone()
} else {
type_.clone()
}
}
SemanticType::Reference {
lifetime,
mutable,
target,
} => SemanticType::Reference {
lifetime: lifetime.clone(),
mutable: *mutable,
target: Box::new(substitute_visible_associated_types(target, table)),
},
SemanticType::Pointer { mutable, target } => SemanticType::Pointer {
mutable: *mutable,
target: Box::new(substitute_visible_associated_types(target, table)),
},
SemanticType::Array { item, size } => SemanticType::Array {
item: Box::new(substitute_visible_associated_types(item, table)),
size: *size,
},
SemanticType::Tuple(items) => SemanticType::Tuple(
items
.iter()
.map(|item| substitute_visible_associated_types(item, table))
.collect(),
),
SemanticType::Named(named) => SemanticType::Named(SemanticNamedType {
path: named.path.clone(),
generic_arguments: named
.generic_arguments
.iter()
.map(|argument| match argument {
crate::semantic::SemanticGenericArgument::Type(type_) => {
crate::semantic::SemanticGenericArgument::Type(
substitute_visible_associated_types(type_, table),
)
}
crate::semantic::SemanticGenericArgument::Lifetime(lifetime) => {
crate::semantic::SemanticGenericArgument::Lifetime(lifetime.clone())
}
})
.collect(),
}),
_ => type_.clone(),
}
}
fn substitute_self(type_: &SemanticType, receiver: &SemanticType) -> SemanticType {
match type_ {
SemanticType::SelfType => receiver.clone(),
SemanticType::Array { item, size } => SemanticType::Array {
item: Box::new(substitute_self(item, receiver)),
size: *size,
},
SemanticType::Tuple(items) => SemanticType::Tuple(
items
.iter()
.map(|item| substitute_self(item, receiver))
.collect(),
),
SemanticType::Function(function) => {
SemanticType::Function(Box::new(SemanticFunctionType {
receiver: function.receiver.clone(),
arguments: function
.arguments
.iter()
.map(|argument| crate::semantic::SemanticFunctionArgument {
name: argument.name.clone(),
mutable: argument.mutable,
type_: substitute_self(&argument.type_, receiver),
})
.collect(),
return_type: Box::new(substitute_self(&function.return_type, receiver)),
}))
}
SemanticType::Reference {
lifetime,
mutable,
target,
} => SemanticType::Reference {
lifetime: lifetime.clone(),
mutable: *mutable,
target: Box::new(substitute_self(target, receiver)),
},
SemanticType::Pointer { mutable, target } => SemanticType::Pointer {
mutable: *mutable,
target: Box::new(substitute_self(target, receiver)),
},
SemanticType::Named(named) => SemanticType::Named(SemanticNamedType {
path: named.path.clone(),
generic_arguments: named
.generic_arguments
.iter()
.map(|argument| match argument {
crate::semantic::SemanticGenericArgument::Type(type_) => {
crate::semantic::SemanticGenericArgument::Type(substitute_self(
type_, receiver,
))
}
crate::semantic::SemanticGenericArgument::Lifetime(lifetime) => {
crate::semantic::SemanticGenericArgument::Lifetime(lifetime.clone())
}
})
.collect(),
}),
other => other.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
core_lib,
parsing::{SourceFile, parse_file},
runtime::TypeMetadataRegistry,
semantic::DeclarationIndex,
};
fn insert(
graph: &mut ModuleGraph,
files: &mut BTreeMap<String, ParsedFile>,
path: &str,
source: &str,
) {
let file = parse_file(SourceFile { path, text: source }).unwrap();
graph
.insert(path, DeclarationIndex::collect(&file).unwrap())
.unwrap();
files.insert(path.to_owned(), file);
}
#[test]
fn lowers_mutable_local_assignment_and_return_to_typed_ir() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://main.lt",
"let mut value: i32 = 1 value = 2 value += 40 return value",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let i32_type = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
});
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(i32_type.clone()),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(body.locals.len(), 1);
assert!(body.locals[0].mutable);
assert_eq!(body.locals[0].type_, i32_type);
let add = registry
.function_id(&CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32.Add.add".into(),
})
.unwrap();
assert!(
body.entry_block()
.instructions
.iter()
.any(|instruction| matches!(
instruction.kind,
TypedInstructionKind::Call { function, .. } if function == add
))
);
assert!(matches!(
body.entry_block().terminator,
TypedTerminator::Return(Some(_))
));
}
#[test]
fn accepts_a_diverging_loop_without_a_return() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("app://main.lt", "loop {}"),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(body.blocks.len(), 2);
assert!(matches!(
body.entry_block().terminator,
TypedTerminator::Jump {
target: BasicBlockId(1),
..
}
));
assert!(matches!(
body.block(BasicBlockId(1)).unwrap().terminator,
TypedTerminator::Jump {
target: BasicBlockId(1),
..
}
));
}
#[test]
fn lowers_while_to_condition_body_and_exit_blocks() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://main.lt",
"let mut value: i32 = 0 while false { value += 1 } return value",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(body.blocks.len(), 4);
assert!(matches!(
body.entry_block().terminator,
TypedTerminator::Jump {
target: BasicBlockId(1),
..
}
));
assert!(matches!(
body.block(BasicBlockId(1)).unwrap().terminator,
TypedTerminator::Branch {
then_block: BasicBlockId(2),
else_block: BasicBlockId(3),
..
}
));
assert!(matches!(
body.block(BasicBlockId(2)).unwrap().terminator,
TypedTerminator::Jump {
target: BasicBlockId(1),
..
}
));
assert!(matches!(
body.block(BasicBlockId(3)).unwrap().terminator,
TypedTerminator::Return(Some(_))
));
}
#[test]
fn lowers_value_if_through_a_merge_block_parameter() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("app://main.lt", "return if true { 1 } else { 2 }"),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
let merge = body.block(BasicBlockId(3)).unwrap();
assert_eq!(merge.parameters.len(), 1);
let parameter = merge.parameters[0].id;
for branch in [BasicBlockId(1), BasicBlockId(2)] {
assert!(matches!(
&body.block(branch).unwrap().terminator,
TypedTerminator::Jump { target, arguments }
if *target == BasicBlockId(3) && arguments.len() == 1
));
}
assert!(matches!(
merge.terminator,
TypedTerminator::Return(Some(value)) if value == parameter
));
}
#[test]
fn lowers_statement_if_to_branch_and_merge_blocks() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://main.lt",
"if true { let branch_value: i32 = 1 } return 2",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(body.blocks.len(), 4);
assert!(matches!(
body.entry_block().terminator,
TypedTerminator::Branch {
then_block: BasicBlockId(1),
else_block: BasicBlockId(2),
..
}
));
assert!(matches!(
body.block(BasicBlockId(1)).unwrap().terminator,
TypedTerminator::Jump {
target: BasicBlockId(3),
..
}
));
assert!(matches!(
body.block(BasicBlockId(2)).unwrap().terminator,
TypedTerminator::Jump {
target: BasicBlockId(3),
..
}
));
assert!(matches!(
body.block(BasicBlockId(3)).unwrap().terminator,
TypedTerminator::Return(Some(_))
));
}
#[test]
fn reports_missing_returns_and_statements_after_a_terminator() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("app://missing.lt", "1"),
("app://unreachable.lt", "return 1 2"),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let missing = files.get("app://missing.lt").unwrap();
let missing_errors =
BodyAnalyzer::new(&graph, ®istry, missing, "app://missing.lt", &signature)
.unwrap()
.analyze(&missing.ast.contract_definition_content.statements)
.unwrap_err();
assert!(
missing_errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::MissingReturn { .. }))
);
let unreachable = files.get("app://unreachable.lt").unwrap();
let unreachable_errors = BodyAnalyzer::new(
&graph,
®istry,
unreachable,
"app://unreachable.lt",
&signature,
)
.unwrap()
.analyze(&unreachable.ast.contract_definition_content.statements)
.unwrap_err();
assert!(
unreachable_errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::UnreachableStatement { .. }))
);
}
#[test]
fn nested_blocks_allow_shadowing_and_restore_the_outer_binding() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://main.lt",
"let mut value: i32 = 1 { let value: i32 = 2 } value = 3 return value",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(body.locals.len(), 2);
assert_eq!(body.locals[0].name, "value");
assert_eq!(body.locals[1].name, "value");
assert!(
body.entry_block()
.instructions
.iter()
.any(|instruction| matches!(
instruction.kind,
TypedInstructionKind::Store {
place: PlaceId(0),
..
}
))
);
}
#[test]
fn inserts_implicit_borrows_for_reference_operator_arguments() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://main.lt",
"let left: i32 = 1 let right: i32 = 2 return left == right",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let bool_type = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "bool".into(),
},
generic_arguments: Vec::new(),
});
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(bool_type),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
let equality = registry
.function_id(&CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32.PartialEq.eq".into(),
})
.unwrap();
assert_eq!(
body.entry_block()
.instructions
.iter()
.filter(|instruction| matches!(
instruction.kind,
TypedInstructionKind::Borrow { .. }
))
.count(),
2
);
assert!(
body.entry_block()
.instructions
.iter()
.any(|instruction| matches!(
&instruction.kind,
TypedInstructionKind::Call { function, arguments, .. }
if *function == equality && arguments.len() == 2
))
);
}
#[test]
fn drops_a_live_owned_local_at_lexical_scope_exit() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
("core://clone.lt", core_lib::CLONE_MODULE_FILE_CONTENT),
("core://drop.lt", core_lib::DROP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://drop_scope.lt",
"pub acs Packet: struct { impl Drop { acs drop: fn(&mut self) { } } } { let local: Packet = packet } return 0",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://drop_scope.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: vec![crate::semantic::SemanticFunctionArgument {
name: "packet".into(),
mutable: false,
type_: SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "app://drop_scope.lt".into(),
local: "Packet".into(),
},
generic_arguments: Vec::new(),
}),
}],
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://drop_scope.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(
body.blocks
.iter()
.flat_map(|block| &block.instructions)
.filter(|instruction| matches!(instruction.kind, TypedInstructionKind::Drop { .. }))
.count(),
1
);
}
#[test]
fn drops_an_unmoved_non_copy_enum_payload_binding_once() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
("core://clone.lt", core_lib::CLONE_MODULE_FILE_CONTENT),
("core://drop.lt", core_lib::DROP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://enum_drop.lt",
"pub acs Packet: struct { impl Drop { acs drop: fn(&mut self) { } } }
pub acs MaybePacket: enum { var Empty var Value Packet }
return match maybe {
MaybePacket.Empty => 0
MaybePacket.Value(packet) => 0
}",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let metadata = TypeMetadataRegistry::build(&graph, &files, &BTreeMap::new()).unwrap();
let file = files.get("app://enum_drop.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: vec![crate::semantic::SemanticFunctionArgument {
name: "maybe".into(),
mutable: false,
type_: SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "app://enum_drop.lt".into(),
local: "MaybePacket".into(),
},
generic_arguments: Vec::new(),
}),
}],
return_type: Box::new(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})),
};
let body = BodyAnalyzer::new_with_metadata(
&graph,
®istry,
&metadata,
file,
"app://enum_drop.lt",
&signature,
)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(
body.blocks
.iter()
.flat_map(|block| &block.instructions)
.filter(|instruction| matches!(instruction.kind, TypedInstructionKind::Drop { .. }))
.count(),
1
);
}
#[test]
fn does_not_drop_an_enum_payload_moved_out_of_its_match_arm() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
("core://clone.lt", core_lib::CLONE_MODULE_FILE_CONTENT),
("core://drop.lt", core_lib::DROP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
(
"app://enum_move.lt",
"pub acs Packet: struct { impl Drop { acs drop: fn(&mut self) { } } }
pub acs MaybePacket: enum { var Empty var Value Packet }
return match maybe {
MaybePacket.Empty => Packet {}
MaybePacket.Value(packet) => packet
}",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let metadata = TypeMetadataRegistry::build(&graph, &files, &BTreeMap::new()).unwrap();
let file = files.get("app://enum_move.lt").unwrap();
let packet = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "app://enum_move.lt".into(),
local: "Packet".into(),
},
generic_arguments: Vec::new(),
});
let signature = SemanticFunctionType {
receiver: None,
arguments: vec![crate::semantic::SemanticFunctionArgument {
name: "maybe".into(),
mutable: false,
type_: SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "app://enum_move.lt".into(),
local: "MaybePacket".into(),
},
generic_arguments: Vec::new(),
}),
}],
return_type: Box::new(packet),
};
let body = BodyAnalyzer::new_with_metadata(
&graph,
®istry,
&metadata,
file,
"app://enum_move.lt",
&signature,
)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
assert_eq!(
body.blocks
.iter()
.flat_map(|block| &block.instructions)
.filter(|instruction| matches!(instruction.kind, TypedInstructionKind::Drop { .. }))
.count(),
0
);
}
#[test]
fn copy_impl_is_active_only_through_an_imported_extension() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
("core://clone.lt", core_lib::CLONE_MODULE_FILE_CONTENT),
("core://drop.lt", core_lib::DROP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("lib://types.lt", "pub acs Packet: struct"),
(
"lib://copy.lt",
"acs types: \"lib://types.lt\" pub acs packet_copy: extension for types.Packet { impl Copy }",
),
(
"app://without.lt",
"acs types: \"lib://types.lt\" packet packet return 0",
),
(
"app://with.lt",
"acs types: \"lib://types.lt\" acs copy_module: \"lib://copy.lt\" acs packet_copy: copy_module.packet_copy packet packet return 0",
),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let packet_type = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "lib://types.lt".into(),
local: "Packet".into(),
},
generic_arguments: Vec::new(),
});
let i32_type = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
});
let signature = SemanticFunctionType {
receiver: None,
arguments: vec![crate::semantic::SemanticFunctionArgument {
name: "packet".into(),
mutable: false,
type_: packet_type,
}],
return_type: Box::new(i32_type),
};
let without = files.get("app://without.lt").unwrap();
let errors = BodyAnalyzer::new(&graph, ®istry, without, "app://without.lt", &signature)
.unwrap()
.analyze(&without.ast.contract_definition_content.statements)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::UseAfterMove { .. }))
);
let with = files.get("app://with.lt").unwrap();
BodyAnalyzer::new(&graph, ®istry, with, "app://with.lt", &signature)
.unwrap()
.analyze(&with.ast.contract_definition_content.statements)
.unwrap();
}
#[test]
fn nested_mutable_dereference_assignment_builds_a_mutable_place_chain() {
let nested = SemanticType::Reference {
lifetime: None,
mutable: true,
target: Box::new(SemanticType::Reference {
lifetime: None,
mutable: true,
target: Box::new(test_i32_type()),
}),
};
analyze_test_source_with_arguments(
"**value = 2 return **value",
vec![crate::semantic::SemanticFunctionArgument {
name: "value".into(),
mutable: false,
type_: nested,
}],
test_i32_type(),
)
.unwrap();
}
#[test]
fn parenthesized_dereference_can_continue_with_a_tuple_field_place() {
let tuple = SemanticType::Tuple(vec![test_i32_type(), test_i32_type()]);
analyze_test_source_with_arguments(
"(*value).0 = 2 return (*value).0",
vec![crate::semantic::SemanticFunctionArgument {
name: "value".into(),
mutable: false,
type_: SemanticType::Reference {
lifetime: None,
mutable: true,
target: Box::new(tuple),
},
}],
test_i32_type(),
)
.unwrap();
}
#[test]
fn nested_assignment_rejects_a_shared_reference_in_the_place_chain() {
let nested = SemanticType::Reference {
lifetime: None,
mutable: false,
target: Box::new(SemanticType::Reference {
lifetime: None,
mutable: true,
target: Box::new(test_i32_type()),
}),
};
let errors = analyze_test_source_with_arguments(
"**value = 2 return **value",
vec![crate::semantic::SemanticFunctionArgument {
name: "value".into(),
mutable: false,
type_: nested,
}],
test_i32_type(),
)
.unwrap_err();
assert!(errors.iter().any(|error| matches!(
error,
BodyAnalysisError::MutableBorrowOfImmutablePlace { .. }
)));
}
fn analyze_test_source(
source: &str,
return_type: SemanticType,
) -> Result<TypedBody, Vec<BodyAnalysisError>> {
analyze_test_source_with_arguments(source, Vec::new(), return_type)
}
fn analyze_test_source_with_arguments(
source: &str,
arguments: Vec<crate::semantic::SemanticFunctionArgument>,
return_type: SemanticType,
) -> Result<TypedBody, Vec<BodyAnalysisError>> {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("app://borrow.lt", source),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://borrow.lt").unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments,
return_type: Box::new(return_type),
};
BodyAnalyzer::new(&graph, ®istry, file, "app://borrow.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
}
fn test_i32_type() -> SemanticType {
SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
})
}
fn test_lifetime(name: &str, id: u32) -> crate::semantic::SemanticLifetime {
crate::semantic::SemanticLifetime::Parameter(crate::semantic::SemanticGenericParameter {
id: crate::semantic::GenericParameterId(id),
name: name.into(),
kind: crate::semantic::SemanticGenericParameterKind::Lifetime,
constraints: Vec::new(),
})
}
#[test]
fn reference_call_result_inherits_the_matching_argument_origin() {
let lifetime = Some(test_lifetime("a", 0));
let reference = SemanticType::Reference {
lifetime: lifetime.clone(),
mutable: false,
target: Box::new(test_i32_type()),
};
let argument = TypedValue {
id: IrValueId(0),
type_: reference.clone(),
storage_place: None,
borrow_origins: vec![PlaceId(7)],
};
assert_eq!(
reference_return_origins(
&reference,
std::iter::once(&reference),
std::slice::from_ref(&argument),
),
vec![PlaceId(7)]
);
}
#[test]
fn preserves_multiple_possible_reference_return_origins() {
let reference = SemanticType::Reference {
lifetime: Some(test_lifetime("a", 0)),
mutable: false,
target: Box::new(test_i32_type()),
};
let arguments = [
TypedValue {
id: IrValueId(0),
type_: reference.clone(),
storage_place: None,
borrow_origins: vec![PlaceId(1)],
},
TypedValue {
id: IrValueId(1),
type_: reference.clone(),
storage_place: None,
borrow_origins: vec![PlaceId(2)],
},
];
assert_eq!(
reference_return_origins(&reference, [&reference, &reference].into_iter(), &arguments,),
vec![PlaceId(1), PlaceId(2)]
);
}
#[test]
fn return_reference_must_match_the_source_parameter_lifetime() {
let i32_type = test_i32_type();
let lifetime_a = test_lifetime("a", 0);
let lifetime_b = test_lifetime("b", 1);
let argument = crate::semantic::SemanticFunctionArgument {
name: "input".into(),
mutable: false,
type_: SemanticType::Reference {
lifetime: Some(lifetime_a.clone()),
mutable: false,
target: Box::new(i32_type.clone()),
},
};
analyze_test_source_with_arguments(
"return input",
vec![argument.clone()],
SemanticType::Reference {
lifetime: Some(lifetime_a),
mutable: false,
target: Box::new(i32_type.clone()),
},
)
.unwrap();
let errors = analyze_test_source_with_arguments(
"return input",
vec![argument],
SemanticType::Reference {
lifetime: Some(lifetime_b),
mutable: false,
target: Box::new(i32_type),
},
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::ReturnLifetimeMismatch { .. }))
);
}
#[test]
fn cannot_return_a_borrow_of_a_by_value_parameter() {
let i32_type = test_i32_type();
let errors = analyze_test_source_with_arguments(
"return &input",
vec![crate::semantic::SemanticFunctionArgument {
name: "input".into(),
mutable: false,
type_: i32_type.clone(),
}],
SemanticType::Reference {
lifetime: Some(test_lifetime("a", 0)),
mutable: false,
target: Box::new(i32_type),
},
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::EscapingLocalBorrow { .. }))
);
}
#[test]
fn reference_if_merge_preserves_all_branch_origins() {
let errors = analyze_test_source(
"let mut first: i32 = 1 let mut second: i32 = 2 let selected: &i32 = if true { &first } else { &second } first = 3",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::BorrowedPlaceMutation { .. })),
"unexpected errors: {errors:?}"
);
}
#[test]
fn reference_creation_requires_an_explicit_borrow_operator() {
let errors = analyze_test_source(
"let value: i32 = 1 let reference: &i32 = value",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::TypeMismatch { .. }))
);
analyze_test_source(
"let value: i32 = 1 let reference: &i32 = &value",
SemanticType::Void,
)
.unwrap();
}
#[test]
fn lexical_borrow_blocks_overwrite_until_holder_scope_ends() {
let errors = analyze_test_source(
"let mut value: i32 = 1 let borrowed: &i32 = &value value = 2",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::BorrowedPlaceMutation { .. }))
);
analyze_test_source(
"let mut value: i32 = 1 { let borrowed: &i32 = &value } value = 2",
SemanticType::Void,
)
.unwrap();
}
#[test]
fn allows_multiple_lexical_shared_borrows() {
analyze_test_source(
"let value: i32 = 1 let first: &i32 = &value let second: &i32 = &value",
SemanticType::Void,
)
.unwrap();
}
#[test]
fn mutable_reborrow_suspends_and_then_restores_the_parent_reference() {
analyze_test_source(
"let mut value: i32 = 1 let first: &mut i32 = &mut value { let second: &mut i32 = &mut first } first",
SemanticType::Void,
)
.unwrap();
}
#[test]
fn cannot_use_a_mutable_reference_while_it_is_reborrowed() {
let errors = analyze_test_source(
"let mut value: i32 = 1 let first: &mut i32 = &mut value { let second: &mut i32 = &mut first first }",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::SuspendedReferenceUse { .. }))
);
}
#[test]
fn transfers_a_mutable_reference_loan_to_the_new_holder() {
let errors = analyze_test_source(
"let mut value: i32 = 1 let first: &mut i32 = &mut value let second: &mut i32 = &mut first value = 2",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::BorrowedPlaceMutation { .. }))
);
}
#[test]
fn rejects_overlapping_lexical_mutable_borrows() {
let errors = analyze_test_source(
"let mut value: i32 = 1 let first: &mut i32 = &mut value let second: &mut i32 = &mut value",
SemanticType::Void,
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::ConflictingBorrows { .. }))
);
}
#[test]
fn rejects_a_reference_to_a_local_value_escaping_through_return() {
let i32_type = test_i32_type();
let errors = analyze_test_source(
"let value: i32 = 1 return &value",
SemanticType::Reference {
lifetime: None,
mutable: false,
target: Box::new(i32_type),
},
)
.unwrap_err();
assert!(
errors
.iter()
.any(|error| matches!(error, BodyAnalysisError::EscapingLocalBorrow { .. }))
);
}
#[test]
fn resolves_binary_addition_through_the_core_trait_method() {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
for (path, source) in [
("core://ops.lt", core_lib::OPS_MODULE_FILE_CONTENT),
("core://cmp.lt", core_lib::CMP_MODULE_FILE_CONTENT),
(
"core://primitive.lt",
core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
),
("core://prelude.lt", core_lib::PRELUDE_MODULE_FILE_CONTENT),
("app://main.lt", "return 1 + 2"),
] {
insert(&mut graph, &mut files, path, source);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.unwrap();
let registry = FunctionRegistry::build(&graph, &files).unwrap();
let file = files.get("app://main.lt").unwrap();
let i32_type = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32".into(),
},
generic_arguments: Vec::new(),
});
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(i32_type),
};
let body = BodyAnalyzer::new(&graph, ®istry, file, "app://main.lt", &signature)
.unwrap()
.analyze(&file.ast.contract_definition_content.statements)
.unwrap();
let add = registry
.function_id(&CanonicalSymbolPath {
module: "core://primitive.lt".into(),
local: "i32.Add.add".into(),
})
.unwrap();
assert!(
body.entry_block()
.instructions
.iter()
.any(|instruction| matches!(
&instruction.kind,
TypedInstructionKind::Call { function, arguments, .. }
if *function == add && arguments.len() == 2
))
);
}
}
fn statement_span(statement: &Statement) -> Span {
match statement {
Statement::Declaration(statement) => statement.span,
Statement::Assignment(statement) => statement.span,
Statement::Expression(expression) => expression.span,
Statement::Return(statement) => statement.span,
}
}
fn is_control_value(value: &ValueExpression) -> bool {
matches!(
value,
ValueExpression::If(_)
| ValueExpression::Contract(_)
| ValueExpression::While(_)
| ValueExpression::Loop(_)
)
}
fn constant_usize(expression: &Expression) -> Option<usize> {
let value = match &expression.kind {
ExpressionKind::Source(ExpressionSource::Value(value)) => value.as_ref(),
ExpressionKind::Source(ExpressionSource::Access(access)) if access.accessors.is_empty() => {
let AccessExpressionEntry::ValueExpression(value) = &access.entry else {
return None;
};
value
}
_ => return None,
};
match value {
ValueExpression::IntAny(value) => usize::try_from(value.value).ok(),
ValueExpression::Uint8(value) => Some(value.value.into()),
ValueExpression::Uint16(value) => Some(value.value.into()),
ValueExpression::Uint32(value) => usize::try_from(value.value).ok(),
ValueExpression::Uint64(value) => usize::try_from(value.value).ok(),
ValueExpression::Usize(value) => Some(value.value),
_ => None,
}
}
fn value_span(value: &ValueExpression) -> Span {
match value {
ValueExpression::Void(v) => v.span,
ValueExpression::Bool(v) => v.span,
ValueExpression::Char(v) => v.span,
ValueExpression::IntAny(v) => v.span,
ValueExpression::Int8(v) => v.span,
ValueExpression::Int16(v) => v.span,
ValueExpression::Int32(v) => v.span,
ValueExpression::Int64(v) => v.span,
ValueExpression::Isize(v) => v.span,
ValueExpression::Uint8(v) => v.span,
ValueExpression::Uint16(v) => v.span,
ValueExpression::Uint32(v) => v.span,
ValueExpression::Uint64(v) => v.span,
ValueExpression::Usize(v) => v.span,
ValueExpression::FloatAny(v) => v.span,
ValueExpression::Float32(v) => v.span,
ValueExpression::Float64(v) => v.span,
ValueExpression::String(v) => v.span,
ValueExpression::Array(v) => v.span,
ValueExpression::Contract(v) => v.span,
ValueExpression::Tuple(v) => v.span,
ValueExpression::If(v) => v.span,
ValueExpression::While(v) => v.span,
ValueExpression::Loop(v) => v.span,
}
}