From adaea0e993fd8db351b5dad92802e47ed6d0ec77 Mon Sep 17 00:00:00 2001 From: Yong He Date: Wed, 17 Aug 2022 23:08:34 -0700 Subject: Warning on lossy implicit casts. (#2367) * Warning on bool to float conversion. * Fix test cases. * Improve. * LanguageServer: don't show constant value for non constant variables. * Fix tests. * Fix warnings in tests. Co-authored-by: Yong He --- source/slang/slang-check-conversion.cpp | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) (limited to 'source/slang/slang-check-conversion.cpp') diff --git a/source/slang/slang-check-conversion.cpp b/source/slang/slang-check-conversion.cpp index 4bcf07b2b..a3273f942 100644 --- a/source/slang/slang-check-conversion.cpp +++ b/source/slang/slang-check-conversion.cpp @@ -955,15 +955,39 @@ namespace Slang // but then emit a diagnostic when actually reifying // the result expression. // - if( cost >= kConversionCost_Explicit ) + if (outToExpr) { - if( outToExpr ) + if (cost >= kConversionCost_Explicit) { getSink()->diagnose(fromExpr, Diagnostics::typeMismatch, toType, fromType); - getSink()->diagnose(fromExpr, Diagnostics::noteExplicitConversionPossible, fromType, toType); + getSink()->diagnose( + fromExpr, Diagnostics::noteExplicitConversionPossible, fromType, toType); + } + else if (cost >= kConversionCost_Default) + { + // For general types of implicit conversions, we issue a warning, unless `fromExpr` is a known constant + // and we know it won't cause a problem. + bool shouldEmitGeneralWarning = true; + if (isScalarIntegerType(toType)) + { + if (auto intVal = tryFoldIntegerConstantExpression(fromExpr, nullptr)) + { + if (auto val = as(intVal)) + { + if (isIntValueInRangeOfType(val->value, toType)) + { + // OK. + shouldEmitGeneralWarning = false; + } + } + } + } + if (shouldEmitGeneralWarning) + { + getSink()->diagnose(fromExpr, Diagnostics::unrecommendedImplicitConversion, fromType, toType); + } } } - if(outCost) *outCost = cost; -- cgit v1.2.3