@@ -3646,8 +3646,20 @@ class CommonVisitor : public AST::BaseVisitor<Struct> {
36463646 if (ASRUtils::expr_value (operand) != nullptr ) {
36473647 int64_t op_value = ASR::down_cast<ASR::UnsignedIntegerConstant_t>(
36483648 ASRUtils::expr_value (operand))->m_n ;
3649+ if (op_value != 0 ) {
3650+ int kind = ASRUtils::extract_kind_from_ttype_t (operand_type);
3651+ int signed_promote_kind = (kind < 8 ) ? kind * 2 : kind;
3652+ diag.add (diag::Diagnostic (
3653+ " The result of the unary minus `-` operation is negative, thus out of range for u" + std::to_string (kind * 8 ),
3654+ diag::Level::Error, diag::Stage::Semantic, {
3655+ diag::Label (" use -i" + std::to_string (signed_promote_kind * 8 )
3656+ + " (u) for signed result" , {x.base .base .loc })
3657+ })
3658+ );
3659+ throw SemanticAbort ();
3660+ }
36493661 value = ASR::down_cast<ASR::expr_t >(ASR::make_UnsignedIntegerConstant_t (
3650- al, x.base .base .loc , -op_value , operand_type));
3662+ al, x.base .base .loc , 0 , operand_type));
36513663 }
36523664 tmp = ASR::make_UnsignedIntegerUnaryMinus_t (al, x.base .base .loc , operand,
36533665 operand_type, value);
@@ -7615,6 +7627,15 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
76157627 target_type = ASRUtils::TYPE (ASR::make_SymbolicExpression_t (al, x.base .base .loc ));
76167628 }
76177629 ASR::expr_t * arg = args[0 ].m_value ;
7630+ if (ASR::is_a<ASR::UnsignedInteger_t>(*target_type)) {
7631+ int64_t value_int;
7632+ if ( ASRUtils::extract_value (ASRUtils::expr_value (arg), value_int) ) {
7633+ if (value_int < 0 ) {
7634+ throw SemanticError (" Cannot cast negative value to unsigned integer " ,
7635+ x.base .base .loc );
7636+ }
7637+ }
7638+ }
76187639 cast_helper (target_type, arg, x.base .base .loc , true );
76197640 tmp = (ASR::asr_t *) arg;
76207641 return ;
0 commit comments