mod coverage;
mod patterns;
use std::collections::HashMap;
use crate::{
analysis::AnalysisDiagnostic,
ast::{Block, Expr, Literal, MatchArm, Pattern, Program, Stmt},
semantic::ExpressionTypes,
source::Span,
types::Type,
};
pub(crate) fn analyze(
program: &Program,
expression_types: ExpressionTypes<'_>,
host_contract: Option<&rils_host::HostContract>,
module: &[String],
declarations: &crate::semantic::DeclarationTypeResolver,
) -> Vec<AnalysisDiagnostic> {
Checker::new(
program,
expression_types,
host_contract,
module,
declarations,
)
.run(program)
}
struct Checker<'a> {
expression_types: ExpressionTypes<'a>,
enums: HashMap<String, Vec<String>>,
impl_type: Option<Type>,
declarations: &'a crate::semantic::DeclarationTypeResolver,
module: Vec<String>,
diagnostics: Vec<AnalysisDiagnostic>,
}
impl<'a> Checker<'a> {
fn new(
program: &Program,
expression_types: ExpressionTypes<'a>,
host_contract: Option<&rils_host::HostContract>,
module: &[String],
declarations: &'a crate::semantic::DeclarationTypeResolver,
) -> Self {
let mut checker = Self {
expression_types,
declarations,
module: module.to_vec(),
enums: HashMap::new(),
impl_type: None,
diagnostics: Vec::new(),
};
if let Some(host) = host_contract {
for declaration in host.types() {
if let Some(host_enum) = declaration.enum_definition.as_ref() {
checker.enums.insert(
declaration.name.clone(),
host_enum
.variants
.keys()
.cloned()
.chain(host_enum.flags.then(|| "_".to_owned()))
.collect(),
);
}
}
}
checker.collect_enums(&program.statements, &mut module.to_vec());
checker
}
fn run(mut self, program: &Program) -> Vec<AnalysisDiagnostic> {
self.statements(&program.statements);
self.diagnostics
}
fn collect_enums(&mut self, statements: &[Stmt], module: &mut Vec<String>) {
for statement in statements {
match statement {
Stmt::Module {
name,
statements: Some(statements),
..
} => {
module.push(name.clone());
self.collect_enums(statements, module);
module.pop();
}
Stmt::Enum { name, variants, .. } => {
self.enums.insert(
crate::semantic::source_type_path(module, name),
variants
.iter()
.map(|variant| variant.name().to_owned())
.collect(),
);
}
_ => {}
}
}
}
fn statements(&mut self, statements: &[Stmt]) -> bool {
let mut reachable = true;
for statement in statements {
if !reachable {
self.diagnostics.push(AnalysisDiagnostic::warning(
"unreachable statement",
statement_span(statement),
));
}
let falls_through = self.statement(statement);
if reachable {
reachable = falls_through;
}
}
reachable
}
fn statement(&mut self, statement: &Stmt) -> bool {
match statement {
Stmt::Module {
name,
statements: Some(statements),
..
} => {
self.module.push(name.clone());
self.statements(statements);
self.module.pop();
true
}
Stmt::Function {
attributes,
return_type,
body,
..
} => {
if !crate::ast::has_compiler_internal_attribute(attributes) {
self.function(return_type.as_ref(), body);
}
true
}
Stmt::Impl {
target, methods, ..
} => {
let previous = self
.impl_type
.replace(self.declarations.resolve(target, &self.module));
for method in methods {
if !crate::ast::has_compiler_internal_attribute(&method.attributes) {
self.function(method.return_type.as_ref(), &method.body);
}
}
self.impl_type = previous;
true
}
Stmt::While {
condition, body, ..
} => {
self.expression(condition);
self.block(body);
true
}
Stmt::Loop { body, .. } => {
let can_break = block_contains_break(body);
self.block(body);
can_break
}
Stmt::For { iterable, body, .. } => {
self.expression(iterable);
self.block(body);
true
}
Stmt::Return { value, .. } | Stmt::Break { value, .. } => {
if let Some(value) = value {
self.expression(value);
}
false
}
Stmt::Continue { .. } => false,
Stmt::Let { initializer, .. } => {
self.expression(initializer);
true
}
Stmt::Expr { expression, .. } => self.expression(expression),
Stmt::Module {
statements: None, ..
}
| Stmt::Use { .. }
| Stmt::Struct { .. }
| Stmt::Enum { .. }
| Stmt::TypeAlias { .. }
| Stmt::Trait { .. } => true,
}
}
fn function(&mut self, return_type: Option<&Type>, body: &Block) {
let falls_through = self.block(body);
let Some(expected) = return_type else {
return;
};
if !falls_through || matches!(expected, Type::Unit | Type::Unknown) {
return;
}
if block_can_produce_unit(body) {
self.diagnostics.push(AnalysisDiagnostic::error(
format!("not all paths return `{expected}`"),
body.span,
));
}
}
fn block(&mut self, block: &Block) -> bool {
self.statements(&block.statements)
}
fn expression(&mut self, expression: &Expr) -> bool {
match expression {
Expr::Member { object, .. }
| Expr::Try {
operand: object, ..
}
| Expr::Borrow { target: object, .. }
| Expr::Unary {
operand: object, ..
}
| Expr::Cast {
operand: object, ..
} => {
self.expression(object);
true
}
Expr::Index { object, index, .. }
| Expr::Assign {
target: object,
value: index,
..
}
| Expr::Binary {
left: object,
right: index,
..
}
| Expr::Logical {
left: object,
right: index,
..
}
| Expr::Range {
start: object,
end: index,
..
} => {
self.expression(object);
self.expression(index);
true
}
Expr::Tuple { elements, .. } | Expr::Array { elements, .. } => {
for element in elements {
self.expression(element);
}
if let Expr::Array {
repeat: Some(repeat),
..
} = expression
{
self.expression(repeat);
}
true
}
Expr::RecordLiteral { fields, .. } => {
for field in fields {
self.expression(&field.value);
}
true
}
Expr::Call {
callee, arguments, ..
} => {
self.expression(callee);
for argument in arguments {
self.expression(argument);
}
true
}
Expr::If {
condition,
then_branch,
else_branch,
..
} => {
self.expression(condition);
let then_falls_through = self.block(then_branch);
let else_falls_through = else_branch
.as_deref()
.is_none_or(|branch| self.expression(branch));
then_falls_through || else_falls_through
}
Expr::Match { value, arms, .. } => {
self.expression(value);
let exhaustive = self.check_match(value, arms);
let mut any_arm_falls_through = false;
for arm in arms {
any_arm_falls_through =
self.expression(&arm.expression) || any_arm_falls_through;
}
!exhaustive || any_arm_falls_through
}
Expr::Block(block) => self.block(block),
Expr::Literal { .. }
| Expr::Variable { .. }
| Expr::Path { .. }
| Expr::GenericPath { .. }
| Expr::QualifiedPath { .. } => true,
}
}
fn check_match(&mut self, value: &Expr, arms: &[MatchArm]) -> bool {
let ty = self
.expression_types
.get(value)
.cloned()
.unwrap_or(Type::Unknown);
let mut coverage = coverage::MatchCoverage::default();
for arm in arms {
let pattern = self.expression_types.arm_pattern(arm);
let Some(pattern) = self.coverage_pattern(pattern, &ty) else {
continue;
};
if !coverage.insert(self, pattern, &ty) {
self.diagnostics.push(AnalysisDiagnostic::warning(
"unreachable match arm",
arm.pattern.span(),
));
}
}
if let Some(missing) = coverage.missing(self, &ty) {
if missing.is_empty() {
return true;
}
self.diagnostics.push(AnalysisDiagnostic::error(
format!("non-exhaustive match; missing {}", missing.join(", ")),
value.span(),
));
}
false
}
}
pub(crate) fn block_diverges(block: &Block) -> bool {
block.statements.iter().any(|statement| match statement {
Stmt::Return { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => true,
Stmt::Loop { body, .. } => !block_contains_break(body),
Stmt::Expr { expression, .. }
| Stmt::Let {
initializer: expression,
..
} => expression_diverges(expression),
_ => false,
})
}
pub(crate) fn expression_diverges(expression: &Expr) -> bool {
match expression {
Expr::Block(block) => block_diverges(block),
Expr::If {
then_branch,
else_branch: Some(branch),
..
} => block_diverges(then_branch) && expression_diverges(branch),
Expr::Match { arms, .. } => {
!arms.is_empty() && arms.iter().all(|arm| expression_diverges(&arm.expression))
}
_ => false,
}
}
fn block_can_produce_unit(block: &Block) -> bool {
let Some(last) = block.statements.last() else {
return true;
};
match last {
Stmt::Return { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => false,
Stmt::Expr {
expression,
terminated: false,
} => expression_can_produce_unit(expression),
_ => true,
}
}
fn expression_can_produce_unit(expression: &Expr) -> bool {
match expression {
Expr::Literal {
value: Literal::Unit,
..
}
| Expr::Assign { .. } => true,
Expr::If {
then_branch,
else_branch,
..
} => {
else_branch.is_none()
|| block_can_produce_unit(then_branch)
|| else_branch
.as_deref()
.is_some_and(expression_can_produce_unit)
}
Expr::Match { arms, .. } => arms
.iter()
.any(|arm| expression_can_produce_unit(&arm.expression)),
Expr::Block(block) => block_can_produce_unit(block),
_ => false,
}
}
fn literal_key(literal: &Literal) -> Option<String> {
match literal {
Literal::Unit => Some("literal:()".into()),
Literal::Bool(value) => Some(format!("literal:{value}")),
Literal::I8(value) => Some(format!("literal:i8:{value}")),
Literal::I16(value) => Some(format!("literal:i16:{value}")),
Literal::I32(value) => Some(format!("literal:i32:{value}")),
Literal::I64(value) => Some(format!("literal:i64:{value}")),
Literal::I128(value) => Some(format!("literal:i128:{value}")),
Literal::Isize(value) => Some(format!("literal:isize:{value}")),
Literal::U8(value) => Some(format!("literal:u8:{value}")),
Literal::U16(value) => Some(format!("literal:u16:{value}")),
Literal::U32(value) => Some(format!("literal:u32:{value}")),
Literal::U64(value) => Some(format!("literal:u64:{value}")),
Literal::U128(value) => Some(format!("literal:u128:{value}")),
Literal::Usize(value) => Some(format!("literal:usize:{value}")),
Literal::F32(value) => {
let bits = if *value == 0.0 { 0 } else { value.to_bits() };
Some(format!("literal:f32:{bits:08x}"))
}
Literal::F64(value) => {
let bits = if *value == 0.0 { 0 } else { value.to_bits() };
Some(format!("literal:f64:{bits:016x}"))
}
Literal::Char(value) => Some(format!("literal:char:{value:?}")),
Literal::Integer(_) | Literal::Float(_) => None,
Literal::String(value) => Some(format!("literal:{value:?}")),
}
}
fn block_contains_break(block: &Block) -> bool {
block.statements.iter().any(statement_contains_break)
}
fn statement_contains_break(statement: &Stmt) -> bool {
match statement {
Stmt::Break { .. } => true,
Stmt::Expr { expression, .. } => expression_contains_break(expression),
Stmt::While { .. }
| Stmt::Loop { .. }
| Stmt::For { .. }
| Stmt::Function { .. }
| Stmt::Impl { .. }
| Stmt::Trait { .. } => false,
_ => false,
}
}
fn expression_contains_break(expression: &Expr) -> bool {
match expression {
Expr::If {
then_branch,
else_branch,
..
} => {
block_contains_break(then_branch)
|| else_branch
.as_deref()
.is_some_and(expression_contains_break)
}
Expr::Match { arms, .. } => arms
.iter()
.any(|arm| expression_contains_break(&arm.expression)),
Expr::Block(block) => block_contains_break(block),
_ => false,
}
}
fn statement_span(statement: &Stmt) -> Span {
match statement {
Stmt::Module { span, .. }
| Stmt::Use { span, .. }
| Stmt::Let { span, .. }
| Stmt::Function { span, .. }
| Stmt::Struct { span, .. }
| Stmt::Enum { span, .. }
| Stmt::TypeAlias { span, .. }
| Stmt::Impl { span, .. }
| Stmt::Trait { span, .. }
| Stmt::While { span, .. }
| Stmt::Loop { span, .. }
| Stmt::For { span, .. }
| Stmt::Return { span, .. }
| Stmt::Break { span, .. }
| Stmt::Continue { span, .. } => *span,
Stmt::Expr { expression, .. } => expression.span(),
}
}