GotoSwitchCaseStatement

Apr 4, 2010 at 2:21 PM

Does PeWriter handle GotoSwitchCaseStatement correctly? I tried to generate assembly with code below (modified HelloCodeModel sample), but it looks like output assembly doesn't contain expected goto instructions:

var block = new BlockStatement();
body.Block = block;

var systemConsole = UnitHelper.FindType(nameTable, coreAssembly, "System.Console");
var writeLine = TypeHelper.GetMethod(systemConsole, nameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);
var call = new MethodCall { IsStaticCall = true, MethodToCall = writeLine, Type = host.PlatformType.SystemVoid };
call.Arguments.Add(new CompileTimeConstant { Type = host.PlatformType.SystemString, Value = "hello" });

var localDefinition = new LocalDefinition { Type = host.PlatformType.SystemInt32 };
block.Statements.Add(new LocalDeclarationStatement { LocalVariable = localDefinition, InitialValue = new CompileTimeConstant { Value = 0, Type = host.PlatformType.SystemInt32 } });
            
var switchStatement = new SwitchStatement { Expression = new BoundExpression { Definition = localDefinition, Type = host.PlatformType.SystemInt32 } };
var switchCase0 = new SwitchCase { Expression = new CompileTimeConstant { Value = 0, Type = host.PlatformType.SystemInt32 } };
var switchCase1 = new SwitchCase { Expression = new CompileTimeConstant { Value = 1, Type = host.PlatformType.SystemInt32 } };

switchCase0.Body.Add(new ExpressionStatement { Expression = call });
switchCase0.Body.Add(new GotoSwitchCaseStatement { TargetCase = switchCase1 });
switchCase0.Body.Add(new BreakStatement());

switchCase1.Body.Add(new ExpressionStatement { Expression = call });
switchCase1.Body.Add(new ExpressionStatement { Expression = call });
switchCase1.Body.Add(new BreakStatement());
            
switchStatement.Cases.Add(switchCase0);
switchStatement.Cases.Add(switchCase1);
block.Statements.Add(switchStatement);
block.Statements.Add(new ReturnStatement());

I expect something like this:
int i = 0;
switch (i)
{
    case 0:
        Console.WriteLine("hello");
        goto case 1;
        break;

    case 1:
        Console.WriteLine("hello");
        Console.WriteLine("hello");
        break;
}
return;
But "goto case 1;" is missed.

I can't find any issues in generating code, so I suppose that this feature is not supported. Please correct me if I miss something.

Alexander
Coordinator
Apr 4, 2010 at 8:16 PM

PeWriter does just fine with switch statements. The problem that you are running into is that CodeModelToIL has not yet been fully implemented. One of the missing features is a full flegded implementation of switch statements.

The code is not difficult to write, just tedious.

Apr 4, 2010 at 8:27 PM

Thanks for your reply. I hope you will have enough resources to write such tedious code :)