Skip to content

Commit

Permalink
Static casts should only propagate wider types
Browse files Browse the repository at this point in the history
  • Loading branch information
MikePopoloski committed Jan 14, 2025
1 parent 06b1a76 commit 98c2035
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
6 changes: 3 additions & 3 deletions source/ast/expressions/ConversionExpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -413,9 +413,9 @@ Expression& ConversionExpression::fromSyntax(Compilation& comp, const CastExpres
// The type we propagate should use the sign of the operand, just like it
// would if we were doing an implicit conversion via an assignment expression.
auto propagatedType = type;
if (type->isIntegral() && operand->type->isIntegral() &&
type->getIntegralFlags() != operand->type->getIntegralFlags()) {
propagatedType = &comp.getType(type->getBitWidth(), operand->type->getIntegralFlags());
if (type->isNumeric() && operand->type->isNumeric()) {
propagatedType = OpInfo::binaryType(comp, type, operand->type, false,
/* signednessFromRt */ true);
}

contextDetermined(context, operand, nullptr, *propagatedType, syntax.apostrophe.range(),
Expand Down
17 changes: 17 additions & 0 deletions tests/unittests/ast/ExpressionTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3788,3 +3788,20 @@ endmodule
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
}

TEST_CASE("Static casts propagate type correctly and don't truncate") {
auto tree = SyntaxTree::fromText(R"(
typedef logic [6:0] lt;
function automatic logic[7:0] foo;
logic [7:0] a = 8'hff;
lt b = lt'(a >> 1);
return 8'(b);
endfunction
$static_assert(foo() == 8'h7f);
)");

Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
}

0 comments on commit 98c2035

Please sign in to comment.