use std::collections::{HashMap, HashSet};
use crate::{
analysis::AnalysisDiagnostic,
ast::{Block, Expr, Literal, Program, Stmt},
format::{FormatPiece, parse_format_string},
semantic::ExpressionTypes,
source::Span,
types::Type,
};
pub(crate) fn analyze(
program: &Program,
expression_types: ExpressionTypes<'_>,
host_types: &HashSet<String>,
declarations: &crate::semantic::DeclarationTypeResolver,
module: &[String],
) -> Vec<AnalysisDiagnostic> {
let mut checker = Checker {
expression_types,
host_types,
declarations,
module: module.to_vec(),
diagnostics: Vec::new(),
generic_bounds: HashMap::new(),
};
checker.statements(&program.statements);
checker.diagnostics
}
struct Checker<'a> {
expression_types: ExpressionTypes<'a>,
host_types: &'a HashSet<String>,
declarations: &'a crate::semantic::DeclarationTypeResolver,
module: Vec<String>,
diagnostics: Vec<AnalysisDiagnostic>,
generic_bounds: HashMap<String, Vec<Type>>,
}
impl Checker<'_> {
fn statements(&mut self, statements: &[Stmt]) {
for statement in statements {
match statement {
Stmt::Module {
name,
statements: Some(statements),
..
} => {
self.module.push(name.clone());
self.statements(statements);
self.module.pop();
}
Stmt::Function {
attributes,
body,
generic_parameters,
..
} => {
if !crate::ast::has_compiler_internal_attribute(attributes) {
let previous = self.generic_bounds.clone();
for parameter in generic_parameters {
self.generic_bounds
.insert(parameter.name.clone(), parameter.bounds.clone());
}
self.block(body);
self.generic_bounds = previous;
}
}
Stmt::Impl {
methods,
generic_parameters,
..
} => {
let previous_impl = self.generic_bounds.clone();
for parameter in generic_parameters {
self.generic_bounds
.insert(parameter.name.clone(), parameter.bounds.clone());
}
for method in methods {
if !crate::ast::has_compiler_internal_attribute(&method.attributes) {
let previous = self.generic_bounds.clone();
for parameter in &method.generic_parameters {
self.generic_bounds
.insert(parameter.name.clone(), parameter.bounds.clone());
}
self.block(&method.body);
self.generic_bounds = previous;
}
}
self.generic_bounds = previous_impl;
}
Stmt::Let { initializer, .. } => self.expression(initializer),
Stmt::While {
condition, body, ..
} => {
self.expression(condition);
self.block(body);
}
Stmt::Loop { body, .. } => self.block(body),
Stmt::For { iterable, body, .. } => {
self.expression(iterable);
self.block(body);
}
Stmt::Return {
value: Some(value), ..
}
| Stmt::Break {
value: Some(value), ..
} => self.expression(value),
Stmt::Expr { expression, .. } => self.expression(expression),
_ => {}
}
}
}
fn block(&mut self, block: &Block) {
self.statements(&block.statements);
}
fn expression(&mut self, expression: &Expr) {
if let Expr::Call {
callee, arguments, ..
} = expression
&& let Expr::Variable { name, .. } = callee.as_ref()
&& let Some(index) = rils_builtins::macro_function(name)
.and_then(|item| item.entry)
.and_then(|entry| entry.format)
{
self.check_call(arguments.get(index..).unwrap_or_default());
}
match expression {
Expr::Member { object, .. }
| Expr::Borrow { target: object, .. }
| Expr::Try {
operand: object, ..
}
| Expr::Unary {
operand: object, ..
}
| Expr::Cast {
operand: object, ..
} => self.expression(object),
Expr::Index { object, 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);
}
Expr::Tuple { elements, .. } => {
for element in elements {
self.expression(element);
}
}
Expr::Array {
elements, repeat, ..
} => {
for element in elements {
self.expression(element);
}
if let Some(repeat) = repeat {
self.expression(repeat);
}
}
Expr::Call {
callee, arguments, ..
} => {
self.expression(callee);
if let Some(Type::Function {
parameters: Some(parameters),
..
}) = self.expression_types.get(callee).cloned()
{
for (expected, argument) in parameters.iter().zip(arguments) {
let actual = self
.expression_types
.get(argument)
.cloned()
.unwrap_or(Type::Unknown);
self.check_bound_argument(expected, &actual, argument.span());
}
}
for argument in arguments {
self.expression(argument);
}
}
Expr::If {
condition,
then_branch,
else_branch,
..
} => {
self.expression(condition);
self.block(then_branch);
if let Some(branch) = else_branch {
self.expression(branch);
}
}
Expr::Assign { target, value, .. } => {
self.expression(target);
self.expression(value);
}
Expr::RecordLiteral { fields, .. } => {
for field in fields {
self.expression(&field.value);
}
}
Expr::Match { value, arms, .. } => {
self.expression(value);
for arm in arms {
self.expression(&arm.expression);
}
}
Expr::Block(block) => self.block(block),
Expr::Literal { .. }
| Expr::Variable { .. }
| Expr::Path { .. }
| Expr::GenericPath { .. }
| Expr::QualifiedPath { .. } => {}
}
}
fn check_call(&mut self, arguments: &[Expr]) {
let Some(Expr::Literal {
value: Literal::String(format),
..
}) = arguments.first()
else {
return;
};
let Ok(pieces) = parse_format_string(format) else {
return;
};
for piece in pieces {
let FormatPiece::Placeholder { argument, spec } = piece else {
continue;
};
let Some(value) = arguments.get(argument + 1) else {
continue;
};
let ty = self
.expression_types
.get(value)
.cloned()
.unwrap_or(Type::Unknown);
let ty = self.resolve_type(&ty);
let supported =
if let Some(required) = rils_builtins::format_capabilities::trait_name(spec.kind) {
self.implements(&ty, required)
} else {
crate::format_traits::supports(&ty, spec.kind, &|ty, _| {
matches!(deref_type(ty), Type::Unknown)
})
};
if !supported {
self.error(
rils_builtins::format_capabilities::diagnostic(spec.kind, &ty),
value.span(),
);
}
}
}
fn check_bound_argument(&mut self, expected: &Type, actual: &Type, span: Span) {
match (expected, actual) {
(Type::BoundVariable { bounds, .. }, actual) => {
for bound in bounds {
if let Type::Named { name, .. } = bound {
let required =
crate::standard_library::builtin_trait_name(name).unwrap_or(name);
if matches!(required, "Display" | "Debug")
&& !self.implements_strict(actual, required)
{
self.error(
format!(
"type `{actual}` does not implement required trait `{required}`"
),
span,
);
}
}
}
}
(Type::Reference { inner, .. }, Type::Reference { inner: actual, .. }) => {
self.check_bound_argument(inner, actual, span)
}
_ => {}
}
}
fn resolve_type(&self, ty: &Type) -> Type {
let bindings = self
.generic_bounds
.iter()
.map(|(name, bounds)| {
(
name.clone(),
Type::BoundVariable {
name: name.clone(),
bounds: bounds
.iter()
.map(|bound| self.declarations.resolve(bound, &self.module))
.collect(),
},
)
})
.collect();
self.declarations
.resolve(&ty.substitute(&bindings), &self.module)
}
fn implements_strict(&self, ty: &Type, required: &str) -> bool {
let ty = self.resolve_type(ty);
if matches!(
deref_type(&ty),
Type::Unknown | Type::Variable(_) | Type::Associated { .. }
) {
return false;
}
self.implements(&ty, required)
}
fn implements(&self, ty: &Type, required: &str) -> bool {
let ty = self.resolve_type(ty);
match deref_type(&ty) {
Type::Unknown | Type::Variable(_) | Type::Associated { .. } => true,
Type::Named { name, .. } if self.host_types.contains(name) => true,
_ => self
.declarations
.implements_trait(&ty, &format!("core::fmt::{required}")),
}
}
fn error(&mut self, message: String, span: Span) {
self.diagnostics
.push(AnalysisDiagnostic::error(message, span));
}
}
fn deref_type(mut ty: &Type) -> &Type {
while let Type::Reference { inner, .. } = ty {
ty = inner;
}
ty
}