public static bool TryGetVariableIndex(this Instruction instruction, out int? variableIndex)
{
Contract.Requires(instruction != null);
Contract.Ensures(Contract.ValueAtReturn<int?>(out variableIndex).HasValue || !Contract.Result<bool>());
switch (instruction.OpCode.Code)
{
case Code.Ldloc_0:
case Code.Stloc_0:
variableIndex = 0;
return true;
case Code.Ldloc_1:
case Code.Stloc_1:
variableIndex = 1;
return true;
case Code.Ldloc_2:
case Code.Stloc_2:
variableIndex = 2;
return true;
case Code.Ldloc_3:
case Code.Stloc_3:
variableIndex = 3;
return true;
case Code.Ldloc:
case Code.Ldloc_S:
case Code.Ldloca:
case Code.Ldloca_S:
case Code.Stloc:
case Code.Stloc_S:
variableIndex = ((VariableDefinition)instruction.Operand).Index;
if (variableIndex < 0)
{
throw new InvalidOperationException(
$"Did not expect a negative variable index for {((VariableDefinition)instruction.Operand).Name}");
}
return true;
default:
variableIndex = default(int?);
return false;
}
}