Search code examples
c#fxcop

FxCOp Custom Rules


I have been working on FxCOP Custom rules. I am working on getting lines of IL instructions used. I have a basic doubt, when we implement a c# code, we get opcodes, are these in different lines for every instruction(Source code Instruction has multiple opcodes in one line)

now, my mentor is asking me to count different lines in which multiple opcodes have been employed. However, I am of the understanding, that each IL instruction is in a different line. I will try to show the difference in opinion as follows:

Source code

opcode 1, opcode 2, opcode 3
opcode 4, opcode 5

My Opinion                   My Mentor's Opinion

Opcode 1                     Opcode 1,Opcode 2, Opcode 3
Opcode 2                     Opcode 5, Opcode 6
opcode 3

I have not been able to find which is true. Please help me find if for any given c# code, IL instructions are in separate lines in spite of the instruction being in the same line for source code, or if it is what my mentor believes and there is a way of finding different lines.

Thanks


Solution

  • You can write something like:

    public override ProblemCollection Check(Member member)
    {
        Method method = member as Method;
    
        if (method == null)
        {
            return base.Check(member);
        }
    
        Console.WriteLine("Method: {0}", member.Name);
    
        InstructionCollection ops = method.Instructions;
    
        foreach (Instruction op in ops)
        {
            Console.WriteLine("File: {0}, Line: {1}, Pos: {2}, OpCode: {3}", op.SourceContext.FileName, op.SourceContext.StartLine, op.SourceContext.StartColumn, op.OpCode);
        }
    
        Console.WriteLine();
    
        return base.Problems;
    }
    

    Note that in Release mode the relationship between line of code and OpCodes is a little "random", because the C# compiler can rearrange a little the code. In Debug mode the relationship is much more clear.

    Note (2) that I'm only considering StartLine and StartColumn. There are EndLine and EndColumn properties.