Skip to content

Commit

Permalink
check all array elements are of the same type
Browse files Browse the repository at this point in the history
  • Loading branch information
xunilrj committed Aug 13, 2024
1 parent 9e589a2 commit 04bc8e8
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 11 deletions.
50 changes: 41 additions & 9 deletions sway-core/src/language/ty/expression/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,49 @@ impl TypeCheckAnalysis for TyExpression {
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
// Check literal "fits" into assigned typed.
if let TyExpressionVariant::Literal(Literal::Numeric(literal_value)) = &self.expression {
let t = ctx.engines.te().get(self.return_type);
if let TypeInfo::UnsignedInteger(bits) = &*t {
if bits.would_overflow(*literal_value) {
handler.emit_err(CompileError::TypeError(TypeError::ConstrainedNumeric {
expected: format!("{:?}", ctx.engines.help_out(t)),
span: self.span.clone(),
}));
match &self.expression {
// Check literal "fits" into assigned typed.
TyExpressionVariant::Literal(Literal::Numeric(literal_value)) => {
let t = ctx.engines.te().get(self.return_type);
if let TypeInfo::UnsignedInteger(bits) = &*t {
if bits.would_overflow(*literal_value) {
handler.emit_err(CompileError::TypeError(TypeError::ConstrainedNumeric {
expected: format!("{:?}", ctx.engines.help_out(t)),
span: self.span.clone(),
}));
}
}
}
// Check all array items are the same
TyExpressionVariant::Array {
elem_type,
contents,
} => {
let eqctx = PartialEqWithEnginesContext::new(ctx.engines);
let array_elem_type = ctx.engines.te().get(*elem_type);

// If the array element is never, we do not need to check
if !matches!(&*array_elem_type, TypeInfo::Never) {
for element in contents {
let elem_type = ctx.engines.te().get(element.return_type);

// If the element is never, we do not need to check
if !matches!(&*array_elem_type, TypeInfo::Never) {
continue;
}

if !array_elem_type.eq(&*elem_type, &eqctx) {
handler.emit_err(CompileError::TypeError(TypeError::MismatchedType {
expected: format!("{:?}", ctx.engines.help_out(&array_elem_type)),
received: format!("{:?}", ctx.engines.help_out(elem_type)),
help_text: String::new(),
span: element.span.clone(),
}));
}
}
}
}
_ => {}
}
self.expression.type_check_analyze(handler, ctx)
}
Expand Down
2 changes: 1 addition & 1 deletion sway-core/src/type_system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ mod id;
mod info;
mod priv_prelude;
mod substitute;
mod unify;
pub(crate) mod unify;

#[allow(unused)]
use std::ops::Deref;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ fn main() {
// u32
let _a = 0x100000000;
Vec::<u32>::new().push(_a);
}

// Array
let a = [1, 2, "hello"];
}

0 comments on commit 04bc8e8

Please sign in to comment.