Browse Source

Fix InvalidCastException on invalid compile-time constant casts.

newNRvisualizers
Daniel Grunwald 13 years ago
parent
commit
5e01d285d0
  1. 4
      ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs
  2. 18
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/MethodTests.cs
  3. 2
      ICSharpCode.NRefactory/Utils/CSharpPrimitiveCast.cs

4
ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs

@ -1305,6 +1305,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -1305,6 +1305,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
} catch (OverflowException) {
return new ErrorResolveResult(targetType);
} catch (InvalidCastException) {
return new ErrorResolveResult(targetType);
}
} else if (code == TypeCode.String) {
if (expression.ConstantValue == null || expression.ConstantValue is string)
@ -1318,6 +1320,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -1318,6 +1320,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
} catch (OverflowException) {
return new ErrorResolveResult(targetType);
} catch (InvalidCastException) {
return new ErrorResolveResult(targetType);
}
}
}

18
ICSharpCode.NRefactory.Tests/CSharp/Resolver/MethodTests.cs

@ -22,7 +22,7 @@ using ICSharpCode.NRefactory.Semantics; @@ -22,7 +22,7 @@ using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
[TestFixture]
public class MethodTests : ResolverTestBase
@ -225,5 +225,21 @@ class TestClass { @@ -225,5 +225,21 @@ class TestClass {
Assert.IsTrue(ReferenceEquals(value1, value2));
}
[Test]
public void MethodWithInvalidCastInDefaultValue()
{
var input = @"
class TestClass
{
void TestMethod ($int x = true$)
{
}
}";
var rr = Resolve<LocalResolveResult>(input);
IParameter p = (IParameter)rr.Variable;
Assert.IsTrue(p.IsOptional);
Assert.IsNull(p.ConstantValue);
}
}
}

2
ICSharpCode.NRefactory/Utils/CSharpPrimitiveCast.cs

@ -32,6 +32,8 @@ namespace ICSharpCode.NRefactory.Utils @@ -32,6 +32,8 @@ namespace ICSharpCode.NRefactory.Utils
/// and let the compiler figure out the exact semantics.
/// And we have to do everything twice, once in a checked-block, once in an unchecked-block.
/// </summary>
/// <exception cref="OverflowException">Overflow checking is enabled and an overflow occurred.</exception>
/// <exception cref="InvalidCastException">The cast is invalid, e.g. casting a boolean to an integer.</exception>
public static object Cast(TypeCode targetType, object input, bool checkForOverflow)
{
if (input == null)

Loading…
Cancel
Save