Browse Source

Ensure IVariable.ConstantValue has the correct type when a local constant declaration involves an implicit conversion

E.g. "const int MAXSIZE = ushort.MaxValue;"
newNRvisualizers
Daniel Grunwald 13 years ago
parent
commit
8f459c2460
  1. 4
      ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs
  2. 31
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs

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

@ -2913,7 +2913,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -2913,7 +2913,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
foreach (VariableInitializer vi in variableDeclarationStatement.Variables) {
IVariable v;
if (isConst) {
v = MakeConstant(type, vi.NameToken, Resolve(vi.Initializer).ConstantValue);
ResolveResult rr = Resolve(vi.Initializer);
rr = resolver.ResolveCast(type, rr);
v = MakeConstant(type, vi.NameToken, rr.ConstantValue);
} else {
v = MakeVariable(type, vi.NameToken);
}

31
ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs

@ -97,5 +97,36 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -97,5 +97,36 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
AssertError(typeof(StringComparison), resolver.WithCheckForOverflow(true).ResolveCast(ResolveType(typeof(StringComparison)), MakeConstant(long.MaxValue)));
}
[Test]
public void ImplicitCastInConstant()
{
string program = @"using System;
class Test {
const int $MAXSIZE = ushort.MaxValue;
}";
var rr = ResolveAtLocation<MemberResolveResult>(program);
IField field = (IField)rr.Member;
Assert.IsTrue(field.IsConst);
Assert.AreEqual("System.Int32", field.Type.FullName);
Assert.AreEqual(typeof(int), field.ConstantValue.GetType());
Assert.AreEqual(ushort.MaxValue, (int)field.ConstantValue);
}
[Test]
public void ImplicitCastInLocalConstant()
{
string program = @"using System;
class Test {
void M() {
const int $MAXSIZE = ushort.MaxValue;
}
}";
var rr = ResolveAtLocation<LocalResolveResult>(program);
Assert.IsTrue(rr.Variable.IsConst);
Assert.AreEqual("System.Int32", rr.Variable.Type.FullName);
Assert.AreEqual(typeof(int), rr.Variable.ConstantValue.GetType());
Assert.AreEqual(ushort.MaxValue, (int)rr.Variable.ConstantValue);
}
}
}

Loading…
Cancel
Save