jbevain/cecil — Issue #82: MethodBody.ThisParameter type should be a pointer for value types
Author: keithshep
Created: 2011-10-29 15:48:37+00:00
State: open

`MethodBody.ThisParameter` uses `method.DeclaringType` for the parameter type which is correct for objects but for value types I don't think this is right. According to ECMA 335 Partition II 13.3 "Instance and virtual methods of classes shall be coded to expect a reference to an instance of the class as the this pointer. By contrast, instance and virtual methods of value types shall be coded to expect a managed pointer"

The following F# code shows how I'm working around this issue for now. It is only very lightly tested so I'm not confident that it's all correct:

```fsharp
/// extend cecil's MethodBody class
type MethodBody with

/// gets all parameters including any implicit this parameters
member x.AllParameters = [|
let meth = x.Method
if meth.HasThis then
//yield x.ThisParameter

// ThisParameter returns a bad type for valuetypes
// see "Partition II 13.3 Methods of value types"
let thisParamTy =
match meth.DeclaringType.MetadataType with
| MetadataType.Boolean | MetadataType.Char | MetadataType.SByte | MetadataType.Byte
| MetadataType.Int16 | MetadataType.UInt16 | MetadataType.Int32 | MetadataType.UInt32
| MetadataType.Int64 | MetadataType.UInt64 | MetadataType.Single | MetadataType.Double
| MetadataType.Pointer | MetadataType.ValueType
| MetadataType.IntPtr | MetadataType.UIntPtr | MetadataType.FunctionPointer ->
new PointerType(meth.DeclaringType) :> TypeReference
| _ ->
meth.DeclaringType :> TypeReference
yield new ParameterDefinition ("0", ParameterAttributes.None, thisParamTy)
for p in meth.Parameters do
yield p
|]
```