mirror of
https://github.com/Smaug123/WoofWare.PawPrint
synced 2025-12-14 21:45:39 +00:00
Compare commits
4 Commits
castclass
...
runtime-ty
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7150e3294 | ||
|
|
ab4c251c97 | ||
|
|
cbbde0c4ba | ||
|
|
8aa33b5606 |
76
CLAUDE.md
76
CLAUDE.md
@@ -81,9 +81,7 @@ dotnet publish --self-contained --runtime-id osx-arm64 CSharpExample/ && dotnet
|
||||
|
||||
* Functions should be fully type-annotated, to give the most helpful error messages on type mismatches.
|
||||
* Generally, prefer to fully-qualify discriminated union cases in `match` statements.
|
||||
* ALWAYS fully-qualify enum cases when constructing them and matching on them (e.g., `PrimitiveType.Int16` not `Int16`).
|
||||
* When writing a "TODO" `failwith`, specify in the error message what the condition is that triggers the failure, so that a failing run can easily be traced back to its cause.
|
||||
* If a field name begins with an underscore (like `_LoadedAssemblies`), do not mutate it directly. Only mutate it via whatever intermediate methods have been defined for that purpose (like `WithLoadedAssembly`).
|
||||
|
||||
### Development Workflow
|
||||
|
||||
@@ -100,77 +98,3 @@ It strongly prefers to avoid special-casing to get around problems, but instead
|
||||
### Common Gotchas
|
||||
|
||||
* I've named several types in such a way as to overlap with built-in types, e.g. MethodInfo is in both WoofWare.PawPrint and System.Reflection.Metadata namespaces. Build errors can usually be fixed by fully-qualifying the type.
|
||||
|
||||
## Type Concretization System
|
||||
|
||||
### Overview
|
||||
|
||||
Type concretization converts abstract type definitions (`TypeDefn`) to concrete runtime types (`ConcreteTypeHandle`). This is essential because IL operations need exact types at runtime, including all generic instantiations. The system separates type concretization from IL execution, ensuring types are properly loaded before use.
|
||||
|
||||
### Key Concepts
|
||||
|
||||
#### Generic Parameters
|
||||
- **Common error**: "Generic type/method parameter X out of range" probably means you're missing the proper generic context: some caller has passed the wrong list of generics through somewhere.
|
||||
|
||||
#### Assembly Context
|
||||
TypeRefs must be resolved in the context of the assembly where they're defined, not where they're used. When resolving a TypeRef, always use the assembly that contains the TypeRef in its metadata.
|
||||
|
||||
### Common Scenarios and Solutions
|
||||
|
||||
#### Nested Generic Contexts
|
||||
When inside `Array.Empty<T>()` calling `AsRef<T>`, the `T` refers to the outer method's generic parameter. Pass the current executing method's generics as context:
|
||||
```fsharp
|
||||
let currentMethod = state.ThreadState.[thread].MethodState.ExecutingMethod
|
||||
concretizeMethodWithTypeGenerics ... currentMethod.Generics state
|
||||
```
|
||||
|
||||
#### Field Access in Generic Contexts
|
||||
When accessing `EmptyArray<T>.Value` from within `Array.Empty<T>()`, use both type and method generics:
|
||||
```fsharp
|
||||
let contextTypeGenerics = currentMethod.DeclaringType.Generics
|
||||
let contextMethodGenerics = currentMethod.Generics
|
||||
```
|
||||
|
||||
#### Call vs CallMethod
|
||||
- `callMethodInActiveAssembly` expects unconcretized methods and does concretization internally
|
||||
- `callMethod` expects already-concretized methods
|
||||
- The refactoring changed to concretizing before calling to ensure types are loaded
|
||||
|
||||
### Common Pitfalls
|
||||
|
||||
1. **Don't create new generic parameters when they already exist**. It's *very rarely* correct to instantiate `TypeDefn.Generic{Type,Method}Parameter` yourself:
|
||||
```fsharp
|
||||
// Wrong: field.DeclaringType.Generics |> List.mapi (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
// Right: field.DeclaringType.Generics
|
||||
```
|
||||
|
||||
2. **Assembly loading context**: The `loadAssembly` function expects the assembly that contains the reference as the first parameter, not the target assembly
|
||||
|
||||
3. **Type forwarding**: Use `Assembly.resolveTypeRef` which handles type forwarding and exported types correctly
|
||||
|
||||
### Key Files for Type System
|
||||
|
||||
- **TypeConcretisation.fs**: Core type concretization logic
|
||||
- `concretizeType`: Main entry point
|
||||
- `concretizeGenericInstantiation`: Handles generic instantiations like `List<T>`
|
||||
- `ConcretizationContext`: Tracks state during concretization
|
||||
|
||||
- **IlMachineState.fs**:
|
||||
- `concretizeMethodForExecution`: Prepares methods for execution
|
||||
- `concretizeFieldForExecution`: Prepares fields for access
|
||||
- Manages the flow of generic contexts through execution
|
||||
|
||||
- **Assembly.fs**:
|
||||
- `resolveTypeRef`: Resolves type references across assemblies
|
||||
- `resolveTypeFromName`: Handles type forwarding and exported types
|
||||
- `resolveTypeFromExport`: Follows type forwarding chains
|
||||
|
||||
### Debugging Type Concretization Issues
|
||||
|
||||
When encountering errors:
|
||||
1. Check the generic context (method name, generic parameters)
|
||||
2. Verify the assembly context being used
|
||||
3. Identify the TypeDefn variant being concretized
|
||||
4. Add logging to see generic contexts: `failwithf "Failed to concretize: %A" typeDefn`
|
||||
5. Check if you're in a generic method calling another generic method
|
||||
6. Verify TypeRefs are being resolved in the correct assembly
|
||||
|
||||
@@ -47,7 +47,7 @@ type DumpedAssembly =
|
||||
TypeDefs :
|
||||
IReadOnlyDictionary<
|
||||
TypeDefinitionHandle,
|
||||
WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
>
|
||||
|
||||
/// <summary>
|
||||
@@ -78,7 +78,8 @@ type DumpedAssembly =
|
||||
/// <summary>
|
||||
/// Dictionary of all field definitions in this assembly, keyed by their handle.
|
||||
/// </summary>
|
||||
Fields : IReadOnlyDictionary<FieldDefinitionHandle, WoofWare.PawPrint.FieldInfo<FakeUnit, TypeDefn>>
|
||||
Fields :
|
||||
IReadOnlyDictionary<FieldDefinitionHandle, WoofWare.PawPrint.FieldInfo<FakeUnit, WoofWare.PawPrint.TypeDefn>>
|
||||
|
||||
/// <summary>
|
||||
/// The entry point method of the assembly, if one exists.
|
||||
@@ -148,7 +149,7 @@ type DumpedAssembly =
|
||||
_TypeDefsLookup :
|
||||
ImmutableDictionary<
|
||||
string * string,
|
||||
WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
>
|
||||
}
|
||||
|
||||
@@ -205,7 +206,7 @@ type DumpedAssembly =
|
||||
static member internal BuildTypeDefsLookup
|
||||
(logger : ILogger)
|
||||
(name : AssemblyName)
|
||||
(typeDefs : WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn> seq)
|
||||
(typeDefs : WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn> seq)
|
||||
=
|
||||
let result = ImmutableDictionary.CreateBuilder ()
|
||||
let keys = HashSet ()
|
||||
@@ -236,7 +237,7 @@ type DumpedAssembly =
|
||||
member this.TypeDef
|
||||
(``namespace`` : string)
|
||||
(name : string)
|
||||
: WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn> option
|
||||
: WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn> option
|
||||
=
|
||||
match this._TypeDefsLookup.TryGetValue ((``namespace``, name)) with
|
||||
| false, _ -> None
|
||||
@@ -251,15 +252,14 @@ type DumpedAssembly =
|
||||
member this.Dispose () = this.PeReader.Dispose ()
|
||||
|
||||
|
||||
type TypeResolutionResult =
|
||||
type TypeResolutionResult<'generic> =
|
||||
| FirstLoadAssy of WoofWare.PawPrint.AssemblyReference
|
||||
| Resolved of DumpedAssembly * TypeInfo<TypeDefn, TypeDefn>
|
||||
| Resolved of DumpedAssembly * TypeInfo<'generic, WoofWare.PawPrint.TypeDefn>
|
||||
|
||||
override this.ToString () : string =
|
||||
match this with
|
||||
| TypeResolutionResult.FirstLoadAssy a -> $"FirstLoadAssy(%s{a.Name.FullName})"
|
||||
| TypeResolutionResult.Resolved (assy, ty) ->
|
||||
$"Resolved(%s{assy.Name.FullName}: {string<TypeInfo<TypeDefn, TypeDefn>> ty})"
|
||||
| TypeResolutionResult.Resolved (assy, ty) -> $"Resolved(%s{assy.Name.FullName}: {ty})"
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module Assembly =
|
||||
@@ -429,52 +429,44 @@ module Assembly =
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(referencedInAssembly : DumpedAssembly)
|
||||
(target : TypeRef)
|
||||
(genericArgs : ImmutableArray<TypeDefn>)
|
||||
: TypeResolutionResult
|
||||
(genericArgs : ImmutableArray<'generic>)
|
||||
: TypeResolutionResult<'generic>
|
||||
=
|
||||
match target.ResolutionScope with
|
||||
| TypeRefResolutionScope.Assembly r ->
|
||||
match referencedInAssembly.AssemblyReferences.TryGetValue r with
|
||||
| false, _ ->
|
||||
failwithf
|
||||
"AssemblyReferenceHandle %A not found in assembly %s. Available references: %A"
|
||||
r
|
||||
referencedInAssembly.Name.FullName
|
||||
(referencedInAssembly.AssemblyReferences.Keys |> Seq.toList)
|
||||
| true, assemblyRef ->
|
||||
|
||||
let assemblyRef = referencedInAssembly.AssemblyReferences.[r]
|
||||
let assemblyName = assemblyRef.Name
|
||||
|
||||
match assemblies.TryGetValue assemblyName.FullName with
|
||||
| false, _ -> TypeResolutionResult.FirstLoadAssy assemblyRef
|
||||
| true, assy ->
|
||||
|
||||
let nsPath = target.Namespace.Split '.' |> Array.toList
|
||||
let nsPath = target.Namespace.Split '.' |> Array.toList
|
||||
|
||||
let targetNs = assy.NonRootNamespaces.[nsPath]
|
||||
let targetNs = assy.NonRootNamespaces.[nsPath]
|
||||
|
||||
let targetType =
|
||||
targetNs.TypeDefinitions
|
||||
|> Seq.choose (fun td ->
|
||||
let ty = assy.TypeDefs.[td]
|
||||
let targetType =
|
||||
targetNs.TypeDefinitions
|
||||
|> Seq.choose (fun td ->
|
||||
let ty = assy.TypeDefs.[td]
|
||||
|
||||
if ty.Name = target.Name && ty.Namespace = target.Namespace then
|
||||
Some ty
|
||||
else
|
||||
None
|
||||
)
|
||||
|> Seq.toList
|
||||
if ty.Name = target.Name && ty.Namespace = target.Namespace then
|
||||
Some ty
|
||||
else
|
||||
None
|
||||
)
|
||||
|> Seq.toList
|
||||
|
||||
match targetType with
|
||||
| [ t ] ->
|
||||
let t = t |> TypeInfo.mapGeneric (fun _ param -> genericArgs.[param.SequenceNumber])
|
||||
match targetType with
|
||||
| [ t ] ->
|
||||
let t = t |> TypeInfo.mapGeneric (fun _ param -> genericArgs.[param.SequenceNumber])
|
||||
|
||||
TypeResolutionResult.Resolved (assy, t)
|
||||
| _ :: _ :: _ -> failwith $"Multiple matching type definitions! {nsPath} {target.Name}"
|
||||
| [] ->
|
||||
match assy.ExportedType (Some target.Namespace) target.Name with
|
||||
| None -> failwith $"Failed to find type {nsPath} {target.Name} in {assy.Name.FullName}!"
|
||||
| Some ty -> resolveTypeFromExport assy assemblies ty genericArgs
|
||||
TypeResolutionResult.Resolved (assy, t)
|
||||
| _ :: _ :: _ -> failwith $"Multiple matching type definitions! {nsPath} {target.Name}"
|
||||
| [] ->
|
||||
match assy.ExportedType (Some target.Namespace) target.Name with
|
||||
| None -> failwith $"Failed to find type {nsPath} {target.Name} in {assy.Name.FullName}!"
|
||||
| Some ty -> resolveTypeFromExport assy assemblies ty genericArgs
|
||||
| k -> failwith $"Unexpected: {k}"
|
||||
|
||||
and resolveTypeFromName
|
||||
@@ -482,8 +474,8 @@ module Assembly =
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(ns : string option)
|
||||
(name : string)
|
||||
(genericArgs : ImmutableArray<TypeDefn>)
|
||||
: TypeResolutionResult
|
||||
(genericArgs : ImmutableArray<'generic>)
|
||||
: TypeResolutionResult<'generic>
|
||||
=
|
||||
match ns with
|
||||
| None -> failwith "what are the semantics here"
|
||||
@@ -510,8 +502,8 @@ module Assembly =
|
||||
(fromAssembly : DumpedAssembly)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(ty : WoofWare.PawPrint.ExportedType)
|
||||
(genericArgs : ImmutableArray<TypeDefn>)
|
||||
: TypeResolutionResult
|
||||
(genericArgs : ImmutableArray<'generic>)
|
||||
: TypeResolutionResult<'generic>
|
||||
=
|
||||
match ty.Data with
|
||||
| NonForwarded _ -> failwith "Somehow didn't find type definition but it is exported"
|
||||
@@ -536,7 +528,7 @@ module DumpedAssembly =
|
||||
| Some (BaseTypeInfo.TypeRef r) ->
|
||||
let assy = loadedAssemblies.[source.FullName]
|
||||
// TODO: generics
|
||||
match Assembly.resolveTypeRef loadedAssemblies assy assy.TypeRefs.[r] ImmutableArray.Empty with
|
||||
match Assembly.resolveTypeRef loadedAssemblies assy assy.TypeRefs.[r] ImmutableArray<unit>.Empty with
|
||||
| TypeResolutionResult.FirstLoadAssy _ ->
|
||||
failwith
|
||||
"seems pretty unlikely that we could have constructed this object without loading its base type"
|
||||
@@ -564,3 +556,249 @@ module DumpedAssembly =
|
||||
| None -> ResolvedBaseType.Object
|
||||
|
||||
go source baseTypeInfo
|
||||
|
||||
// TODO: this is in totally the wrong place, it was just convenient to put it here
|
||||
/// Returns a mapping whose keys are assembly full name * type definition.
|
||||
let concretiseType
|
||||
(mapping : AllConcreteTypes)
|
||||
(baseTypes : BaseClassTypes<'corelib>)
|
||||
(getCorelibAssembly : 'corelib -> AssemblyName)
|
||||
(getTypeInfo :
|
||||
ComparableTypeDefinitionHandle
|
||||
-> AssemblyName
|
||||
-> TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>)
|
||||
(resolveTypeRef : TypeRef -> TypeResolutionResult<'a>)
|
||||
(typeGenerics : (AssemblyName * TypeDefn) ImmutableArray)
|
||||
(methodGenerics : (AssemblyName * TypeDefn) ImmutableArray)
|
||||
(defn : AssemblyName * TypeDefn)
|
||||
: Map<string * TypeDefn, ConcreteTypeHandle> * AllConcreteTypes
|
||||
=
|
||||
// Track types currently being processed to detect cycles
|
||||
let rec concretiseTypeRec
|
||||
(inProgress : Map<string * TypeDefn, ConcreteTypeHandle>)
|
||||
(newlyCreated : Map<string * TypeDefn, ConcreteTypeHandle>)
|
||||
(mapping : AllConcreteTypes)
|
||||
(assy : AssemblyName)
|
||||
(typeDefn : TypeDefn)
|
||||
: ConcreteTypeHandle * Map<string * TypeDefn, ConcreteTypeHandle> * AllConcreteTypes
|
||||
=
|
||||
|
||||
// First check if we're already processing this type (cycle)
|
||||
match inProgress |> Map.tryFind (assy.FullName, typeDefn) with
|
||||
| Some handle -> handle, newlyCreated, mapping
|
||||
| None ->
|
||||
|
||||
// Check if already concretised in this session
|
||||
match newlyCreated |> Map.tryFind (assy.FullName, typeDefn) with
|
||||
| Some handle -> handle, newlyCreated, mapping
|
||||
| None ->
|
||||
|
||||
match typeDefn with
|
||||
| PrimitiveType primitiveType ->
|
||||
let typeInfo =
|
||||
match primitiveType with
|
||||
| PrimitiveType.Boolean -> baseTypes.Boolean
|
||||
| PrimitiveType.Char -> baseTypes.Char
|
||||
| PrimitiveType.SByte -> baseTypes.SByte
|
||||
| PrimitiveType.Byte -> baseTypes.Byte
|
||||
| PrimitiveType.Int16 -> baseTypes.Int16
|
||||
| PrimitiveType.UInt16 -> baseTypes.UInt16
|
||||
| PrimitiveType.Int32 -> baseTypes.Int32
|
||||
| PrimitiveType.UInt32 -> baseTypes.UInt32
|
||||
| PrimitiveType.Int64 -> baseTypes.Int64
|
||||
| PrimitiveType.UInt64 -> baseTypes.UInt64
|
||||
| PrimitiveType.Single -> baseTypes.Single
|
||||
| PrimitiveType.Double -> baseTypes.Double
|
||||
| PrimitiveType.String -> baseTypes.String
|
||||
| PrimitiveType.TypedReference -> failwith "TypedReference not supported in BaseClassTypes"
|
||||
| PrimitiveType.IntPtr -> failwith "IntPtr not supported in BaseClassTypes"
|
||||
| PrimitiveType.UIntPtr -> failwith "UIntPtr not supported in BaseClassTypes"
|
||||
| PrimitiveType.Object -> baseTypes.Object
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
typeInfo.Assembly
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeInfo.TypeDefHandle
|
||||
[]
|
||||
|
||||
let handle, mapping = mapping |> AllConcreteTypes.add concreteType
|
||||
|
||||
handle,
|
||||
newlyCreated
|
||||
|> Map.add ((getCorelibAssembly baseTypes.Corelib).FullName, typeDefn) handle,
|
||||
mapping
|
||||
|
||||
| Void -> failwith "Void is not a real type and cannot be concretised"
|
||||
|
||||
| Array (elt, shape) ->
|
||||
let eltHandle, newlyCreated, mapping =
|
||||
concretiseTypeRec inProgress newlyCreated mapping elt
|
||||
|
||||
let arrayTypeInfo = baseTypes.Array
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
arrayTypeInfo.Assembly
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
arrayTypeInfo.TypeDefHandle
|
||||
[ eltHandle ]
|
||||
|
||||
let handle, mapping = mapping |> AllConcreteTypes.add concreteType
|
||||
handle, newlyCreated |> Map.add typeDefn handle, mapping
|
||||
|
||||
| OneDimensionalArrayLowerBoundZero elements ->
|
||||
let eltHandle, newlyCreated, mapping =
|
||||
concretiseTypeRec inProgress newlyCreated mapping elements
|
||||
|
||||
let arrayTypeInfo = baseTypes.Array
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
arrayTypeInfo.Assembly
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
arrayTypeInfo.TypeDefHandle
|
||||
[ eltHandle ]
|
||||
|
||||
let handle, mapping = mapping |> AllConcreteTypes.add concreteType
|
||||
|
||||
handle,
|
||||
newlyCreated
|
||||
|> Map.add ((getCorelibAssembly baseTypes.Corelib).FullName, typeDefn) handle,
|
||||
mapping
|
||||
|
||||
| Pointer inner -> failwith "Pointer types require special handling - no TypeDefinition available"
|
||||
|
||||
| Byref inner -> failwith "Byref types require special handling - no TypeDefinition available"
|
||||
|
||||
| Pinned inner -> failwith "Pinned types require special handling - no TypeDefinition available"
|
||||
|
||||
| GenericTypeParameter index ->
|
||||
if index < typeGenerics.Length then
|
||||
concretiseTypeRec inProgress newlyCreated mapping typeGenerics.[index]
|
||||
else
|
||||
failwithf "Generic type parameter index %d out of range" index
|
||||
|
||||
| GenericMethodParameter index ->
|
||||
if index < methodGenerics.Length then
|
||||
concretiseTypeRec inProgress newlyCreated mapping methodGenerics.[index]
|
||||
else
|
||||
failwithf "Generic method parameter index %d out of range" index
|
||||
|
||||
| FromDefinition (typeDefHandle, assemblyFullName, _) ->
|
||||
let assemblyName = AssemblyName assemblyFullName
|
||||
let typeInfo = getTypeInfo typeDefHandle assemblyName
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make mapping assemblyName typeInfo.Namespace typeInfo.Name typeDefHandle.Get []
|
||||
|
||||
let handle, mapping = mapping |> AllConcreteTypes.add concreteType
|
||||
handle, newlyCreated |> Map.add (assemblyFullName, typeDefn) handle, mapping
|
||||
|
||||
| FromReference (typeRef, sigKind) ->
|
||||
match resolveTypeRef typeRef with
|
||||
| TypeResolutionResult.FirstLoadAssy assy -> failwith "TODO"
|
||||
| TypeResolutionResult.Resolved (resolvedAssy, typeInfo) ->
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
resolvedAssy.Name
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeInfo.TypeDefHandle
|
||||
[]
|
||||
|
||||
let handle, mapping = mapping |> AllConcreteTypes.add concreteType
|
||||
handle, newlyCreated |> Map.add typeDefn handle, mapping
|
||||
|
||||
| GenericInstantiation (genericDef, args) ->
|
||||
// This is the tricky case - we might have self-reference
|
||||
// First, allocate a handle for this type
|
||||
let tempHandle = ConcreteTypeHandle mapping.NextHandle
|
||||
|
||||
let mapping =
|
||||
{ mapping with
|
||||
NextHandle = mapping.NextHandle + 1
|
||||
}
|
||||
|
||||
let inProgress = inProgress |> Map.add typeDefn tempHandle
|
||||
|
||||
// Concretise all type arguments first
|
||||
let rec concretiseArgs
|
||||
(acc : ConcreteTypeHandle list)
|
||||
(newlyCreated : Map<TypeDefn, ConcreteTypeHandle>)
|
||||
(mapping : AllConcreteTypes)
|
||||
(args : TypeDefn list)
|
||||
: ConcreteTypeHandle list * Map<TypeDefn, ConcreteTypeHandle> * AllConcreteTypes
|
||||
=
|
||||
match args with
|
||||
| [] -> List.rev acc, newlyCreated, mapping
|
||||
| arg :: rest ->
|
||||
let argHandle, newlyCreated, mapping =
|
||||
concretiseTypeRec inProgress newlyCreated mapping arg
|
||||
|
||||
concretiseArgs (argHandle :: acc) newlyCreated mapping rest
|
||||
|
||||
let argHandles, newlyCreated, mapping =
|
||||
concretiseArgs [] newlyCreated mapping (args |> Seq.toList)
|
||||
|
||||
// Now extract the definition from the generic def
|
||||
match genericDef with
|
||||
| FromDefinition (typeDefHandle, assemblyFullName, _) ->
|
||||
let assemblyName = AssemblyName (assemblyFullName)
|
||||
let typeInfo = getTypeInfo typeDefHandle assemblyName
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
assemblyName
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeDefHandle.Get
|
||||
argHandles
|
||||
// Update the pre-allocated entry
|
||||
let mapping =
|
||||
{ mapping with
|
||||
Mapping = mapping.Mapping |> Map.add tempHandle concreteType
|
||||
}
|
||||
|
||||
tempHandle, newlyCreated |> Map.add typeDefn tempHandle, mapping
|
||||
|
||||
| FromReference (typeRef, _) ->
|
||||
match resolveTypeRef typeRef with
|
||||
| TypeResolutionResult.FirstLoadAssy _ -> failwith "TODO"
|
||||
| TypeResolutionResult.Resolved (resolvedAssy, typeInfo) ->
|
||||
|
||||
let cth, concreteType, mapping =
|
||||
ConcreteType.make
|
||||
mapping
|
||||
resolvedAssy.Name
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeInfo.TypeDefHandle
|
||||
argHandles
|
||||
|
||||
let mapping =
|
||||
{ mapping with
|
||||
Mapping = mapping.Mapping |> Map.add tempHandle concreteType
|
||||
}
|
||||
|
||||
tempHandle, newlyCreated |> Map.add typeDefn tempHandle, mapping
|
||||
|
||||
| _ -> failwithf "Generic instantiation of non-definition type: %A" genericDef
|
||||
|
||||
| Modified (original, afterMod, required) ->
|
||||
failwith "Modified types require special handling - not yet implemented"
|
||||
|
||||
| FunctionPointer _ -> failwith "Function pointer concretisation not implemented"
|
||||
|
||||
let _, newlyCreated, finalMapping =
|
||||
concretiseTypeRec Map.empty Map.empty mapping (fst defn) (snd defn)
|
||||
|
||||
newlyCreated, finalMapping
|
||||
|
||||
@@ -11,7 +11,7 @@ type ComparableTypeDefinitionHandle =
|
||||
_Inner : TypeDefinitionHandle
|
||||
}
|
||||
|
||||
override this.Equals (other) =
|
||||
override this.Equals other =
|
||||
match other with
|
||||
| :? ComparableTypeDefinitionHandle as other -> this._Inner.GetHashCode () = other._Inner.GetHashCode ()
|
||||
| _ -> false
|
||||
|
||||
@@ -20,16 +20,10 @@ module FakeUnit =
|
||||
type ConcreteType<'typeGeneric when 'typeGeneric : comparison and 'typeGeneric :> IComparable<'typeGeneric>> =
|
||||
private
|
||||
{
|
||||
/// Do not use this, because it's intended to be private; use the accessor `.Assembly : AssemblyName`
|
||||
/// instead.
|
||||
_AssemblyName : AssemblyName
|
||||
/// Do not use this, because it's intended to be private; use the accessor `.Definition` instead.
|
||||
_Definition : ComparableTypeDefinitionHandle
|
||||
/// Do not use this, because it's intended to be private; use the accessor `.Name` instead.
|
||||
_Name : string
|
||||
/// Do not use this, because it's intended to be private; use the accessor `.Namespace` instead.
|
||||
_Namespace : string
|
||||
/// Do not use this, because it's intended to be private; use the accessor `.Generics` instead.
|
||||
_Name : string
|
||||
_Generics : 'typeGeneric list
|
||||
}
|
||||
|
||||
@@ -54,19 +48,17 @@ type ConcreteType<'typeGeneric when 'typeGeneric : comparison and 'typeGeneric :
|
||||
member this.CompareTo (other : ConcreteType<'typeGeneric>) : int =
|
||||
let comp = this._AssemblyName.FullName.CompareTo other._AssemblyName.FullName
|
||||
|
||||
if comp <> 0 then
|
||||
comp
|
||||
if comp = 0 then
|
||||
let comp =
|
||||
(this._Definition :> IComparable<ComparableTypeDefinitionHandle>).CompareTo other._Definition
|
||||
|
||||
if comp = 0 then
|
||||
let thisGen = (this._Generics : 'typeGeneric list) :> IComparable<'typeGeneric list>
|
||||
thisGen.CompareTo other._Generics
|
||||
else
|
||||
comp
|
||||
else
|
||||
|
||||
let comp =
|
||||
(this._Definition :> IComparable<ComparableTypeDefinitionHandle>).CompareTo other._Definition
|
||||
|
||||
if comp <> 0 then
|
||||
comp
|
||||
else
|
||||
|
||||
let thisGen = (this._Generics : 'typeGeneric list) :> IComparable<'typeGeneric list>
|
||||
thisGen.CompareTo other._Generics
|
||||
|
||||
interface IComparable with
|
||||
member this.CompareTo other =
|
||||
@@ -75,23 +67,64 @@ type ConcreteType<'typeGeneric when 'typeGeneric : comparison and 'typeGeneric :
|
||||
(this :> IComparable<ConcreteType<'typeGeneric>>).CompareTo other
|
||||
| _ -> failwith "bad comparison"
|
||||
|
||||
/// Because a runtime type may depend on itself by some chain of generics, we need to break the indirection;
|
||||
/// we do so by storing all concrete types in some global mapping and then referring to them only by handle.
|
||||
type ConcreteTypeHandle = | ConcreteTypeHandle of int
|
||||
|
||||
type AllConcreteTypes =
|
||||
{
|
||||
Mapping : Map<ConcreteTypeHandle, ConcreteType<ConcreteTypeHandle>>
|
||||
NextHandle : int
|
||||
}
|
||||
|
||||
static member Empty =
|
||||
{
|
||||
Mapping = Map.empty
|
||||
NextHandle = 0
|
||||
}
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module AllConcreteTypes =
|
||||
let lookup (cth : ConcreteTypeHandle) (this : AllConcreteTypes) : ConcreteType<ConcreteTypeHandle> option =
|
||||
this.Mapping |> Map.tryFind cth
|
||||
|
||||
let lookup' (ct : ConcreteType<ConcreteTypeHandle>) (this : AllConcreteTypes) : ConcreteTypeHandle option =
|
||||
failwith "TODO"
|
||||
|
||||
/// `source` is AssemblyName * Namespace * Name
|
||||
let add (ct : ConcreteType<ConcreteTypeHandle>) (this : AllConcreteTypes) : ConcreteTypeHandle * AllConcreteTypes =
|
||||
let toRet = ConcreteTypeHandle this.NextHandle
|
||||
|
||||
let newState =
|
||||
{
|
||||
NextHandle = this.NextHandle + 1
|
||||
Mapping = this.Mapping |> Map.add toRet ct
|
||||
}
|
||||
|
||||
toRet, newState
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module ConcreteType =
|
||||
let make
|
||||
(mapping : AllConcreteTypes)
|
||||
(assemblyName : AssemblyName)
|
||||
(ns : string)
|
||||
(name : string)
|
||||
(defn : TypeDefinitionHandle)
|
||||
(generics : TypeDefn list)
|
||||
: ConcreteType<TypeDefn>
|
||||
(generics : ConcreteTypeHandle list)
|
||||
: ConcreteTypeHandle * ConcreteType<_> * AllConcreteTypes
|
||||
=
|
||||
{
|
||||
_AssemblyName = assemblyName
|
||||
_Definition = ComparableTypeDefinitionHandle.Make defn
|
||||
_Name = name
|
||||
_Namespace = ns
|
||||
_Generics = generics
|
||||
}
|
||||
let toAdd =
|
||||
{
|
||||
_AssemblyName = assemblyName
|
||||
_Definition = ComparableTypeDefinitionHandle.Make defn
|
||||
_Name = name
|
||||
_Namespace = ns
|
||||
_Generics = generics
|
||||
}
|
||||
|
||||
let added, mapping = AllConcreteTypes.add toAdd mapping
|
||||
added, toAdd, mapping
|
||||
|
||||
let make'
|
||||
(assemblyName : AssemblyName)
|
||||
@@ -104,8 +137,8 @@ module ConcreteType =
|
||||
{
|
||||
_AssemblyName = assemblyName
|
||||
_Definition = ComparableTypeDefinitionHandle.Make defn
|
||||
_Name = name
|
||||
_Namespace = ns
|
||||
_Name = name
|
||||
_Generics = List.replicate genericParamCount FakeUnit.FakeUnit
|
||||
}
|
||||
|
||||
@@ -121,6 +154,6 @@ module ConcreteType =
|
||||
_AssemblyName = x._AssemblyName
|
||||
_Definition = x._Definition
|
||||
_Generics = generics
|
||||
_Name = x._Name
|
||||
_Namespace = x._Namespace
|
||||
_Name = x._Name
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ open System.Reflection.Metadata
|
||||
/// Represents detailed information about a field in a .NET assembly.
|
||||
/// This is a strongly-typed representation of FieldDefinition from System.Reflection.Metadata.
|
||||
/// </summary>
|
||||
type FieldInfo<'typeGeneric, 'fieldGeneric when 'typeGeneric : comparison and 'typeGeneric :> IComparable<'typeGeneric>>
|
||||
=
|
||||
type FieldInfo<'typeGeneric, 'sigGeneric when 'typeGeneric : comparison and 'typeGeneric :> IComparable<'typeGeneric>> =
|
||||
{
|
||||
/// <summary>
|
||||
/// The metadata token handle that uniquely identifies this field in the assembly.
|
||||
@@ -27,7 +26,7 @@ type FieldInfo<'typeGeneric, 'fieldGeneric when 'typeGeneric : comparison and 't
|
||||
/// <summary>
|
||||
/// The type of the field.
|
||||
/// </summary>
|
||||
Signature : 'fieldGeneric
|
||||
Signature : 'sigGeneric
|
||||
|
||||
/// <summary>
|
||||
/// The attributes applied to this field, including visibility, static/instance,
|
||||
@@ -67,11 +66,11 @@ module FieldInfo =
|
||||
Attributes = def.Attributes
|
||||
}
|
||||
|
||||
let mapTypeGenerics<'a, 'b, 'field
|
||||
let mapTypeGenerics<'a, 'b, 'sigGen
|
||||
when 'a :> IComparable<'a> and 'a : comparison and 'b :> IComparable<'b> and 'b : comparison>
|
||||
(f : int -> 'a -> 'b)
|
||||
(input : FieldInfo<'a, 'field>)
|
||||
: FieldInfo<'b, 'field>
|
||||
(input : FieldInfo<'a, 'sigGen>)
|
||||
: FieldInfo<'b, 'sigGen>
|
||||
=
|
||||
let declaringType = input.DeclaringType |> ConcreteType.mapGeneric f
|
||||
|
||||
@@ -81,5 +80,23 @@ module FieldInfo =
|
||||
DeclaringType = declaringType
|
||||
Signature = input.Signature
|
||||
Attributes = input.Attributes
|
||||
|
||||
}
|
||||
|
||||
let mapSigGenerics<'a, 'b, 'state, 'typeGen when 'typeGen :> IComparable<'typeGen> and 'typeGen : comparison>
|
||||
(state : 'state)
|
||||
(f : 'state -> 'a -> 'state * 'b)
|
||||
(input : FieldInfo<'typeGen, 'a>)
|
||||
: FieldInfo<'typeGen, 'b> * 'state
|
||||
=
|
||||
let state, signature = f state input.Signature
|
||||
|
||||
let ret =
|
||||
{
|
||||
Handle = input.Handle
|
||||
Name = input.Name
|
||||
DeclaringType = input.DeclaringType
|
||||
Signature = signature
|
||||
Attributes = input.Attributes
|
||||
}
|
||||
|
||||
ret, state
|
||||
|
||||
@@ -78,9 +78,6 @@ type NullaryIlOp =
|
||||
| Not
|
||||
| Shr
|
||||
| Shr_un
|
||||
/// Shifts an integer value to the left (in zeroes) by a specified number of bits, pushing the result onto the evaluation stack.
|
||||
/// Top of stack is number of bits to be shifted.
|
||||
/// Inserts a zero bit in the lowest positions.
|
||||
| Shl
|
||||
| Conv_ovf_i
|
||||
| Conv_ovf_u
|
||||
|
||||
@@ -117,7 +117,7 @@ type ExceptionRegion =
|
||||
| ExceptionRegionKind.Fault -> ExceptionRegion.Fault offset
|
||||
| _ -> raise (ArgumentOutOfRangeException ())
|
||||
|
||||
type MethodInstructions<'methodVars> =
|
||||
type MethodInstructions<'methodVar> =
|
||||
{
|
||||
/// <summary>
|
||||
/// The IL instructions that compose the method body, along with their offset positions.
|
||||
@@ -137,14 +137,14 @@ type MethodInstructions<'methodVars> =
|
||||
/// </summary>
|
||||
LocalsInit : bool
|
||||
|
||||
LocalVars : ImmutableArray<'methodVars> option
|
||||
LocalVars : ImmutableArray<'methodVar> option
|
||||
|
||||
ExceptionRegions : ImmutableArray<ExceptionRegion>
|
||||
}
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module MethodInstructions =
|
||||
let onlyRet () : MethodInstructions<'methodVars> =
|
||||
let onlyRet<'a> () : MethodInstructions<'a> =
|
||||
let op = IlOp.Nullary NullaryIlOp.Ret
|
||||
|
||||
{
|
||||
@@ -155,14 +155,36 @@ module MethodInstructions =
|
||||
ExceptionRegions = ImmutableArray.Empty
|
||||
}
|
||||
|
||||
let setLocalVars<'a, 'b> (v : ImmutableArray<'b> option) (s : MethodInstructions<'a>) : MethodInstructions<'b> =
|
||||
{
|
||||
Instructions = s.Instructions
|
||||
Locations = s.Locations
|
||||
LocalsInit = s.LocalsInit
|
||||
LocalVars = v
|
||||
ExceptionRegions = s.ExceptionRegions
|
||||
}
|
||||
let map<'a, 'b, 'state>
|
||||
(state : 'state)
|
||||
(f : 'state -> 'a -> 'b * 'state)
|
||||
(i : MethodInstructions<'a>)
|
||||
: MethodInstructions<'b> * 'state
|
||||
=
|
||||
let vars, state =
|
||||
match i.LocalVars with
|
||||
| None -> None, state
|
||||
| Some v ->
|
||||
let result = ImmutableArray.CreateBuilder v.Length
|
||||
let mutable state = state
|
||||
|
||||
for i = 0 to v.Length - 1 do
|
||||
let res, state' = f state v.[i]
|
||||
state <- state'
|
||||
result.Add res
|
||||
|
||||
Some (result.ToImmutable ()), state
|
||||
|
||||
let result =
|
||||
{
|
||||
Instructions = i.Instructions
|
||||
Locations = i.Locations
|
||||
LocalsInit = i.LocalsInit
|
||||
LocalVars = vars
|
||||
ExceptionRegions = i.ExceptionRegions
|
||||
}
|
||||
|
||||
result, state
|
||||
|
||||
/// <summary>
|
||||
/// Represents detailed information about a method in a .NET assembly.
|
||||
@@ -207,7 +229,8 @@ type MethodInfo<'typeGenerics, 'methodGenerics, 'methodVars
|
||||
Signature : TypeMethodSignature<'methodVars>
|
||||
|
||||
/// <summary>
|
||||
/// The signature as it was read from assembly metadata.
|
||||
/// The signature of the method, including return type and parameter types, as read directly from metadata
|
||||
/// (not made concrete in a running instance of the program).
|
||||
/// </summary>
|
||||
RawSignature : TypeMethodSignature<TypeDefn>
|
||||
|
||||
@@ -242,12 +265,9 @@ type MethodInfo<'typeGenerics, 'methodGenerics, 'methodVars
|
||||
member this.IsPinvokeImpl : bool =
|
||||
this.MethodAttributes.HasFlag MethodAttributes.PinvokeImpl
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module MethodInfo =
|
||||
let isJITIntrinsic
|
||||
member this.IsJITIntrinsic<'a, 'b, 'c when 'a :> IComparable<'a> and 'a : comparison>
|
||||
(getMemberRefParentType : MemberReferenceHandle -> TypeRef)
|
||||
(methodDefs : IReadOnlyDictionary<MethodDefinitionHandle, MethodInfo<'a, 'b, 'c>>)
|
||||
(this : MethodInfo<'d, 'e, 'f>)
|
||||
: bool
|
||||
=
|
||||
this.CustomAttributes
|
||||
@@ -267,11 +287,13 @@ module MethodInfo =
|
||||
| con -> failwith $"TODO: {con}"
|
||||
)
|
||||
|
||||
let mapTypeGenerics<'a, 'b, 'methodGen, 'vars
|
||||
[<RequireQualifiedAccess>]
|
||||
module MethodInfo =
|
||||
let mapTypeGenerics<'a, 'b, 'methodGen, 'methodVars
|
||||
when 'a :> IComparable<'a> and 'a : comparison and 'b : comparison and 'b :> IComparable<'b>>
|
||||
(f : int -> 'a -> 'b)
|
||||
(m : MethodInfo<'a, 'methodGen, 'vars>)
|
||||
: MethodInfo<'b, 'methodGen, 'vars>
|
||||
(m : MethodInfo<'a, 'methodGen, 'methodVars>)
|
||||
: MethodInfo<'b, 'methodGen, 'methodVars>
|
||||
=
|
||||
{
|
||||
DeclaringType = m.DeclaringType |> ConcreteType.mapGeneric f
|
||||
@@ -281,17 +303,17 @@ module MethodInfo =
|
||||
Parameters = m.Parameters
|
||||
Generics = m.Generics
|
||||
Signature = m.Signature
|
||||
RawSignature = m.RawSignature
|
||||
CustomAttributes = m.CustomAttributes
|
||||
MethodAttributes = m.MethodAttributes
|
||||
ImplAttributes = m.ImplAttributes
|
||||
IsStatic = m.IsStatic
|
||||
RawSignature = m.RawSignature
|
||||
}
|
||||
|
||||
let mapMethodGenerics<'a, 'b, 'vars, 'typeGen when 'typeGen :> IComparable<'typeGen> and 'typeGen : comparison>
|
||||
let mapMethodGenerics<'a, 'b, 'typeGen, 'methodVars when 'typeGen :> IComparable<'typeGen> and 'typeGen : comparison>
|
||||
(f : int -> 'a -> 'b)
|
||||
(m : MethodInfo<'typeGen, 'a, 'vars>)
|
||||
: MethodInfo<'typeGen, 'b, 'vars>
|
||||
(m : MethodInfo<'typeGen, 'a, 'methodVars>)
|
||||
: MethodInfo<'typeGen, 'b, 'methodVars>
|
||||
=
|
||||
{
|
||||
DeclaringType = m.DeclaringType
|
||||
@@ -301,33 +323,46 @@ module MethodInfo =
|
||||
Parameters = m.Parameters
|
||||
Generics = m.Generics |> Seq.mapi f |> ImmutableArray.CreateRange
|
||||
Signature = m.Signature
|
||||
RawSignature = m.RawSignature
|
||||
CustomAttributes = m.CustomAttributes
|
||||
MethodAttributes = m.MethodAttributes
|
||||
ImplAttributes = m.ImplAttributes
|
||||
IsStatic = m.IsStatic
|
||||
RawSignature = m.RawSignature
|
||||
}
|
||||
|
||||
let setMethodVars
|
||||
(vars2 : MethodInstructions<'vars2> option)
|
||||
(signature : TypeMethodSignature<'vars2>)
|
||||
(m : MethodInfo<'typeGen, 'methodGen, 'vars1>)
|
||||
: MethodInfo<'typeGen, 'methodGen, 'vars2>
|
||||
let mapVarGenerics<'a, 'b, 'state, 'typeGen, 'methodGen
|
||||
when 'typeGen :> IComparable<'typeGen> and 'typeGen : comparison>
|
||||
(state : 'state)
|
||||
(f : 'state -> 'a -> 'b * 'state)
|
||||
(m : MethodInfo<'typeGen, 'methodGen, 'a>)
|
||||
: MethodInfo<'typeGen, 'methodGen, 'b> * 'state
|
||||
=
|
||||
{
|
||||
DeclaringType = m.DeclaringType
|
||||
Handle = m.Handle
|
||||
Name = m.Name
|
||||
Instructions = vars2
|
||||
Parameters = m.Parameters
|
||||
Generics = m.Generics
|
||||
Signature = signature
|
||||
RawSignature = m.RawSignature
|
||||
CustomAttributes = m.CustomAttributes
|
||||
MethodAttributes = m.MethodAttributes
|
||||
ImplAttributes = m.ImplAttributes
|
||||
IsStatic = m.IsStatic
|
||||
}
|
||||
let instructions, state =
|
||||
match m.Instructions with
|
||||
| None -> None, state
|
||||
| Some i ->
|
||||
let result, state = MethodInstructions.map state f i
|
||||
Some result, state
|
||||
|
||||
let signature, state = m.Signature |> TypeMethodSignature.map f state
|
||||
|
||||
let result =
|
||||
{
|
||||
DeclaringType = m.DeclaringType
|
||||
Handle = m.Handle
|
||||
Name = m.Name
|
||||
Instructions = instructions
|
||||
Parameters = m.Parameters
|
||||
Generics = m.Generics
|
||||
Signature = signature
|
||||
CustomAttributes = m.CustomAttributes
|
||||
MethodAttributes = m.MethodAttributes
|
||||
ImplAttributes = m.ImplAttributes
|
||||
IsStatic = m.IsStatic
|
||||
RawSignature = m.RawSignature
|
||||
}
|
||||
|
||||
result, state
|
||||
|
||||
type private Dummy = class end
|
||||
|
||||
@@ -753,17 +788,17 @@ module MethodInfo =
|
||||
Parameters = methodParams
|
||||
Generics = methodGenericParams
|
||||
Signature = typeSig
|
||||
RawSignature = typeSig
|
||||
MethodAttributes = methodDef.Attributes
|
||||
CustomAttributes = attrs
|
||||
IsStatic = not methodSig.Header.IsInstance
|
||||
ImplAttributes = implAttrs
|
||||
RawSignature = typeSig
|
||||
}
|
||||
|> Some
|
||||
|
||||
let rec resolveBaseType
|
||||
(methodGenerics : TypeDefn ImmutableArray option)
|
||||
(executingMethod : MethodInfo<TypeDefn, 'methodGen, 'vars>)
|
||||
(executingMethod : MethodInfo<TypeDefn, 'methodGen, 'methodVars>)
|
||||
(td : TypeDefn)
|
||||
: ResolvedBaseType
|
||||
=
|
||||
|
||||
@@ -15,17 +15,6 @@ type MethodSpec =
|
||||
/// </summary>
|
||||
Method : MetadataToken
|
||||
|
||||
/// <summary>
|
||||
/// The actual type arguments for generic instantiation.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// For <c>Volatile.Read<System.IO.TextWriter></c>, the <c>Signature</c> is <c>[System.IO.TextWriter]</c>.
|
||||
/// </example>
|
||||
/// <remarks>
|
||||
/// The contents might themselves be <c>TypeDefn.GenericMethodParameter</c>, for example.
|
||||
/// This happens when the method is itself being called from within a generic method, and the generic parameters
|
||||
/// of the spec are being instantiated with generic parameters from the caller.
|
||||
/// </remarks>
|
||||
Signature : TypeDefn ImmutableArray
|
||||
}
|
||||
|
||||
|
||||
@@ -1,900 +0,0 @@
|
||||
namespace WoofWare.PawPrint
|
||||
|
||||
open System.Collections.Immutable
|
||||
open System.Reflection
|
||||
open System.Reflection.Metadata
|
||||
|
||||
type ConcreteTypeHandle =
|
||||
| Concrete of int
|
||||
| Byref of ConcreteTypeHandle
|
||||
| Pointer of ConcreteTypeHandle
|
||||
|
||||
type AllConcreteTypes =
|
||||
{
|
||||
Mapping : Map<int, ConcreteType<ConcreteTypeHandle>>
|
||||
NextHandle : int
|
||||
}
|
||||
|
||||
static member Empty =
|
||||
{
|
||||
Mapping = Map.empty
|
||||
NextHandle = 0
|
||||
}
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module AllConcreteTypes =
|
||||
let lookup (cth : ConcreteTypeHandle) (this : AllConcreteTypes) : ConcreteType<ConcreteTypeHandle> option =
|
||||
match cth with
|
||||
| ConcreteTypeHandle.Concrete id -> this.Mapping |> Map.tryFind id
|
||||
| ConcreteTypeHandle.Byref _ -> None // Byref types are not stored in the mapping
|
||||
| ConcreteTypeHandle.Pointer _ -> None // Pointer types are not stored in the mapping
|
||||
|
||||
let lookup' (ct : ConcreteType<ConcreteTypeHandle>) (this : AllConcreteTypes) : ConcreteTypeHandle option =
|
||||
this.Mapping
|
||||
|> Map.tryPick (fun id existingCt ->
|
||||
if
|
||||
existingCt._AssemblyName = ct._AssemblyName
|
||||
&& existingCt._Namespace = ct._Namespace
|
||||
&& existingCt._Name = ct._Name
|
||||
&& existingCt._Definition = ct._Definition
|
||||
&& existingCt._Generics = ct._Generics
|
||||
then
|
||||
Some (ConcreteTypeHandle.Concrete id)
|
||||
else
|
||||
None
|
||||
)
|
||||
|
||||
let findExistingConcreteType
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(asm : AssemblyName, ns : string, name : string, generics : ConcreteTypeHandle list as key)
|
||||
: ConcreteTypeHandle option
|
||||
=
|
||||
concreteTypes.Mapping
|
||||
|> Map.tryPick (fun id ct ->
|
||||
if
|
||||
ct.Assembly.FullName = asm.FullName
|
||||
&& ct.Namespace = ns
|
||||
&& ct.Name = name
|
||||
&& ct.Generics = generics
|
||||
then
|
||||
Some (ConcreteTypeHandle.Concrete id)
|
||||
else
|
||||
None
|
||||
)
|
||||
|
||||
/// `source` is AssemblyName * Namespace * Name
|
||||
let add (ct : ConcreteType<ConcreteTypeHandle>) (this : AllConcreteTypes) : ConcreteTypeHandle * AllConcreteTypes =
|
||||
let id = this.NextHandle
|
||||
let toRet = ConcreteTypeHandle.Concrete id
|
||||
|
||||
let newState =
|
||||
{
|
||||
NextHandle = this.NextHandle + 1
|
||||
Mapping = this.Mapping |> Map.add id ct
|
||||
}
|
||||
|
||||
toRet, newState
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module TypeConcretization =
|
||||
|
||||
type ConcretizationContext =
|
||||
{
|
||||
/// Types currently being processed (to detect cycles)
|
||||
InProgress : ImmutableDictionary<AssemblyName * TypeDefn, ConcreteTypeHandle>
|
||||
/// All concrete types created so far
|
||||
ConcreteTypes : AllConcreteTypes
|
||||
/// For resolving type references
|
||||
LoadedAssemblies : ImmutableDictionary<string, DumpedAssembly>
|
||||
BaseTypes : BaseClassTypes<DumpedAssembly>
|
||||
}
|
||||
|
||||
// Helper function to find existing types by assembly, namespace, name, and generics
|
||||
let private findExistingType
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(assembly : AssemblyName)
|
||||
(ns : string)
|
||||
(name : string)
|
||||
(generics : ConcreteTypeHandle list)
|
||||
: ConcreteTypeHandle option
|
||||
=
|
||||
concreteTypes.Mapping
|
||||
|> Map.tryPick (fun id ct ->
|
||||
if
|
||||
ct.Assembly.FullName = assembly.FullName
|
||||
&& ct.Namespace = ns
|
||||
&& ct.Name = name
|
||||
&& ct.Generics = generics
|
||||
then
|
||||
Some (ConcreteTypeHandle.Concrete id)
|
||||
else
|
||||
None
|
||||
)
|
||||
|
||||
// Helper function for primitive types (convenience wrapper)
|
||||
let private findExistingPrimitiveType
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(key : AssemblyName * string * string)
|
||||
: ConcreteTypeHandle option
|
||||
=
|
||||
let (asm, ns, name) = key
|
||||
findExistingType concreteTypes asm ns name []
|
||||
|
||||
// Helper function to create and add a ConcreteType to the context
|
||||
let private createAndAddConcreteType
|
||||
(ctx : ConcretizationContext)
|
||||
(assembly : AssemblyName)
|
||||
(definition : ComparableTypeDefinitionHandle)
|
||||
(ns : string)
|
||||
(name : string)
|
||||
(generics : ConcreteTypeHandle list)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
let concreteType =
|
||||
{
|
||||
_AssemblyName = assembly
|
||||
_Definition = definition
|
||||
_Namespace = ns
|
||||
_Name = name
|
||||
_Generics = generics
|
||||
}
|
||||
|
||||
let handle, newConcreteTypes = AllConcreteTypes.add concreteType ctx.ConcreteTypes
|
||||
|
||||
let newCtx =
|
||||
{ ctx with
|
||||
ConcreteTypes = newConcreteTypes
|
||||
}
|
||||
|
||||
handle, newCtx
|
||||
|
||||
// Helper function for assembly loading with retry pattern
|
||||
let private loadAssemblyAndResolveTypeRef
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly)
|
||||
(ctx : ConcretizationContext)
|
||||
(currentAssembly : AssemblyName)
|
||||
(typeRef : TypeRef)
|
||||
: (DumpedAssembly * WoofWare.PawPrint.TypeInfo<_, _>) * ConcretizationContext
|
||||
=
|
||||
let currentAssy =
|
||||
match ctx.LoadedAssemblies.TryGetValue currentAssembly.FullName with
|
||||
| false, _ -> failwithf "Current assembly %s not loaded" currentAssembly.FullName
|
||||
| true, assy -> assy
|
||||
|
||||
// First try to resolve without loading new assemblies
|
||||
let resolutionResult =
|
||||
Assembly.resolveTypeRef ctx.LoadedAssemblies currentAssy typeRef ImmutableArray.Empty
|
||||
|
||||
match resolutionResult with
|
||||
| TypeResolutionResult.Resolved (targetAssy, typeInfo) -> (targetAssy, typeInfo), ctx
|
||||
| TypeResolutionResult.FirstLoadAssy assemblyRef ->
|
||||
// Need to load the assembly
|
||||
match typeRef.ResolutionScope with
|
||||
| TypeRefResolutionScope.Assembly assyRef ->
|
||||
let newAssemblies, loadedAssy = loadAssembly currentAssembly assyRef
|
||||
|
||||
let newCtx =
|
||||
{ ctx with
|
||||
LoadedAssemblies = newAssemblies
|
||||
}
|
||||
|
||||
// Now try to resolve again with the loaded assembly
|
||||
let resolutionResult2 =
|
||||
Assembly.resolveTypeRef newCtx.LoadedAssemblies currentAssy typeRef ImmutableArray.Empty
|
||||
|
||||
match resolutionResult2 with
|
||||
| TypeResolutionResult.Resolved (targetAssy, typeInfo) -> (targetAssy, typeInfo), newCtx
|
||||
| TypeResolutionResult.FirstLoadAssy _ ->
|
||||
failwithf "Failed to resolve type %s.%s after loading assembly" typeRef.Namespace typeRef.Name
|
||||
| _ -> failwith "Unexpected resolution scope"
|
||||
|
||||
let private concretizePrimitive
|
||||
(ctx : ConcretizationContext)
|
||||
(prim : PrimitiveType)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
|
||||
// Get the TypeInfo for this primitive from BaseClassTypes
|
||||
let typeInfo =
|
||||
match prim with
|
||||
| PrimitiveType.Boolean -> ctx.BaseTypes.Boolean
|
||||
| PrimitiveType.Char -> ctx.BaseTypes.Char
|
||||
| PrimitiveType.SByte -> ctx.BaseTypes.SByte
|
||||
| PrimitiveType.Byte -> ctx.BaseTypes.Byte
|
||||
| PrimitiveType.Int16 -> ctx.BaseTypes.Int16
|
||||
| PrimitiveType.UInt16 -> ctx.BaseTypes.UInt16
|
||||
| PrimitiveType.Int32 -> ctx.BaseTypes.Int32
|
||||
| PrimitiveType.UInt32 -> ctx.BaseTypes.UInt32
|
||||
| PrimitiveType.Int64 -> ctx.BaseTypes.Int64
|
||||
| PrimitiveType.UInt64 -> ctx.BaseTypes.UInt64
|
||||
| PrimitiveType.Single -> ctx.BaseTypes.Single
|
||||
| PrimitiveType.Double -> ctx.BaseTypes.Double
|
||||
| PrimitiveType.String -> ctx.BaseTypes.String
|
||||
| PrimitiveType.Object -> ctx.BaseTypes.Object
|
||||
| PrimitiveType.TypedReference -> ctx.BaseTypes.TypedReference
|
||||
| PrimitiveType.IntPtr -> ctx.BaseTypes.IntPtr
|
||||
| PrimitiveType.UIntPtr -> ctx.BaseTypes.UIntPtr
|
||||
|
||||
// Check if we've already concretized this primitive type
|
||||
let key = (typeInfo.Assembly, typeInfo.Namespace, typeInfo.Name)
|
||||
|
||||
match findExistingPrimitiveType ctx.ConcreteTypes key with
|
||||
| Some handle -> handle, ctx
|
||||
| None ->
|
||||
// Create and add the concrete type (primitives have no generic arguments)
|
||||
createAndAddConcreteType
|
||||
ctx
|
||||
typeInfo.Assembly
|
||||
(ComparableTypeDefinitionHandle.Make typeInfo.TypeDefHandle)
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
[] // Primitives have no generic parameters
|
||||
|
||||
let private concretizeArray
|
||||
(ctx : ConcretizationContext)
|
||||
(elementHandle : ConcreteTypeHandle)
|
||||
(shape : 'a)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
|
||||
// Arrays are System.Array<T> where T is the element type
|
||||
let arrayTypeInfo = ctx.BaseTypes.Array
|
||||
|
||||
// Check if we've already concretized this array type
|
||||
match
|
||||
findExistingType
|
||||
ctx.ConcreteTypes
|
||||
arrayTypeInfo.Assembly
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
[ elementHandle ]
|
||||
with
|
||||
| Some handle -> handle, ctx
|
||||
| None ->
|
||||
// Create and add the concrete array type
|
||||
createAndAddConcreteType
|
||||
ctx
|
||||
arrayTypeInfo.Assembly
|
||||
(ComparableTypeDefinitionHandle.Make arrayTypeInfo.TypeDefHandle)
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
[ elementHandle ] // Array<T> has one generic parameter
|
||||
|
||||
let private concretizeOneDimArray
|
||||
(ctx : ConcretizationContext)
|
||||
(elementHandle : ConcreteTypeHandle)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
|
||||
// One-dimensional arrays with lower bound 0 are also System.Array<T>
|
||||
// They just have different IL instructions for access
|
||||
let arrayTypeInfo = ctx.BaseTypes.Array
|
||||
|
||||
// Check if we've already concretized this array type
|
||||
match
|
||||
findExistingType
|
||||
ctx.ConcreteTypes
|
||||
arrayTypeInfo.Assembly
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
[ elementHandle ]
|
||||
with
|
||||
| Some handle -> handle, ctx
|
||||
| None ->
|
||||
// Create and add the concrete array type
|
||||
createAndAddConcreteType
|
||||
ctx
|
||||
arrayTypeInfo.Assembly
|
||||
(ComparableTypeDefinitionHandle.Make arrayTypeInfo.TypeDefHandle)
|
||||
arrayTypeInfo.Namespace
|
||||
arrayTypeInfo.Name
|
||||
[ elementHandle ] // Array<T> has one generic parameter
|
||||
|
||||
let concretizeTypeDefinition
|
||||
(ctx : ConcretizationContext)
|
||||
(assemblyName : AssemblyName)
|
||||
(typeDefHandle : ComparableTypeDefinitionHandle)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
|
||||
// Look up the type definition in the assembly
|
||||
let assembly =
|
||||
match ctx.LoadedAssemblies.TryGetValue assemblyName.FullName with
|
||||
| false, _ -> failwithf "Cannot concretize type definition - assembly %s not loaded" assemblyName.FullName
|
||||
| true, assy -> assy
|
||||
|
||||
let typeInfo = assembly.TypeDefs.[typeDefHandle.Get]
|
||||
|
||||
// Check if this type has generic parameters
|
||||
if not typeInfo.Generics.IsEmpty then
|
||||
failwithf
|
||||
"Cannot concretize open generic type %s.%s - it has %d generic parameters"
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeInfo.Generics.Length
|
||||
|
||||
// Check if we've already concretized this type
|
||||
match findExistingType ctx.ConcreteTypes assemblyName typeInfo.Namespace typeInfo.Name [] with
|
||||
| Some handle -> handle, ctx
|
||||
| None ->
|
||||
// Create and add the concrete type (no generic arguments since it's not generic)
|
||||
createAndAddConcreteType ctx assemblyName typeDefHandle typeInfo.Namespace typeInfo.Name [] // No generic parameters
|
||||
|
||||
let private concretizeTypeReference
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly)
|
||||
(ctx : ConcretizationContext)
|
||||
(currentAssembly : AssemblyName)
|
||||
(typeRef : TypeRef)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
// Use the helper to load assembly and resolve the type reference
|
||||
let (targetAssy, typeInfo), ctx =
|
||||
loadAssemblyAndResolveTypeRef loadAssembly ctx currentAssembly typeRef
|
||||
|
||||
// Check if this type has generic parameters
|
||||
if not typeInfo.Generics.IsEmpty then
|
||||
failwithf
|
||||
"Cannot concretize type reference to open generic type %s.%s - it has %d generic parameters"
|
||||
typeInfo.Namespace
|
||||
typeInfo.Name
|
||||
typeInfo.Generics.Length
|
||||
|
||||
// Create or find the concrete type
|
||||
concretizeTypeDefinition ctx targetAssy.Name (ComparableTypeDefinitionHandle.Make typeInfo.TypeDefHandle)
|
||||
|
||||
/// Concretize a type in a specific generic context
|
||||
let rec concretizeType
|
||||
(ctx : ConcretizationContext)
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assembly : AssemblyName)
|
||||
(typeGenerics : ConcreteTypeHandle ImmutableArray)
|
||||
(methodGenerics : ConcreteTypeHandle ImmutableArray)
|
||||
(typeDefn : TypeDefn)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
|
||||
let key = (assembly, typeDefn)
|
||||
|
||||
// Check if we're already processing this type (cycle detection)
|
||||
match ctx.InProgress.TryGetValue key with
|
||||
| true, handle -> handle, ctx
|
||||
| false, _ ->
|
||||
|
||||
match typeDefn with
|
||||
| TypeDefn.PrimitiveType prim -> concretizePrimitive ctx prim
|
||||
|
||||
| TypeDefn.Array (elementType, shape) ->
|
||||
let elementHandle, ctx =
|
||||
concretizeType ctx loadAssembly assembly typeGenerics methodGenerics elementType
|
||||
|
||||
concretizeArray ctx elementHandle shape
|
||||
|
||||
| TypeDefn.OneDimensionalArrayLowerBoundZero elementType ->
|
||||
let elementHandle, ctx =
|
||||
concretizeType ctx loadAssembly assembly typeGenerics methodGenerics elementType
|
||||
|
||||
concretizeOneDimArray ctx elementHandle
|
||||
|
||||
| TypeDefn.GenericTypeParameter index ->
|
||||
if index < typeGenerics.Length then
|
||||
typeGenerics.[index], ctx
|
||||
else
|
||||
failwithf "Generic type parameter %d out of range" index
|
||||
|
||||
| TypeDefn.GenericMethodParameter index ->
|
||||
if index < methodGenerics.Length then
|
||||
methodGenerics.[index], ctx
|
||||
else
|
||||
failwithf "Generic method parameter %d out of range" index
|
||||
|
||||
| TypeDefn.GenericInstantiation (genericDef, args) ->
|
||||
concretizeGenericInstantiation ctx loadAssembly assembly typeGenerics methodGenerics genericDef args
|
||||
|
||||
| TypeDefn.FromDefinition (typeDefHandle, targetAssembly, _) ->
|
||||
concretizeTypeDefinition ctx (AssemblyName targetAssembly) typeDefHandle
|
||||
|
||||
| TypeDefn.FromReference (typeRef, _) -> concretizeTypeReference loadAssembly ctx assembly typeRef
|
||||
|
||||
| TypeDefn.Byref elementType ->
|
||||
// Byref types are managed references to other types
|
||||
// First concretize the element type
|
||||
let elementHandle, ctx =
|
||||
concretizeType ctx loadAssembly assembly typeGenerics methodGenerics elementType
|
||||
|
||||
// Return a Byref constructor wrapping the element type
|
||||
ConcreteTypeHandle.Byref elementHandle, ctx
|
||||
|
||||
| TypeDefn.Pointer elementType ->
|
||||
// Pointer types are unmanaged pointers to other types
|
||||
// First concretize the element type
|
||||
let elementHandle, ctx =
|
||||
concretizeType ctx loadAssembly assembly typeGenerics methodGenerics elementType
|
||||
|
||||
// Return a Pointer constructor wrapping the element type
|
||||
ConcreteTypeHandle.Pointer elementHandle, ctx
|
||||
|
||||
| TypeDefn.Void ->
|
||||
// Void isn't a real runtime type, but we assign it a concretization entry anyway
|
||||
// Use System.Void from the base class types
|
||||
let voidTypeInfo = ctx.BaseTypes.Void
|
||||
|
||||
match
|
||||
findExistingType ctx.ConcreteTypes voidTypeInfo.Assembly voidTypeInfo.Namespace voidTypeInfo.Name []
|
||||
with
|
||||
| Some handle -> handle, ctx
|
||||
| None ->
|
||||
// Create and add the concrete Void type
|
||||
createAndAddConcreteType
|
||||
ctx
|
||||
voidTypeInfo.Assembly
|
||||
(ComparableTypeDefinitionHandle.Make voidTypeInfo.TypeDefHandle)
|
||||
voidTypeInfo.Namespace
|
||||
voidTypeInfo.Name
|
||||
[] // Void has no generic parameters
|
||||
|
||||
| _ -> failwithf "TODO: Concretization of %A not implemented" typeDefn
|
||||
|
||||
and private concretizeGenericInstantiation
|
||||
(ctx : ConcretizationContext)
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assembly : AssemblyName)
|
||||
(typeGenerics : ConcreteTypeHandle ImmutableArray)
|
||||
(methodGenerics : ConcreteTypeHandle ImmutableArray)
|
||||
(genericDef : TypeDefn)
|
||||
(args : ImmutableArray<TypeDefn>)
|
||||
: ConcreteTypeHandle * ConcretizationContext
|
||||
=
|
||||
// First, concretize all type arguments
|
||||
let argHandles, ctxAfterArgs =
|
||||
args
|
||||
|> Seq.fold
|
||||
(fun (handles, ctx) arg ->
|
||||
let handle, ctx =
|
||||
concretizeType ctx loadAssembly assembly typeGenerics methodGenerics arg
|
||||
|
||||
handle :: handles, ctx
|
||||
)
|
||||
([], ctx)
|
||||
|
||||
let argHandles = argHandles |> List.rev
|
||||
|
||||
// Get the base type definition
|
||||
let baseAssembly, baseTypeDefHandle, baseNamespace, baseName, ctxAfterArgs =
|
||||
match genericDef with
|
||||
| FromDefinition (handle, assy, _) ->
|
||||
// Look up the type definition to get namespace and name
|
||||
let currentAssy = ctxAfterArgs.LoadedAssemblies.[AssemblyName(assy).FullName]
|
||||
let typeDef = currentAssy.TypeDefs.[handle.Get]
|
||||
AssemblyName assy, handle, typeDef.Namespace, typeDef.Name, ctxAfterArgs
|
||||
| FromReference (typeRef, _) ->
|
||||
// For a type reference, we need to find where the type is defined
|
||||
// We're looking for the generic type definition, not an instantiation
|
||||
let currentAssy = ctxAfterArgs.LoadedAssemblies.[assembly.FullName]
|
||||
|
||||
// Helper to find the type definition without instantiating generics
|
||||
let rec findTypeDefinition (assy : DumpedAssembly) (ns : string) (name : string) =
|
||||
// First check if it's defined in this assembly
|
||||
match assy.TypeDef ns name with
|
||||
| Some typeDef -> Some (assy, typeDef)
|
||||
| None ->
|
||||
// Check if it's exported/forwarded
|
||||
match assy.ExportedType (Some ns) name with
|
||||
| Some export ->
|
||||
match export.Data with
|
||||
| NonForwarded _ -> None // Shouldn't happen
|
||||
| ForwardsTo assyRef ->
|
||||
let forwardedAssy = assy.AssemblyReferences.[assyRef]
|
||||
|
||||
match ctxAfterArgs.LoadedAssemblies.TryGetValue forwardedAssy.Name.FullName with
|
||||
| true, targetAssy -> findTypeDefinition targetAssy ns name
|
||||
| false, _ -> None // Assembly not loaded yet
|
||||
| None -> None
|
||||
|
||||
// First try to resolve without loading new assemblies
|
||||
match typeRef.ResolutionScope with
|
||||
| TypeRefResolutionScope.Assembly assyRef ->
|
||||
let targetAssyRef = currentAssy.AssemblyReferences.[assyRef]
|
||||
let targetAssyName = targetAssyRef.Name
|
||||
|
||||
match ctxAfterArgs.LoadedAssemblies.TryGetValue targetAssyName.FullName with
|
||||
| true, targetAssy ->
|
||||
// Try to find the type
|
||||
match findTypeDefinition targetAssy typeRef.Namespace typeRef.Name with
|
||||
| Some (foundAssy, typeDef) ->
|
||||
foundAssy.Name,
|
||||
ComparableTypeDefinitionHandle.Make typeDef.TypeDefHandle,
|
||||
typeDef.Namespace,
|
||||
typeDef.Name,
|
||||
ctxAfterArgs
|
||||
| None ->
|
||||
failwithf
|
||||
"Type %s.%s not found in assembly %s or its forwards"
|
||||
typeRef.Namespace
|
||||
typeRef.Name
|
||||
targetAssyName.FullName
|
||||
|
||||
| false, _ ->
|
||||
// Need to load the assembly
|
||||
let newAssemblies, loadedAssy = loadAssembly assembly assyRef
|
||||
|
||||
let ctxWithNewAssy =
|
||||
{ ctxAfterArgs with
|
||||
LoadedAssemblies = newAssemblies
|
||||
}
|
||||
|
||||
// Now try to find the type in the loaded assembly
|
||||
match findTypeDefinition loadedAssy typeRef.Namespace typeRef.Name with
|
||||
| Some (foundAssy, typeDef) ->
|
||||
foundAssy.Name,
|
||||
ComparableTypeDefinitionHandle.Make typeDef.TypeDefHandle,
|
||||
typeDef.Namespace,
|
||||
typeDef.Name,
|
||||
ctxWithNewAssy
|
||||
| None ->
|
||||
failwithf
|
||||
"Type %s.%s not found in loaded assembly %s or its forwards"
|
||||
typeRef.Namespace
|
||||
typeRef.Name
|
||||
loadedAssy.Name.FullName
|
||||
|
||||
| _ -> failwith "TODO: handle other resolution scopes for type refs in generic instantiation"
|
||||
| _ -> failwithf "Generic instantiation of %A not supported" genericDef
|
||||
|
||||
// Check if this exact generic instantiation already exists
|
||||
match findExistingType ctxAfterArgs.ConcreteTypes baseAssembly baseNamespace baseName argHandles with
|
||||
| Some existingHandle ->
|
||||
// Type already exists, return it
|
||||
existingHandle, ctxAfterArgs
|
||||
| None ->
|
||||
// Need to handle cycles: check if we're already processing this type
|
||||
let typeDefnKey = (assembly, GenericInstantiation (genericDef, args))
|
||||
|
||||
match ctxAfterArgs.InProgress.TryGetValue typeDefnKey with
|
||||
| true, handle ->
|
||||
// We're in a cycle, return the in-progress handle
|
||||
handle, ctxAfterArgs
|
||||
| false, _ ->
|
||||
// Pre-allocate a handle for this type to handle cycles
|
||||
let tempId = ctxAfterArgs.ConcreteTypes.NextHandle
|
||||
let tempHandle = ConcreteTypeHandle.Concrete tempId
|
||||
|
||||
// Create the concrete type
|
||||
let concreteType =
|
||||
{
|
||||
_AssemblyName = baseAssembly
|
||||
_Definition = baseTypeDefHandle
|
||||
_Namespace = baseNamespace
|
||||
_Name = baseName
|
||||
_Generics = argHandles
|
||||
}
|
||||
|
||||
// Add to the concrete types and mark as in progress
|
||||
let newCtx =
|
||||
{ ctxAfterArgs with
|
||||
ConcreteTypes =
|
||||
{ ctxAfterArgs.ConcreteTypes with
|
||||
NextHandle = ctxAfterArgs.ConcreteTypes.NextHandle + 1
|
||||
Mapping = ctxAfterArgs.ConcreteTypes.Mapping |> Map.add tempId concreteType
|
||||
}
|
||||
InProgress = ctxAfterArgs.InProgress.SetItem (typeDefnKey, tempHandle)
|
||||
}
|
||||
|
||||
// Remove from in-progress when done
|
||||
let finalCtx =
|
||||
{ newCtx with
|
||||
InProgress = newCtx.InProgress.Remove typeDefnKey
|
||||
}
|
||||
|
||||
tempHandle, finalCtx
|
||||
|
||||
/// High-level API for concretizing types
|
||||
[<RequireQualifiedAccess>]
|
||||
module Concretization =
|
||||
|
||||
/// Helper to concretize an array of types
|
||||
let private concretizeTypeArray
|
||||
(ctx : TypeConcretization.ConcretizationContext)
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assembly : AssemblyName)
|
||||
(typeArgs : ConcreteTypeHandle ImmutableArray)
|
||||
(methodArgs : ConcreteTypeHandle ImmutableArray)
|
||||
(types : ImmutableArray<TypeDefn>)
|
||||
: ImmutableArray<ConcreteTypeHandle> * TypeConcretization.ConcretizationContext
|
||||
=
|
||||
|
||||
let handles = ImmutableArray.CreateBuilder (types.Length)
|
||||
let mutable ctx = ctx
|
||||
|
||||
for i = 0 to types.Length - 1 do
|
||||
let handle, newCtx =
|
||||
TypeConcretization.concretizeType ctx loadAssembly assembly typeArgs methodArgs types.[i]
|
||||
|
||||
handles.Add handle
|
||||
ctx <- newCtx
|
||||
|
||||
handles.ToImmutable (), ctx
|
||||
|
||||
/// Helper to concretize a method signature
|
||||
let private concretizeMethodSignature
|
||||
(ctx : TypeConcretization.ConcretizationContext)
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assembly : AssemblyName)
|
||||
(typeArgs : ConcreteTypeHandle ImmutableArray)
|
||||
(methodArgs : ConcreteTypeHandle ImmutableArray)
|
||||
(signature : TypeMethodSignature<TypeDefn>)
|
||||
: TypeMethodSignature<ConcreteTypeHandle> * TypeConcretization.ConcretizationContext
|
||||
=
|
||||
|
||||
// Concretize return type
|
||||
let returnHandle, ctx =
|
||||
TypeConcretization.concretizeType ctx loadAssembly assembly typeArgs methodArgs signature.ReturnType
|
||||
|
||||
// Concretize parameter types
|
||||
let paramHandles = ResizeArray<ConcreteTypeHandle> ()
|
||||
let mutable ctx = ctx
|
||||
|
||||
for paramType in signature.ParameterTypes do
|
||||
let handle, newCtx =
|
||||
TypeConcretization.concretizeType ctx loadAssembly assembly typeArgs methodArgs paramType
|
||||
|
||||
paramHandles.Add (handle)
|
||||
ctx <- newCtx
|
||||
|
||||
let newSignature =
|
||||
{
|
||||
Header = signature.Header
|
||||
ReturnType = returnHandle
|
||||
ParameterTypes = paramHandles |> Seq.toList
|
||||
GenericParameterCount = signature.GenericParameterCount
|
||||
RequiredParameterCount = signature.RequiredParameterCount
|
||||
}
|
||||
|
||||
newSignature, ctx
|
||||
|
||||
/// Helper to ensure base type assembly is loaded
|
||||
let rec private ensureBaseTypeAssembliesLoaded
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(assyName : AssemblyName)
|
||||
(baseTypeInfo : BaseTypeInfo option)
|
||||
: ImmutableDictionary<string, DumpedAssembly>
|
||||
=
|
||||
match baseTypeInfo with
|
||||
| None -> assemblies
|
||||
| Some (BaseTypeInfo.TypeRef r) ->
|
||||
let assy = assemblies.[assyName.FullName]
|
||||
let typeRef = assy.TypeRefs.[r]
|
||||
|
||||
match typeRef.ResolutionScope with
|
||||
| TypeRefResolutionScope.Assembly assyRef ->
|
||||
let targetAssyRef = assy.AssemblyReferences.[assyRef]
|
||||
|
||||
match assemblies.TryGetValue targetAssyRef.Name.FullName with
|
||||
| true, _ -> assemblies
|
||||
| false, _ ->
|
||||
// Need to load the assembly - pass the assembly that contains the reference
|
||||
let newAssemblies, _ = loadAssembly assy.Name assyRef
|
||||
newAssemblies
|
||||
| _ -> assemblies
|
||||
| Some (BaseTypeInfo.TypeDef _)
|
||||
| Some (BaseTypeInfo.ForeignAssemblyType _)
|
||||
| Some (BaseTypeInfo.TypeSpec _) -> assemblies
|
||||
|
||||
/// Concretize a method's signature and body
|
||||
let concretizeMethod
|
||||
(ctx : AllConcreteTypes)
|
||||
(loadAssembly :
|
||||
AssemblyName -> AssemblyReferenceHandle -> (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly))
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(baseTypes : BaseClassTypes<DumpedAssembly>)
|
||||
(method : WoofWare.PawPrint.MethodInfo<TypeDefn, WoofWare.PawPrint.GenericParameter, TypeDefn>)
|
||||
(typeArgs : ConcreteTypeHandle ImmutableArray)
|
||||
(methodArgs : ConcreteTypeHandle ImmutableArray)
|
||||
: WoofWare.PawPrint.MethodInfo<ConcreteTypeHandle, ConcreteTypeHandle, ConcreteTypeHandle> *
|
||||
AllConcreteTypes *
|
||||
ImmutableDictionary<string, DumpedAssembly>
|
||||
=
|
||||
|
||||
// Ensure base type assemblies are loaded for the declaring type
|
||||
let assemblies =
|
||||
let assy = assemblies.[method.DeclaringType._AssemblyName.FullName]
|
||||
let typeDef = assy.TypeDefs.[method.DeclaringType._Definition.Get]
|
||||
ensureBaseTypeAssembliesLoaded loadAssembly assemblies assy.Name typeDef.BaseType
|
||||
|
||||
let concCtx =
|
||||
{
|
||||
TypeConcretization.ConcretizationContext.InProgress = ImmutableDictionary.Empty
|
||||
TypeConcretization.ConcretizationContext.ConcreteTypes = ctx
|
||||
TypeConcretization.ConcretizationContext.LoadedAssemblies = assemblies
|
||||
TypeConcretization.ConcretizationContext.BaseTypes = baseTypes
|
||||
}
|
||||
|
||||
// First, we need to create a TypeDefn for the declaring type with its generics instantiated
|
||||
let declaringTypeDefn =
|
||||
if method.DeclaringType._Generics.IsEmpty then
|
||||
// Non-generic type - determine the SignatureTypeKind
|
||||
let assy = concCtx.LoadedAssemblies.[method.DeclaringType._AssemblyName.FullName]
|
||||
let arg = assy.TypeDefs.[method.DeclaringType._Definition.Get]
|
||||
|
||||
let baseType =
|
||||
arg.BaseType
|
||||
|> DumpedAssembly.resolveBaseType baseTypes concCtx.LoadedAssemblies assy.Name
|
||||
|
||||
let signatureTypeKind =
|
||||
match baseType with
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
|
||||
TypeDefn.FromDefinition (
|
||||
method.DeclaringType._Definition,
|
||||
method.DeclaringType._AssemblyName.FullName,
|
||||
signatureTypeKind
|
||||
)
|
||||
else
|
||||
// Generic type - create a GenericInstantiation
|
||||
let assy = concCtx.LoadedAssemblies.[method.DeclaringType._AssemblyName.FullName]
|
||||
let arg = assy.TypeDefs.[method.DeclaringType._Definition.Get]
|
||||
|
||||
let baseTypeResolved =
|
||||
arg.BaseType
|
||||
|> DumpedAssembly.resolveBaseType baseTypes concCtx.LoadedAssemblies assy.Name
|
||||
|
||||
let signatureTypeKind =
|
||||
match baseTypeResolved with
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
|
||||
let baseType =
|
||||
TypeDefn.FromDefinition (
|
||||
method.DeclaringType._Definition,
|
||||
method.DeclaringType._AssemblyName.FullName,
|
||||
signatureTypeKind
|
||||
)
|
||||
|
||||
let genericArgsLength = method.DeclaringType.Generics.Length
|
||||
|
||||
if genericArgsLength > typeArgs.Length then
|
||||
failwithf
|
||||
"Method declaring type expects %d generic arguments but only %d provided"
|
||||
genericArgsLength
|
||||
typeArgs.Length
|
||||
|
||||
let genericArgs =
|
||||
typeArgs.Slice (0, genericArgsLength)
|
||||
|> Seq.mapi (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|> ImmutableArray.CreateRange
|
||||
|
||||
TypeDefn.GenericInstantiation (baseType, genericArgs)
|
||||
|
||||
// Concretize the declaring type
|
||||
let declaringHandle, concCtx =
|
||||
TypeConcretization.concretizeType
|
||||
concCtx
|
||||
loadAssembly
|
||||
method.DeclaringType._AssemblyName
|
||||
typeArgs
|
||||
methodArgs
|
||||
declaringTypeDefn
|
||||
|
||||
// Look up the concretized declaring type
|
||||
let concretizedDeclaringType =
|
||||
AllConcreteTypes.lookup declaringHandle concCtx.ConcreteTypes |> Option.get
|
||||
|
||||
// Concretize signature
|
||||
let signature, concCtx =
|
||||
concretizeMethodSignature
|
||||
concCtx
|
||||
loadAssembly
|
||||
method.DeclaringType._AssemblyName
|
||||
typeArgs
|
||||
methodArgs
|
||||
method.Signature
|
||||
|
||||
// Concretize local variables
|
||||
let instructions, concCtx2 =
|
||||
match method.Instructions with
|
||||
| None -> None, concCtx
|
||||
| Some instr ->
|
||||
let locals, updatedCtx =
|
||||
match instr.LocalVars with
|
||||
| None -> None, concCtx
|
||||
| Some vars ->
|
||||
let handles, ctx =
|
||||
concretizeTypeArray
|
||||
concCtx
|
||||
loadAssembly
|
||||
method.DeclaringType._AssemblyName
|
||||
typeArgs
|
||||
methodArgs
|
||||
vars
|
||||
|
||||
Some handles, ctx
|
||||
|
||||
Some (MethodInstructions.setLocalVars locals instr), updatedCtx
|
||||
|
||||
// Map generics to handles
|
||||
let genericHandles =
|
||||
method.Generics
|
||||
|> Seq.mapi (fun i _ -> methodArgs.[i])
|
||||
|> ImmutableArray.CreateRange
|
||||
|
||||
let concretizedMethod : MethodInfo<_, _, ConcreteTypeHandle> =
|
||||
{
|
||||
DeclaringType = concretizedDeclaringType
|
||||
Handle = method.Handle
|
||||
Name = method.Name
|
||||
Instructions = instructions
|
||||
Parameters = method.Parameters
|
||||
Generics = genericHandles
|
||||
Signature = signature
|
||||
RawSignature = method.RawSignature
|
||||
CustomAttributes = method.CustomAttributes
|
||||
MethodAttributes = method.MethodAttributes
|
||||
ImplAttributes = method.ImplAttributes
|
||||
IsStatic = method.IsStatic
|
||||
}
|
||||
|
||||
concretizedMethod, concCtx2.ConcreteTypes, concCtx2.LoadedAssemblies
|
||||
|
||||
let rec concreteHandleToTypeDefn
|
||||
(baseClassTypes : BaseClassTypes<DumpedAssembly>)
|
||||
(handle : ConcreteTypeHandle)
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
: TypeDefn
|
||||
=
|
||||
match handle with
|
||||
| ConcreteTypeHandle.Byref elementHandle ->
|
||||
let elementType =
|
||||
concreteHandleToTypeDefn baseClassTypes elementHandle concreteTypes assemblies
|
||||
|
||||
TypeDefn.Byref elementType
|
||||
| ConcreteTypeHandle.Pointer elementHandle ->
|
||||
let elementType =
|
||||
concreteHandleToTypeDefn baseClassTypes elementHandle concreteTypes assemblies
|
||||
|
||||
TypeDefn.Pointer elementType
|
||||
| ConcreteTypeHandle.Concrete _ ->
|
||||
match AllConcreteTypes.lookup handle concreteTypes with
|
||||
| None -> failwith "Logic error: handle not found"
|
||||
| Some concreteType ->
|
||||
|
||||
// Determine SignatureTypeKind
|
||||
let assy = assemblies.[concreteType.Assembly.FullName]
|
||||
let typeDef = assy.TypeDefs.[concreteType.Definition.Get]
|
||||
// Determine SignatureTypeKind from base type
|
||||
let baseType =
|
||||
typeDef.BaseType
|
||||
|> DumpedAssembly.resolveBaseType baseClassTypes assemblies assy.Name
|
||||
|
||||
let signatureTypeKind =
|
||||
match baseType with
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
|
||||
if concreteType.Generics.IsEmpty then
|
||||
TypeDefn.FromDefinition (concreteType.Definition, concreteType.Assembly.FullName, signatureTypeKind)
|
||||
else
|
||||
// Recursively convert generic arguments
|
||||
let genericArgs =
|
||||
concreteType.Generics
|
||||
|> List.map (fun h -> concreteHandleToTypeDefn baseClassTypes h concreteTypes assemblies)
|
||||
|> ImmutableArray.CreateRange
|
||||
|
||||
let baseDef =
|
||||
TypeDefn.FromDefinition (concreteType.Definition, concreteType.Assembly.FullName, signatureTypeKind)
|
||||
|
||||
TypeDefn.GenericInstantiation (baseDef, genericArgs)
|
||||
@@ -56,32 +56,32 @@ module TypeMethodSignature =
|
||||
}
|
||||
|
||||
let map<'a, 'b, 'state>
|
||||
(f : 'state -> 'a -> 'b * 'state)
|
||||
(state : 'state)
|
||||
(f : 'state -> 'a -> 'state * 'b)
|
||||
(signature : TypeMethodSignature<'a>)
|
||||
: 'state * TypeMethodSignature<'b>
|
||||
(s : TypeMethodSignature<'a>)
|
||||
: TypeMethodSignature<'b> * 'state
|
||||
=
|
||||
let state, ret = f state signature.ReturnType
|
||||
let ret, state = s.ReturnType |> f state
|
||||
|
||||
let state, pars =
|
||||
((state, []), signature.ParameterTypes)
|
||||
||> List.fold (fun (state, acc) par ->
|
||||
let state, result = f state par
|
||||
let state, paramTypes =
|
||||
((state, []), s.ParameterTypes)
|
||||
||> List.fold (fun (state, acc) ty ->
|
||||
let result, state = f state ty
|
||||
state, result :: acc
|
||||
)
|
||||
|
||||
let pars = List.rev pars
|
||||
let paramTypes = paramTypes |> List.rev
|
||||
|
||||
let answer =
|
||||
let result =
|
||||
{
|
||||
Header = signature.Header
|
||||
Header = s.Header
|
||||
ParameterTypes = paramTypes
|
||||
GenericParameterCount = s.GenericParameterCount
|
||||
RequiredParameterCount = s.RequiredParameterCount
|
||||
ReturnType = ret
|
||||
ParameterTypes = pars
|
||||
GenericParameterCount = signature.GenericParameterCount
|
||||
RequiredParameterCount = signature.RequiredParameterCount
|
||||
}
|
||||
|
||||
state, answer
|
||||
result, state
|
||||
|
||||
/// See I.8.2.2
|
||||
type PrimitiveType =
|
||||
@@ -162,21 +162,7 @@ type TypeDefn =
|
||||
| FromDefinition of ComparableTypeDefinitionHandle * assemblyFullName : string * SignatureTypeKind
|
||||
| GenericInstantiation of generic : TypeDefn * args : ImmutableArray<TypeDefn>
|
||||
| FunctionPointer of TypeMethodSignature<TypeDefn>
|
||||
/// <summary>
|
||||
/// A class/interface generic.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// The type <c>List<T></c> has a generic parameter; an instance method on that <c>List</c> would refer to
|
||||
/// <c>T</c> as <c>GenericTypeParameter 0</c>.
|
||||
/// </example>
|
||||
| GenericTypeParameter of index : int
|
||||
/// <summary>
|
||||
/// A method generic.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// The method <c>List.map<'a, 'b></c> takes two generic parameters; those are referred to as
|
||||
/// <c>GenericMethodParameter 0</c> and <c>GenericMethodParameter 1</c> respectively.
|
||||
/// </example>
|
||||
| GenericMethodParameter of index : int
|
||||
/// Not really a type: this indicates the *absence* of a return value.
|
||||
| Void
|
||||
|
||||
@@ -84,18 +84,8 @@ type TypeInfo<'generic, 'fieldGeneric> =
|
||||
override this.ToString () =
|
||||
$"%s{this.Assembly.Name}.%s{this.Namespace}.%s{this.Name}"
|
||||
|
||||
static member NominallyEqual
|
||||
(a : TypeInfo<'generic, 'fieldGeneric>)
|
||||
(b : TypeInfo<'generic, 'fieldGeneric>)
|
||||
: bool
|
||||
=
|
||||
a.Assembly.FullName = b.Assembly.FullName
|
||||
&& a.Namespace = b.Namespace
|
||||
&& a.Name = b.Name
|
||||
&& a.Generics = b.Generics
|
||||
|
||||
type TypeInfoEval<'ret> =
|
||||
abstract Eval<'a, 'field> : TypeInfo<'a, 'field> -> 'ret
|
||||
abstract Eval<'a, 'fieldGeneric> : TypeInfo<'a, 'fieldGeneric> -> 'ret
|
||||
|
||||
type TypeInfoCrate =
|
||||
abstract Apply<'ret> : TypeInfoEval<'ret> -> 'ret
|
||||
@@ -107,7 +97,7 @@ type TypeInfoCrate =
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module TypeInfoCrate =
|
||||
let make<'a, 'field> (t : TypeInfo<'a, 'field>) : TypeInfoCrate =
|
||||
let make<'a, 'b> (t : TypeInfo<'a, 'b>) : TypeInfoCrate =
|
||||
{ new TypeInfoCrate with
|
||||
member _.Apply e = e.Eval t
|
||||
|
||||
@@ -129,37 +119,37 @@ module TypeInfoCrate =
|
||||
type BaseClassTypes<'corelib> =
|
||||
{
|
||||
Corelib : 'corelib
|
||||
String : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Boolean : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Char : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
SByte : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Byte : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Int16 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
UInt16 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Int32 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
UInt32 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Int64 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
UInt64 : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Single : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Double : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Array : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Enum : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
ValueType : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
DelegateType : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Object : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
RuntimeMethodHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
RuntimeFieldHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
RuntimeTypeHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
RuntimeType : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
Void : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
TypedReference : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
IntPtr : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
UIntPtr : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
String : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Boolean : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Char : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
SByte : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Byte : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Int16 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
UInt16 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Int32 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
UInt32 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Int64 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
UInt64 : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Single : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Double : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Array : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Enum : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
ValueType : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
DelegateType : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
Object : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
RuntimeMethodHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
RuntimeFieldHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
RuntimeTypeHandle : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
RuntimeType : TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
}
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module TypeInfo =
|
||||
let withGenerics<'a, 'b, 'field> (gen : 'b ImmutableArray) (t : TypeInfo<'a, 'field>) : TypeInfo<'b, 'field> =
|
||||
let withGenerics<'a, 'b, 'fieldSig>
|
||||
(gen : 'b ImmutableArray)
|
||||
(t : TypeInfo<'a, 'fieldSig>)
|
||||
: TypeInfo<'b, 'fieldSig>
|
||||
=
|
||||
{
|
||||
Namespace = t.Namespace
|
||||
Name = t.Name
|
||||
@@ -175,7 +165,7 @@ module TypeInfo =
|
||||
Events = t.Events
|
||||
}
|
||||
|
||||
let mapGeneric<'a, 'b, 'field> (f : int -> 'a -> 'b) (t : TypeInfo<'a, 'field>) : TypeInfo<'b, 'field> =
|
||||
let mapGeneric<'a, 'b, 'fieldSig> (f : int -> 'a -> 'b) (t : TypeInfo<'a, 'fieldSig>) : TypeInfo<'b, 'fieldSig> =
|
||||
withGenerics (t.Generics |> Seq.mapi f |> ImmutableArray.CreateRange) t
|
||||
|
||||
let internal read
|
||||
@@ -184,7 +174,7 @@ module TypeInfo =
|
||||
(thisAssembly : AssemblyName)
|
||||
(metadataReader : MetadataReader)
|
||||
(typeHandle : TypeDefinitionHandle)
|
||||
: TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
: TypeInfo<WoofWare.PawPrint.GenericParameter, WoofWare.PawPrint.TypeDefn>
|
||||
=
|
||||
let typeDef = metadataReader.GetTypeDefinition typeHandle
|
||||
let methods = typeDef.GetMethods ()
|
||||
@@ -289,11 +279,11 @@ module TypeInfo =
|
||||
else
|
||||
None
|
||||
|
||||
let rec resolveBaseType<'corelib, 'generic, 'field>
|
||||
let rec resolveBaseType<'corelib, 'generic, 'fieldGeneric>
|
||||
(baseClassTypes : BaseClassTypes<'corelib>)
|
||||
(getName : 'corelib -> AssemblyName)
|
||||
(getTypeDef : 'corelib -> TypeDefinitionHandle -> TypeInfo<'generic, 'field>)
|
||||
(getTypeRef : 'corelib -> TypeReferenceHandle -> TypeInfo<'generic, 'field>)
|
||||
(getTypeDef : 'corelib -> TypeDefinitionHandle -> TypeInfo<'generic, 'fieldGeneric>)
|
||||
(getTypeRef : 'corelib -> TypeReferenceHandle -> TypeInfo<'generic, 'fieldGeneric>)
|
||||
(sourceAssembly : AssemblyName)
|
||||
(value : BaseTypeInfo option)
|
||||
: ResolvedBaseType
|
||||
@@ -325,23 +315,16 @@ module TypeInfo =
|
||||
let toTypeDefn
|
||||
(corelib : BaseClassTypes<'corelib>)
|
||||
(getName : 'corelib -> AssemblyName)
|
||||
(getTypeDef : 'corelib -> TypeDefinitionHandle -> TypeInfo<'generic, 'field>)
|
||||
(getTypeRef : 'corelib -> TypeReferenceHandle -> TypeInfo<'generic, 'field>)
|
||||
(ty : TypeInfo<TypeDefn, TypeDefn>)
|
||||
(getTypeDef : 'corelib -> TypeDefinitionHandle -> TypeInfo<'generic, 'fieldGeneric>)
|
||||
(getTypeRef : 'corelib -> TypeReferenceHandle -> TypeInfo<'generic, 'fieldGeneric>)
|
||||
(ty : TypeInfo<'generic, 'fieldGeneric>)
|
||||
: TypeDefn
|
||||
=
|
||||
let stk =
|
||||
match resolveBaseType corelib getName getTypeDef getTypeRef ty.Assembly ty.BaseType with
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Object -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> failwith "todo"
|
||||
|
||||
let defn =
|
||||
TypeDefn.FromDefinition (ComparableTypeDefinitionHandle.Make ty.TypeDefHandle, ty.Assembly.FullName, stk)
|
||||
|
||||
if ty.Generics.IsEmpty then
|
||||
defn
|
||||
else
|
||||
let generics = ty.Generics
|
||||
TypeDefn.GenericInstantiation (defn, generics)
|
||||
TypeDefn.FromDefinition (ComparableTypeDefinitionHandle.Make ty.TypeDefHandle, ty.Assembly.FullName, stk)
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
<Compile Include="ExportedType.fs" />
|
||||
<Compile Include="TypeSpec.fs" />
|
||||
<Compile Include="Assembly.fs" />
|
||||
<Compile Include="TypeConcretisation.fs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -16,30 +16,6 @@ module TestPureCases =
|
||||
|
||||
let unimplemented =
|
||||
[
|
||||
{
|
||||
FileName = "CrossAssemblyTypes.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "GenericEdgeCases.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "TestShl.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "TestShr.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "Threads.cs"
|
||||
ExpectedReturnCode = 3
|
||||
@@ -92,132 +68,6 @@ module TestPureCases =
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = [ CliType.Numeric (CliNumericType.Int32 1) ] |> Some
|
||||
}
|
||||
{
|
||||
FileName = "CastClassSimpleInheritance.cs"
|
||||
ExpectedReturnCode = 5
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsInstSimpleInheritance.cs"
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassNull.cs"
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassArrayCovariance.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassToObject.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstPatternMatching.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassMultipleInterfaces.cs"
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassCrossAssembly.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassNestedTypes.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassGenerics.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassEnum.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassBoxing.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstBoxing.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassArray.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstArray.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstNull.cs"
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassInvalid.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstFailed.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstFailedInterface.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "CastClassInterface.cs"
|
||||
ExpectedReturnCode = 1
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "IsinstInterface.cs"
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "StaticVariables.cs"
|
||||
ExpectedReturnCode = 0
|
||||
@@ -256,9 +106,18 @@ module TestPureCases =
|
||||
}
|
||||
{
|
||||
FileName = "ArgumentOrdering.cs"
|
||||
ExpectedReturnCode = 0
|
||||
ExpectedReturnCode = 42
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
LocalVariablesOfMain =
|
||||
[
|
||||
// localVar
|
||||
CliType.Numeric (CliNumericType.Int32 42)
|
||||
// t
|
||||
CliType.ValueType [ CliType.Numeric (CliNumericType.Int32 42) ]
|
||||
// return value
|
||||
CliType.Numeric (CliNumericType.Int32 42)
|
||||
]
|
||||
|> Some
|
||||
}
|
||||
{
|
||||
FileName = "BasicLock.cs"
|
||||
@@ -344,18 +203,6 @@ module TestPureCases =
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "TypeConcretization.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
{
|
||||
FileName = "TestOr.cs"
|
||||
ExpectedReturnCode = 0
|
||||
NativeImpls = MockEnv.make ()
|
||||
LocalVariablesOfMain = None
|
||||
}
|
||||
]
|
||||
|
||||
[<TestCaseSource(nameof cases)>]
|
||||
|
||||
@@ -32,35 +32,8 @@
|
||||
<EmbeddedResource Include="sourcesPure\Threads.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\ResizeArray.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\ArgumentOrdering.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassSimpleInheritance.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsInstSimpleInheritance.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassNull.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassArrayCovariance.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassToObject.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstPatternMatching.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassMultipleInterfaces.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassCrossAssembly.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassNestedTypes.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassGenerics.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassEnum.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassBoxing.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstBoxing.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassArray.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstArray.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstNull.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassInvalid.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstFailed.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstFailedInterface.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CastClassInterface.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\IsinstInterface.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\TestShl.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\TestShr.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\TestOr.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CustomDelegate.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\Ldind.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\TypeConcretization.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\CrossAssemblyTypes.cs" />
|
||||
<EmbeddedResource Include="sourcesPure\GenericEdgeCases.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="sourcesImpure\WriteLine.cs" />
|
||||
|
||||
@@ -10,40 +10,10 @@ public class Program
|
||||
}
|
||||
}
|
||||
|
||||
public struct Calculator
|
||||
{
|
||||
private int baseValue;
|
||||
|
||||
public Calculator(int initial)
|
||||
{
|
||||
baseValue = initial;
|
||||
}
|
||||
|
||||
public int Add(int a, int b, int c)
|
||||
{
|
||||
return baseValue + a + b + c;
|
||||
}
|
||||
|
||||
public int SubtractIsh(int a, int b)
|
||||
{
|
||||
return baseValue - a + b;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
int localVar = 42;
|
||||
TestStruct t = new TestStruct(ref localVar);
|
||||
if (t.Value != 42) return 1;
|
||||
|
||||
Calculator calc = new Calculator(10);
|
||||
int addResult = calc.Add(1, 2, 3); // Should be 10 + 1 + 2 + 3 = 16
|
||||
if (addResult != 16) return 2;
|
||||
|
||||
// Test 2: Verify order matters
|
||||
int subResult = calc.SubtractIsh(3, 2); // Should be 10 - 3 + 2 = 9
|
||||
if (subResult != 9) return 3;
|
||||
|
||||
return 0;
|
||||
return t.Value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
|
||||
|
||||
// Cast array to System.Array - should succeed
|
||||
System.Array array = (System.Array)numbers;
|
||||
|
||||
return array.Length;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public struct Counter
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public Counter(int count)
|
||||
{
|
||||
Count = count;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Counter counter = new Counter(42);
|
||||
|
||||
// Box the value type
|
||||
object boxed = counter;
|
||||
|
||||
// Check if boxed value is System.ValueType
|
||||
if (boxed is System.ValueType)
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public struct Point
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
|
||||
public Point(int x, int y)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Point p = new Point(10, 32);
|
||||
|
||||
// Box the value type
|
||||
object boxed = p;
|
||||
|
||||
// Cast boxed value type to object (should succeed)
|
||||
object obj = (object)boxed;
|
||||
|
||||
// Unbox
|
||||
Point unboxed = (Point)obj;
|
||||
|
||||
return unboxed.X + unboxed.Y;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
// Using types from System.Collections.Generic assembly
|
||||
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
|
||||
|
||||
// Cast to interface from another assembly
|
||||
IEnumerable<int> enumerable = (IEnumerable<int>)list;
|
||||
|
||||
int count = 0;
|
||||
foreach (var item in enumerable)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
|
||||
return count == 5 ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public enum Color
|
||||
{
|
||||
Red = 1,
|
||||
Green = 2,
|
||||
Blue = 42
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Color myColor = Color.Blue;
|
||||
|
||||
// Box enum value
|
||||
object boxed = myColor;
|
||||
|
||||
// Cast to System.Enum
|
||||
System.Enum enumValue = (System.Enum)boxed;
|
||||
|
||||
// Cast back to specific enum
|
||||
Color unboxed = (Color)enumValue;
|
||||
|
||||
return (int)unboxed;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Container<T>
|
||||
{
|
||||
public T Value { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Container<int> intContainer = new Container<int> { Value = 42 };
|
||||
|
||||
// Cast generic type to object
|
||||
object obj = (object)intContainer;
|
||||
|
||||
// Check type and cast back
|
||||
if (obj is Container<int> container)
|
||||
{
|
||||
return container.Value;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public interface ICalculator
|
||||
{
|
||||
int Calculate(int x, int y);
|
||||
}
|
||||
|
||||
public class Adder : ICalculator
|
||||
{
|
||||
public int Calculate(int x, int y)
|
||||
{
|
||||
return x + y;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Adder adder = new Adder();
|
||||
|
||||
// Cast to interface - should succeed
|
||||
ICalculator calc = (ICalculator)adder;
|
||||
|
||||
return calc.Calculate(10, 32);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Cat
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public class Dog
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
object cat = new Cat { Name = "Whiskers" };
|
||||
|
||||
// Invalid cast - should throw InvalidCastException
|
||||
Dog dog = (Dog)cat;
|
||||
|
||||
// Should not reach here
|
||||
return 0;
|
||||
}
|
||||
catch (System.InvalidCastException)
|
||||
{
|
||||
// Expected exception caught
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public interface IReadable
|
||||
{
|
||||
string Read();
|
||||
}
|
||||
|
||||
public interface IWritable
|
||||
{
|
||||
void Write(string data);
|
||||
}
|
||||
|
||||
public class File : IReadable, IWritable
|
||||
{
|
||||
private string content = "Hello";
|
||||
|
||||
public string Read()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
public void Write(string data)
|
||||
{
|
||||
content = data;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
File file = new File();
|
||||
|
||||
// Cast to first interface
|
||||
IReadable readable = (IReadable)file;
|
||||
|
||||
// Cast to second interface
|
||||
IWritable writable = (IWritable)file;
|
||||
|
||||
return readable != null && writable != null ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Outer
|
||||
{
|
||||
public class Inner
|
||||
{
|
||||
public int Value { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Outer.Inner inner = new Outer.Inner { Value = 42 };
|
||||
|
||||
// Cast nested type to object
|
||||
object obj = (object)inner;
|
||||
|
||||
// Cast back
|
||||
Outer.Inner casted = (Outer.Inner)obj;
|
||||
|
||||
return casted.Value;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class MyClass
|
||||
{
|
||||
public int Value { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
MyClass obj = null;
|
||||
|
||||
// Cast null reference - should succeed and remain null
|
||||
object result = (object)obj;
|
||||
|
||||
return result == null ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Animal
|
||||
{
|
||||
public int Age { get; set; }
|
||||
}
|
||||
|
||||
public class Dog : Animal
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Dog myDog = new Dog { Age = 5, Name = "Rex" };
|
||||
|
||||
// Cast to base class - should succeed
|
||||
Animal animal = (Animal)myDog;
|
||||
|
||||
return animal.Age;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class CustomClass
|
||||
{
|
||||
public int Id { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
CustomClass custom = new CustomClass { Id = 42 };
|
||||
|
||||
// Everything can be cast to System.Object
|
||||
System.Object obj = (System.Object)custom;
|
||||
|
||||
// Verify it's the same object
|
||||
return obj != null && obj == custom ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
|
||||
// Test cross-assembly type resolution using standard library types
|
||||
public class CrossAssemblyTypeTest
|
||||
{
|
||||
public static int TestSystemTypes()
|
||||
{
|
||||
// Test various System types to ensure proper assembly resolution
|
||||
|
||||
// System.DateTime
|
||||
var date = new DateTime(2023, 1, 1);
|
||||
if (date.Year != 2023) return 1;
|
||||
|
||||
// System.Guid
|
||||
var guid = Guid.Empty;
|
||||
if (guid != Guid.Empty) return 2;
|
||||
|
||||
// System.TimeSpan
|
||||
var timeSpan = TimeSpan.FromMinutes(30);
|
||||
if (timeSpan.TotalMinutes != 30) return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int TestCollectionTypes()
|
||||
{
|
||||
// Test various collection types from different assemblies
|
||||
|
||||
// Dictionary<TKey, TValue>
|
||||
var dict = new Dictionary<string, int>();
|
||||
dict["test"] = 42;
|
||||
if (dict["test"] != 42) return 1;
|
||||
|
||||
// HashSet<T>
|
||||
var hashSet = new HashSet<int>();
|
||||
hashSet.Add(1);
|
||||
hashSet.Add(2);
|
||||
hashSet.Add(1); // duplicate
|
||||
if (hashSet.Count != 2) return 2;
|
||||
|
||||
// Queue<T>
|
||||
var queue = new Queue<string>();
|
||||
queue.Enqueue("first");
|
||||
queue.Enqueue("second");
|
||||
if (queue.Dequeue() != "first") return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int TestGenericInterfaces()
|
||||
{
|
||||
// Test generic interfaces across assemblies
|
||||
|
||||
var list = new List<int> { 1, 2, 3 };
|
||||
|
||||
// IEnumerable<T>
|
||||
IEnumerable<int> enumerable = list;
|
||||
int count = 0;
|
||||
foreach (int item in enumerable)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
if (count != 3) return 1;
|
||||
|
||||
// ICollection<T>
|
||||
ICollection<int> collection = list;
|
||||
if (collection.Count != 3) return 2;
|
||||
|
||||
// IList<T>
|
||||
IList<int> ilist = list;
|
||||
if (ilist[0] != 1) return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test Array.Empty<T> which was mentioned in the diff as a specific case
|
||||
public class ArrayEmptyTest
|
||||
{
|
||||
public static int TestArrayEmpty()
|
||||
{
|
||||
// Test Array.Empty<T> for different types
|
||||
var emptyInts = Array.Empty<int>();
|
||||
var emptyStrings = Array.Empty<string>();
|
||||
|
||||
if (emptyInts.Length != 0) return 1;
|
||||
if (emptyStrings.Length != 0) return 2;
|
||||
|
||||
// Verify they are different instances for different types
|
||||
// but same instance for same type
|
||||
var emptyInts2 = Array.Empty<int>();
|
||||
if (!ReferenceEquals(emptyInts, emptyInts2)) return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Main(string[] args)
|
||||
{
|
||||
int result;
|
||||
|
||||
result = CrossAssemblyTypeTest.TestSystemTypes();
|
||||
if (result != 0) return 100 + result;
|
||||
|
||||
result = CrossAssemblyTypeTest.TestCollectionTypes();
|
||||
if (result != 0) return 200 + result;
|
||||
|
||||
result = CrossAssemblyTypeTest.TestGenericInterfaces();
|
||||
if (result != 0) return 300 + result;
|
||||
|
||||
result = ArrayEmptyTest.TestArrayEmpty();
|
||||
if (result != 0) return 400 + result;
|
||||
|
||||
return 0; // All tests passed
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
// Test edge cases with generic parameters as mentioned in the diff
|
||||
public class GenericParameterEdgeCases
|
||||
{
|
||||
// Test method with multiple generic parameters
|
||||
public static T2 Convert<T1, T2>(T1 input, Func<T1, T2> converter)
|
||||
{
|
||||
return converter(input);
|
||||
}
|
||||
|
||||
// Test nested generic method calls
|
||||
public static List<T> WrapInList<T>(T item)
|
||||
{
|
||||
var list = new List<T>();
|
||||
list.Add(item);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static int TestMultipleGenericParameters()
|
||||
{
|
||||
// Test Convert method with different type combinations
|
||||
string result1 = Convert<int, string>(42, x => x.ToString());
|
||||
if (result1 != "42") return 1;
|
||||
|
||||
int result2 = Convert<string, int>("123", x => int.Parse(x));
|
||||
if (result2 != 123) return 2;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int TestNestedGenericMethodCalls()
|
||||
{
|
||||
// Test calling generic method from within another generic method
|
||||
var intList = WrapInList<int>(42);
|
||||
if (intList.Count != 1) return 1;
|
||||
if (intList[0] != 42) return 2;
|
||||
|
||||
var stringList = WrapInList<string>("test");
|
||||
if (stringList.Count != 1) return 3;
|
||||
if (stringList[0] != "test") return 4;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test deeply nested generic types
|
||||
public class DeepNestingTest
|
||||
{
|
||||
public static int TestDeeplyNestedGenerics()
|
||||
{
|
||||
// Test Dictionary<string, List<Dictionary<int, string>>>
|
||||
var complexType = new Dictionary<string, List<Dictionary<int, string>>>();
|
||||
|
||||
var innerDict = new Dictionary<int, string>();
|
||||
innerDict[1] = "one";
|
||||
innerDict[2] = "two";
|
||||
|
||||
var listOfDicts = new List<Dictionary<int, string>>();
|
||||
listOfDicts.Add(innerDict);
|
||||
|
||||
complexType["test"] = listOfDicts;
|
||||
|
||||
if (complexType["test"].Count != 1) return 1;
|
||||
if (complexType["test"][0][1] != "one") return 2;
|
||||
if (complexType["test"][0][2] != "two") return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test generic constraints and inheritance scenarios
|
||||
public class GenericConstraintTest<T> where T : class
|
||||
{
|
||||
private T value;
|
||||
|
||||
public GenericConstraintTest(T val)
|
||||
{
|
||||
value = val;
|
||||
}
|
||||
|
||||
public bool IsNull()
|
||||
{
|
||||
return value == null;
|
||||
}
|
||||
|
||||
public static int TestGenericConstraints()
|
||||
{
|
||||
var test = new GenericConstraintTest<string>("hello");
|
||||
if (test.IsNull()) return 1;
|
||||
|
||||
var nullTest = new GenericConstraintTest<string>(null);
|
||||
if (!nullTest.IsNull()) return 2;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test generic field access scenarios mentioned in the diff
|
||||
public class GenericFieldAccess<T>
|
||||
{
|
||||
public static T DefaultValue = default(T);
|
||||
|
||||
public static int TestStaticGenericField()
|
||||
{
|
||||
// Test that static fields work correctly with generics
|
||||
if (GenericFieldAccess<int>.DefaultValue != 0) return 1;
|
||||
|
||||
// Test that different instantiations have different static fields
|
||||
GenericFieldAccess<int>.DefaultValue = 42;
|
||||
if (GenericFieldAccess<int>.DefaultValue != 42) return 2;
|
||||
if (GenericFieldAccess<string>.DefaultValue != null) return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Main(string[] args)
|
||||
{
|
||||
int result;
|
||||
|
||||
result = GenericParameterEdgeCases.TestMultipleGenericParameters();
|
||||
if (result != 0) return 100 + result;
|
||||
|
||||
result = GenericParameterEdgeCases.TestNestedGenericMethodCalls();
|
||||
if (result != 0) return 200 + result;
|
||||
|
||||
result = DeepNestingTest.TestDeeplyNestedGenerics();
|
||||
if (result != 0) return 300 + result;
|
||||
|
||||
result = GenericConstraintTest<string>.TestGenericConstraints();
|
||||
if (result != 0) return 400 + result;
|
||||
|
||||
result = GenericFieldAccess<int>.TestStaticGenericField();
|
||||
if (result != 0) return 500 + result;
|
||||
|
||||
return 0; // All tests passed
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Vehicle
|
||||
{
|
||||
public int Wheels { get; set; }
|
||||
}
|
||||
|
||||
public class Car : Vehicle
|
||||
{
|
||||
public string Model { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Car myCar = new Car { Wheels = 4, Model = "Tesla" };
|
||||
|
||||
// 'is' operator uses isinst instruction
|
||||
if (myCar is Vehicle)
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
string[] names = new string[] { "Alice", "Bob", "Charlie" };
|
||||
|
||||
// Check if array is System.Array
|
||||
if (names is System.Array)
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public struct Counter
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public Counter(int count)
|
||||
{
|
||||
Count = count;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Counter counter = new Counter(42);
|
||||
|
||||
// Box the value type
|
||||
object boxed = counter;
|
||||
|
||||
// Check if boxed value is System.ValueType
|
||||
if (boxed is System.ValueType)
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class Bird
|
||||
{
|
||||
public bool CanFly { get; set; }
|
||||
}
|
||||
|
||||
public class Fish
|
||||
{
|
||||
public bool CanSwim { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Bird sparrow = new Bird { CanFly = true };
|
||||
|
||||
// Cast to object first to bypass compile-time checking
|
||||
object obj = sparrow;
|
||||
|
||||
// This should fail at runtime and return null (not throw)
|
||||
Fish fish = obj as Fish;
|
||||
|
||||
return fish == null ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public interface IAnimal
|
||||
{
|
||||
string Name { get; set; }
|
||||
}
|
||||
|
||||
public class Bird : IAnimal
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public bool CanFly { get; set; }
|
||||
}
|
||||
|
||||
public class Fish : IAnimal
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public bool CanSwim { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
IAnimal animal = new Bird { Name = "Sparrow", CanFly = true };
|
||||
|
||||
// This should fail at runtime and return null (not throw)
|
||||
// because the actual object is Bird, not Fish
|
||||
Fish fish = animal as Fish;
|
||||
|
||||
return fish == null ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public interface IDisposable
|
||||
{
|
||||
void Dispose();
|
||||
}
|
||||
|
||||
public class Resource : IDisposable
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Cleanup
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Resource resource = new Resource { Id = 42 };
|
||||
|
||||
// 'as' operator uses isinst instruction
|
||||
IDisposable disposable = resource as IDisposable;
|
||||
|
||||
return disposable != null ? resource.Id : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public class MyType
|
||||
{
|
||||
public int Value { get; set; }
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
MyType obj = null;
|
||||
|
||||
// isinst on null should return null
|
||||
object result = obj as object;
|
||||
|
||||
return result == null ? 42 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
public class Program
|
||||
{
|
||||
public abstract class Shape
|
||||
{
|
||||
public abstract double GetArea();
|
||||
}
|
||||
|
||||
public class Circle : Shape
|
||||
{
|
||||
public double Radius { get; set; }
|
||||
|
||||
public override double GetArea()
|
||||
{
|
||||
return 3.14 * Radius * Radius;
|
||||
}
|
||||
}
|
||||
|
||||
public class Square : Shape
|
||||
{
|
||||
public double Side { get; set; }
|
||||
|
||||
public override double GetArea()
|
||||
{
|
||||
return Side * Side;
|
||||
}
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
Shape shape = new Circle { Radius = 10 };
|
||||
|
||||
// Pattern matching uses isinst
|
||||
if (shape is Circle circle)
|
||||
{
|
||||
return (int)circle.Radius;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public class GenericCounter<T>
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Main(string[] argv)
|
||||
static int Main()
|
||||
{
|
||||
// Test that different generic instantiations have separate static variables
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
public class TestOr
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
// Test 1: Bitwise OR with Int32
|
||||
int a32 = 12; // Binary: 1100
|
||||
int b32 = 10; // Binary: 1010
|
||||
int result32 = a32 | b32; // Should be 14 (Binary: 1110)
|
||||
if (result32 != 14) return 1;
|
||||
|
||||
// Test 2: Bitwise OR with Int64
|
||||
long a64 = 0x00FF00FFL;
|
||||
long b64 = 0xFF00FF00L;
|
||||
long result64 = a64 | b64;
|
||||
if (result64 != 0xFFFFFFFFL) return 2;
|
||||
|
||||
// Test 3: Mixed bitwise OR (Int32 and native int)
|
||||
int aMixed = 15; // Binary: 1111
|
||||
nint bMixed = 240; // Binary: 11110000
|
||||
nint resultMixed = aMixed | bMixed; // Should be 255 (Binary: 11111111)
|
||||
if (resultMixed != 255) return 3;
|
||||
|
||||
// Test 4: OR with itself
|
||||
int self = 42;
|
||||
int selfResult = self | self;
|
||||
if (selfResult != 42) return 4;
|
||||
|
||||
// Test 5: OR with 0
|
||||
int withZero = 123;
|
||||
int zeroResult = withZero | 0;
|
||||
if (zeroResult != 123) return 5;
|
||||
|
||||
// Test 6: Native int OR native int
|
||||
nint nativeA = 0x0F;
|
||||
nint nativeB = 0xF0;
|
||||
nint nativeResult = nativeA | nativeB; // Should be 0xFF
|
||||
if (nativeResult != 0xFF) return 6;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
public class TestShl
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
// Test 1: Shift Left with Int32
|
||||
int value32 = 5; // Binary: 0101
|
||||
int shift32 = 2;
|
||||
int result32 = value32 << shift32; // Should be 20 (Binary: 10100)
|
||||
if (result32 != 20) return 1;
|
||||
|
||||
// Test 2: Shift Left with Int64
|
||||
long value64 = 7L; // Binary: 0111
|
||||
int shift64 = 3;
|
||||
long result64 = value64 << shift64; // Should be 56 (Binary: 111000)
|
||||
if (result64 != 56L) return 2;
|
||||
|
||||
// Test 3: Shift by 0
|
||||
int noShiftValue = 42;
|
||||
int noShiftResult = noShiftValue << 0;
|
||||
if (noShiftResult != 42) return 3;
|
||||
|
||||
// Test 4: Shift by 1
|
||||
int singleShiftResult = noShiftValue << 1;
|
||||
if (singleShiftResult != 84) return 4;
|
||||
|
||||
// Test 5: Shift with native int
|
||||
nint nativeValue = 3;
|
||||
int nativeShift = 4;
|
||||
nint nativeResult = nativeValue << nativeShift; // Should be 48
|
||||
if (nativeResult != 48) return 5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
public class TestShr
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
// Test 1: Shift Right with Int32
|
||||
int value32 = 20; // Binary: 10100
|
||||
int shift32 = 2;
|
||||
int result32 = value32 >> shift32; // Should be 5 (Binary: 0101)
|
||||
if (result32 != 5) return 1;
|
||||
|
||||
// Test 2: Shift Right with Int64
|
||||
long value64 = 56L; // Binary: 111000
|
||||
int shift64 = 3;
|
||||
long result64 = value64 >> shift64; // Should be 7 (Binary: 0111)
|
||||
if (result64 != 7L) return 2;
|
||||
|
||||
// Test 3: Right shift preserving sign (negative number)
|
||||
int negative = -16;
|
||||
int negativeResult = negative >> 2; // Should be -4
|
||||
if (negativeResult != -4) return 3;
|
||||
|
||||
// Test 4: Shift by 0
|
||||
int noShiftValue = 99;
|
||||
int noShiftResult = noShiftValue >> 0;
|
||||
if (noShiftResult != 99) return 4;
|
||||
|
||||
// Test 5: Shift with native int
|
||||
nint nativeValue = 48;
|
||||
int nativeShift = 4;
|
||||
nint nativeResult = nativeValue >> nativeShift; // Should be 3
|
||||
if (nativeResult != 3) return 5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
// Test basic type concretization
|
||||
public class BasicTypeTest
|
||||
{
|
||||
public static int TestBasicTypes()
|
||||
{
|
||||
// Test primitive types
|
||||
int i = 42;
|
||||
string s = "hello";
|
||||
bool b = true;
|
||||
|
||||
if (i != 42) return 1;
|
||||
if (s != "hello") return 2;
|
||||
if (!b) return 3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test generic type instantiation
|
||||
public class GenericTypeTest<T>
|
||||
{
|
||||
private T value;
|
||||
|
||||
public GenericTypeTest(T val)
|
||||
{
|
||||
value = val;
|
||||
}
|
||||
|
||||
public T GetValue()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
public static int TestGenericInstantiation()
|
||||
{
|
||||
var intTest = new GenericTypeTest<int>(123);
|
||||
var stringTest = new GenericTypeTest<string>("test");
|
||||
|
||||
if (intTest.GetValue() != 123) return 1;
|
||||
if (stringTest.GetValue() != "test") return 2;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test nested generic types
|
||||
public class NestedGenericTest
|
||||
{
|
||||
public static int TestNestedGenerics()
|
||||
{
|
||||
var listOfInts = new List<int>();
|
||||
listOfInts.Add(1);
|
||||
listOfInts.Add(2);
|
||||
|
||||
if (listOfInts.Count != 2) return 1;
|
||||
if (listOfInts[0] != 1) return 2;
|
||||
if (listOfInts[1] != 2) return 3;
|
||||
|
||||
var listOfLists = new List<List<int>>();
|
||||
listOfLists.Add(listOfInts);
|
||||
|
||||
if (listOfLists.Count != 1) return 4;
|
||||
if (listOfLists[0].Count != 2) return 5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Test generic methods
|
||||
public class GenericMethodTest
|
||||
{
|
||||
public static T Identity<T>(T input)
|
||||
{
|
||||
return input;
|
||||
}
|
||||
|
||||
public static int TestGenericMethods()
|
||||
{
|
||||
int intResult = Identity<int>(42);
|
||||
string stringResult = Identity<string>("hello");
|
||||
|
||||
if (intResult != 42) return 1;
|
||||
if (stringResult != "hello") return 2;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Main(string[] args)
|
||||
{
|
||||
int result;
|
||||
|
||||
result = BasicTypeTest.TestBasicTypes();
|
||||
if (result != 0) return 100 + result;
|
||||
|
||||
result = GenericTypeTest<int>.TestGenericInstantiation();
|
||||
if (result != 0) return 200 + result;
|
||||
|
||||
result = NestedGenericTest.TestNestedGenerics();
|
||||
if (result != 0) return 300 + result;
|
||||
|
||||
result = GenericMethodTest.TestGenericMethods();
|
||||
if (result != 0) return 400 + result;
|
||||
|
||||
return 0; // All tests passed
|
||||
}
|
||||
}
|
||||
@@ -60,18 +60,22 @@ module AbstractMachine =
|
||||
|
||||
let delegateToRun = state.ManagedHeap.NonArrayObjects.[delegateToRunAddr]
|
||||
|
||||
let target =
|
||||
match delegateToRun.Fields.["_target"] with
|
||||
| CliType.ObjectRef addr -> addr
|
||||
| x -> failwith $"TODO: delegate target wasn't an object ref: %O{x}"
|
||||
if delegateToRun.Fields.["_target"] <> CliType.ObjectRef None then
|
||||
failwith "TODO: delegate target wasn't None"
|
||||
|
||||
let methodPtr =
|
||||
match delegateToRun.Fields.["_methodPtr"] with
|
||||
| CliType.Numeric (CliNumericType.NativeInt (NativeIntSource.FunctionPointer mi)) -> mi
|
||||
| d -> failwith $"unexpectedly not a method pointer in delegate invocation: {d}"
|
||||
|
||||
let typeGenerics =
|
||||
instruction.ExecutingMethod.DeclaringType.Generics |> ImmutableArray.CreateRange
|
||||
|
||||
let methodGenerics = instruction.ExecutingMethod.Generics
|
||||
|
||||
let methodPtr =
|
||||
methodPtr |> MethodInfo.mapTypeGenerics (fun i _ -> typeGenerics.[i])
|
||||
|
||||
// When we return, we need to go back up the stack
|
||||
match state |> IlMachineState.returnStackFrame loggerFactory baseClassTypes thread with
|
||||
| None -> failwith "unexpectedly nowhere to return from delegate"
|
||||
@@ -82,41 +86,23 @@ module AbstractMachine =
|
||||
(state, instruction.Arguments)
|
||||
||> Seq.fold (fun state arg -> IlMachineState.pushToEvalStack arg thread state)
|
||||
|
||||
// The odd little calling convention strikes again: we push the `target` parameter on top of the
|
||||
// stack, although that doesn't actually happen in the CLR.
|
||||
// We'll pretend we're constructing an object, so that the calling convention gets respected in
|
||||
// `callMethod`.
|
||||
let state, constructing =
|
||||
match target with
|
||||
| None -> state, None
|
||||
| Some target ->
|
||||
let state =
|
||||
IlMachineState.pushToEvalStack (CliType.ObjectRef (Some target)) thread state
|
||||
|
||||
state, Some target
|
||||
|
||||
let state, _ =
|
||||
state.WithThreadSwitchedToAssembly methodPtr.DeclaringType.Assembly thread
|
||||
|
||||
// Don't advance the program counter again on return; that was already done by the Callvirt that
|
||||
// caused this delegate to be invoked.
|
||||
let currentThreadState = state.ThreadState.[thread]
|
||||
|
||||
let state =
|
||||
IlMachineState.callMethod
|
||||
let state, result =
|
||||
state
|
||||
|> IlMachineState.callMethodInActiveAssembly
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
None
|
||||
constructing
|
||||
false
|
||||
thread
|
||||
false
|
||||
methodGenerics
|
||||
methodPtr
|
||||
thread
|
||||
currentThreadState
|
||||
state
|
||||
None
|
||||
|
||||
ExecutionResult.Stepped (state, WhatWeDid.Executed)
|
||||
ExecutionResult.Stepped (state, result)
|
||||
| _ ->
|
||||
|
||||
let outcome =
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace WoofWare.PawPrint
|
||||
|
||||
open System
|
||||
open System.Collections.Immutable
|
||||
open System.Reflection
|
||||
open System.Reflection.Metadata
|
||||
@@ -62,7 +63,7 @@ type UnsignedNativeIntSource =
|
||||
type NativeIntSource =
|
||||
| Verbatim of int64
|
||||
| ManagedPointer of ManagedPointerSource
|
||||
| FunctionPointer of MethodInfo<ConcreteTypeHandle, ConcreteTypeHandle, ConcreteTypeHandle>
|
||||
| FunctionPointer of MethodInfo<FakeUnit, WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
| TypeHandlePtr of int64<typeHandle>
|
||||
|
||||
override this.ToString () : string =
|
||||
@@ -151,7 +152,7 @@ type CliType =
|
||||
| RuntimePointer of CliRuntimePointer
|
||||
/// This is *not* a CLI type as such. I don't actually know its status. A value type is represented simply
|
||||
/// as a concatenated list of its fields.
|
||||
| ValueType of (string * CliType) list
|
||||
| ValueType of CliType list
|
||||
|
||||
/// In fact any non-zero value will do for True, but we'll use 1
|
||||
static member OfBool (b : bool) = CliType.Bool (if b then 1uy else 0uy)
|
||||
@@ -167,6 +168,7 @@ type CliTypeResolutionResult =
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module CliType =
|
||||
|
||||
let zeroOfPrimitive (primitiveType : PrimitiveType) : CliType =
|
||||
match primitiveType with
|
||||
| PrimitiveType.Boolean -> CliType.Bool 0uy
|
||||
@@ -191,209 +193,96 @@ module CliType =
|
||||
| PrimitiveType.UIntPtr -> CliType.RuntimePointer (CliRuntimePointer.Managed CliRuntimePointerSource.Null)
|
||||
| PrimitiveType.Object -> CliType.ObjectRef None
|
||||
|
||||
let rec zeroOf
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
let rec zeroOfTypeDefn
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(corelib : BaseClassTypes<DumpedAssembly>)
|
||||
(handle : ConcreteTypeHandle)
|
||||
: CliType * AllConcreteTypes
|
||||
(assy : DumpedAssembly)
|
||||
(typeGenerics : TypeDefn ImmutableArray)
|
||||
(methodGenerics : TypeDefn ImmutableArray)
|
||||
(ty : TypeDefn)
|
||||
: CliTypeResolutionResult
|
||||
=
|
||||
zeroOfWithVisited concreteTypes assemblies corelib handle Set.empty
|
||||
match ty with
|
||||
| TypeDefn.PrimitiveType primitiveType -> CliTypeResolutionResult.Resolved (zeroOfPrimitive primitiveType)
|
||||
| TypeDefn.Array _ -> CliTypeResolutionResult.Resolved (CliType.ObjectRef None)
|
||||
| TypeDefn.Pinned typeDefn -> failwith "todo"
|
||||
| TypeDefn.Pointer _ ->
|
||||
CliRuntimePointer.Managed CliRuntimePointerSource.Null
|
||||
|> CliType.RuntimePointer
|
||||
|> CliTypeResolutionResult.Resolved
|
||||
| TypeDefn.Byref _ -> CliTypeResolutionResult.Resolved (CliType.ObjectRef None)
|
||||
| TypeDefn.OneDimensionalArrayLowerBoundZero _ -> CliTypeResolutionResult.Resolved (CliType.ObjectRef None)
|
||||
| TypeDefn.Modified (original, afterMod, modificationRequired) -> failwith "todo"
|
||||
| TypeDefn.FromReference (typeRef, signatureTypeKind) ->
|
||||
match signatureTypeKind with
|
||||
| SignatureTypeKind.Unknown -> failwith "todo"
|
||||
| SignatureTypeKind.ValueType ->
|
||||
match Assembly.resolveTypeRef assemblies assy typeRef typeGenerics with
|
||||
| TypeResolutionResult.Resolved (sourceAssy, ty) ->
|
||||
let fields =
|
||||
ty.Fields
|
||||
|> List.filter (fun field -> not (field.Attributes.HasFlag FieldAttributes.Static))
|
||||
|> List.map (fun fi ->
|
||||
match
|
||||
zeroOfTypeDefn assemblies corelib sourceAssy typeGenerics methodGenerics fi.Signature
|
||||
with
|
||||
| CliTypeResolutionResult.Resolved ty -> Ok ty
|
||||
| CliTypeResolutionResult.FirstLoad a -> Error a
|
||||
)
|
||||
|> Result.allOkOrError
|
||||
|
||||
and zeroOfWithVisited
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(corelib : BaseClassTypes<DumpedAssembly>)
|
||||
(handle : ConcreteTypeHandle)
|
||||
(visited : Set<ConcreteTypeHandle>)
|
||||
: CliType * AllConcreteTypes
|
||||
=
|
||||
match fields with
|
||||
| Error (_, []) -> failwith "logic error"
|
||||
| Error (_, f :: _) -> CliTypeResolutionResult.FirstLoad f
|
||||
| Ok fields -> CliType.ValueType fields |> CliTypeResolutionResult.Resolved
|
||||
| TypeResolutionResult.FirstLoadAssy assy -> CliTypeResolutionResult.FirstLoad assy
|
||||
| SignatureTypeKind.Class -> CliType.ObjectRef None |> CliTypeResolutionResult.Resolved
|
||||
| _ -> raise (ArgumentOutOfRangeException ())
|
||||
| TypeDefn.FromDefinition (typeDefinitionHandle, _, signatureTypeKind) ->
|
||||
let typeDef = assy.TypeDefs.[typeDefinitionHandle.Get]
|
||||
|
||||
// Handle constructed types first
|
||||
match handle with
|
||||
| ConcreteTypeHandle.Byref _ ->
|
||||
// Byref types are managed references - the zero value is a null reference
|
||||
CliType.RuntimePointer (CliRuntimePointer.Managed CliRuntimePointerSource.Null), concreteTypes
|
||||
|
||||
| ConcreteTypeHandle.Pointer _ ->
|
||||
// Pointer types are unmanaged pointers - the zero value is a null pointer
|
||||
CliType.RuntimePointer (CliRuntimePointer.Unmanaged 0L), concreteTypes
|
||||
|
||||
| ConcreteTypeHandle.Concrete _ ->
|
||||
// This is a concrete type - look it up in the mapping
|
||||
let concreteType =
|
||||
match AllConcreteTypes.lookup handle concreteTypes with
|
||||
| Some ct -> ct
|
||||
| None -> failwithf "ConcreteTypeHandle %A not found in AllConcreteTypes" handle
|
||||
|
||||
// Get the type definition from the assembly
|
||||
let assembly = assemblies.[concreteType.Assembly.FullName]
|
||||
let typeDef = assembly.TypeDefs.[concreteType.Definition.Get]
|
||||
|
||||
// Check if it's a primitive type by comparing with corelib types FIRST
|
||||
if concreteType.Assembly = corelib.Corelib.Name && concreteType.Generics.IsEmpty then
|
||||
// Check against known primitive types
|
||||
if TypeInfo.NominallyEqual typeDef corelib.Boolean then
|
||||
zeroOfPrimitive PrimitiveType.Boolean, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Char then
|
||||
zeroOfPrimitive PrimitiveType.Char, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.SByte then
|
||||
zeroOfPrimitive PrimitiveType.SByte, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Byte then
|
||||
zeroOfPrimitive PrimitiveType.Byte, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Int16 then
|
||||
zeroOfPrimitive PrimitiveType.Int16, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.UInt16 then
|
||||
zeroOfPrimitive PrimitiveType.UInt16, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Int32 then
|
||||
zeroOfPrimitive PrimitiveType.Int32, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.UInt32 then
|
||||
zeroOfPrimitive PrimitiveType.UInt32, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Int64 then
|
||||
zeroOfPrimitive PrimitiveType.Int64, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.UInt64 then
|
||||
zeroOfPrimitive PrimitiveType.UInt64, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Single then
|
||||
zeroOfPrimitive PrimitiveType.Single, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Double then
|
||||
zeroOfPrimitive PrimitiveType.Double, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.String then
|
||||
zeroOfPrimitive PrimitiveType.String, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.Object then
|
||||
zeroOfPrimitive PrimitiveType.Object, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.IntPtr then
|
||||
zeroOfPrimitive PrimitiveType.IntPtr, concreteTypes
|
||||
elif TypeInfo.NominallyEqual typeDef corelib.UIntPtr then
|
||||
zeroOfPrimitive PrimitiveType.UIntPtr, concreteTypes
|
||||
else if
|
||||
// Check if it's an array type
|
||||
typeDef = corelib.Array
|
||||
then
|
||||
CliType.ObjectRef None, concreteTypes // Arrays are reference types
|
||||
else if
|
||||
// Not a known primitive, now check for cycles
|
||||
Set.contains handle visited
|
||||
then
|
||||
// We're in a cycle - return a default zero value for the type
|
||||
// For value types in cycles, we'll return a null reference as a safe fallback
|
||||
// This should only happen with self-referential types
|
||||
CliType.ObjectRef None, concreteTypes
|
||||
else
|
||||
let visited = Set.add handle visited
|
||||
// Not a known primitive, check if it's a value type or reference type
|
||||
determineZeroForCustomType concreteTypes assemblies corelib handle concreteType typeDef visited
|
||||
else if
|
||||
// Not from corelib or has generics
|
||||
concreteType.Assembly = corelib.Corelib.Name
|
||||
&& typeDef = corelib.Array
|
||||
&& concreteType.Generics.Length = 1
|
||||
then
|
||||
// This is an array type
|
||||
CliType.ObjectRef None, concreteTypes
|
||||
else if
|
||||
// Custom type - now check for cycles
|
||||
Set.contains handle visited
|
||||
then
|
||||
// We're in a cycle - return a default zero value for the type
|
||||
// For value types in cycles, we'll return a null reference as a safe fallback
|
||||
// This should only happen with self-referential types
|
||||
CliType.ObjectRef None, concreteTypes
|
||||
if typeDef = corelib.Int32 then
|
||||
zeroOfPrimitive PrimitiveType.Int32 |> CliTypeResolutionResult.Resolved
|
||||
elif typeDef = corelib.Int64 then
|
||||
zeroOfPrimitive PrimitiveType.Int64 |> CliTypeResolutionResult.Resolved
|
||||
elif typeDef = corelib.UInt32 then
|
||||
zeroOfPrimitive PrimitiveType.UInt32 |> CliTypeResolutionResult.Resolved
|
||||
elif typeDef = corelib.UInt64 then
|
||||
zeroOfPrimitive PrimitiveType.UInt64 |> CliTypeResolutionResult.Resolved
|
||||
else
|
||||
let visited = Set.add handle visited
|
||||
// Custom type - need to determine if it's a value type or reference type
|
||||
determineZeroForCustomType concreteTypes assemblies corelib handle concreteType typeDef visited
|
||||
// TODO: the rest
|
||||
match signatureTypeKind with
|
||||
| SignatureTypeKind.Unknown -> failwith "todo"
|
||||
| SignatureTypeKind.ValueType ->
|
||||
let fields =
|
||||
typeDef.Fields
|
||||
// oh lord, this is awfully ominous - I really don't want to store the statics here
|
||||
|> List.filter (fun field -> not (field.Attributes.HasFlag FieldAttributes.Static))
|
||||
|> List.map (fun fi ->
|
||||
match zeroOfTypeDefn assemblies corelib assy typeGenerics methodGenerics fi.Signature with
|
||||
| CliTypeResolutionResult.Resolved ty -> Ok ty
|
||||
| CliTypeResolutionResult.FirstLoad a -> Error a
|
||||
)
|
||||
|> Result.allOkOrError
|
||||
|
||||
and private determineZeroForCustomType
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(corelib : BaseClassTypes<DumpedAssembly>)
|
||||
(handle : ConcreteTypeHandle)
|
||||
(concreteType : ConcreteType<ConcreteTypeHandle>)
|
||||
(typeDef : WoofWare.PawPrint.TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>)
|
||||
(visited : Set<ConcreteTypeHandle>)
|
||||
: CliType * AllConcreteTypes
|
||||
=
|
||||
match fields with
|
||||
| Error (_, []) -> failwith "logic error"
|
||||
| Error (_, f :: _) -> CliTypeResolutionResult.FirstLoad f
|
||||
| Ok fields ->
|
||||
|
||||
// Determine if this is a value type by checking inheritance
|
||||
let isValueType =
|
||||
match DumpedAssembly.resolveBaseType corelib assemblies typeDef.Assembly typeDef.BaseType with
|
||||
| ResolvedBaseType.ValueType
|
||||
| ResolvedBaseType.Enum -> true
|
||||
| ResolvedBaseType.Delegate -> false // Delegates are reference types
|
||||
| ResolvedBaseType.Object -> false
|
||||
CliType.ValueType fields |> CliTypeResolutionResult.Resolved
|
||||
| SignatureTypeKind.Class -> CliType.ObjectRef None |> CliTypeResolutionResult.Resolved
|
||||
| _ -> raise (ArgumentOutOfRangeException ())
|
||||
| TypeDefn.GenericInstantiation (generic, args) ->
|
||||
zeroOfTypeDefn assemblies corelib assy args methodGenerics generic
|
||||
| TypeDefn.FunctionPointer typeMethodSignature -> failwith "todo"
|
||||
| TypeDefn.GenericTypeParameter index ->
|
||||
// TODO: can generics depend on other generics? presumably, so we pass the array down again
|
||||
zeroOfTypeDefn assemblies corelib assy typeGenerics methodGenerics typeGenerics.[index]
|
||||
| TypeDefn.GenericMethodParameter index ->
|
||||
zeroOfTypeDefn assemblies corelib assy typeGenerics methodGenerics methodGenerics.[index]
|
||||
| TypeDefn.Void -> failwith "should never construct an element of type Void"
|
||||
|
||||
if isValueType then
|
||||
// It's a value type - need to create zero values for all non-static fields
|
||||
let mutable currentConcreteTypes = concreteTypes
|
||||
|
||||
let fieldZeros =
|
||||
typeDef.Fields
|
||||
|> List.filter (fun field -> not (field.Attributes.HasFlag FieldAttributes.Static))
|
||||
|> List.map (fun field ->
|
||||
// Need to concretize the field type with the concrete type's generics
|
||||
let fieldTypeDefn = field.Signature
|
||||
|
||||
let fieldHandle, updatedConcreteTypes =
|
||||
concretizeFieldType currentConcreteTypes assemblies corelib concreteType fieldTypeDefn
|
||||
|
||||
currentConcreteTypes <- updatedConcreteTypes
|
||||
|
||||
let fieldZero, updatedConcreteTypes2 =
|
||||
zeroOfWithVisited currentConcreteTypes assemblies corelib fieldHandle visited
|
||||
|
||||
currentConcreteTypes <- updatedConcreteTypes2
|
||||
(field.Name, fieldZero)
|
||||
)
|
||||
|
||||
CliType.ValueType fieldZeros, currentConcreteTypes
|
||||
else
|
||||
// It's a reference type
|
||||
CliType.ObjectRef None, concreteTypes
|
||||
|
||||
and private concretizeFieldType
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(corelib : BaseClassTypes<DumpedAssembly>)
|
||||
(declaringType : ConcreteType<ConcreteTypeHandle>)
|
||||
(fieldType : TypeDefn)
|
||||
: ConcreteTypeHandle * AllConcreteTypes
|
||||
=
|
||||
|
||||
// Create a concretization context
|
||||
let ctx =
|
||||
{
|
||||
TypeConcretization.ConcretizationContext.InProgress = ImmutableDictionary.Empty
|
||||
TypeConcretization.ConcretizationContext.ConcreteTypes = concreteTypes
|
||||
TypeConcretization.ConcretizationContext.LoadedAssemblies = assemblies
|
||||
TypeConcretization.ConcretizationContext.BaseTypes = corelib
|
||||
}
|
||||
|
||||
// The field type might reference generic parameters of the declaring type
|
||||
let typeGenerics = declaringType.Generics |> ImmutableArray.CreateRange
|
||||
let methodGenerics = ImmutableArray.Empty // Fields don't have method generics
|
||||
|
||||
let loadAssembly
|
||||
(assyName : AssemblyName)
|
||||
(ref : AssemblyReferenceHandle)
|
||||
: (ImmutableDictionary<string, DumpedAssembly> * DumpedAssembly)
|
||||
=
|
||||
match assemblies.TryGetValue assyName.FullName with
|
||||
| true, currentAssy ->
|
||||
let targetAssyRef = currentAssy.AssemblyReferences.[ref]
|
||||
|
||||
match assemblies.TryGetValue targetAssyRef.Name.FullName with
|
||||
| true, targetAssy -> assemblies, targetAssy
|
||||
| false, _ ->
|
||||
failwithf "Assembly %s not loaded when trying to resolve reference" targetAssyRef.Name.FullName
|
||||
| false, _ -> failwithf "Current assembly %s not loaded when trying to resolve reference" assyName.FullName
|
||||
|
||||
let handle, newCtx =
|
||||
TypeConcretization.concretizeType
|
||||
ctx
|
||||
loadAssembly
|
||||
declaringType.Assembly
|
||||
typeGenerics
|
||||
methodGenerics
|
||||
fieldType
|
||||
|
||||
handle, newCtx.ConcreteTypes
|
||||
let rec zeroOf (concreteTypes : AllConcreteTypes) (cth : ConcreteTypeHandle) : CliType =
|
||||
let ty = AllConcreteTypes.lookup cth concreteTypes |> Option.get
|
||||
failwith "TODO"
|
||||
|
||||
@@ -114,26 +114,6 @@ module Corelib =
|
||||
|> Seq.choose (fun (KeyValue (_, v)) -> if v.Name = "RuntimeFieldHandle" then Some v else None)
|
||||
|> Seq.exactlyOne
|
||||
|
||||
let voidType =
|
||||
corelib.TypeDefs
|
||||
|> Seq.choose (fun (KeyValue (_, v)) -> if v.Name = "Void" then Some v else None)
|
||||
|> Seq.exactlyOne
|
||||
|
||||
let typedReferenceType =
|
||||
corelib.TypeDefs
|
||||
|> Seq.choose (fun (KeyValue (_, v)) -> if v.Name = "TypedReference" then Some v else None)
|
||||
|> Seq.exactlyOne
|
||||
|
||||
let intPtrType =
|
||||
corelib.TypeDefs
|
||||
|> Seq.choose (fun (KeyValue (_, v)) -> if v.Name = "IntPtr" then Some v else None)
|
||||
|> Seq.exactlyOne
|
||||
|
||||
let uintPtrType =
|
||||
corelib.TypeDefs
|
||||
|> Seq.choose (fun (KeyValue (_, v)) -> if v.Name = "UIntPtr" then Some v else None)
|
||||
|> Seq.exactlyOne
|
||||
|
||||
{
|
||||
Corelib = corelib
|
||||
String = stringType
|
||||
@@ -158,8 +138,4 @@ module Corelib =
|
||||
RuntimeMethodHandle = runtimeMethodHandleType
|
||||
RuntimeFieldHandle = runtimeFieldHandleType
|
||||
RuntimeType = runtimeTypeType
|
||||
Void = voidType
|
||||
TypedReference = typedReferenceType
|
||||
IntPtr = intPtrType
|
||||
UIntPtr = uintPtrType
|
||||
}
|
||||
|
||||
@@ -10,8 +10,7 @@ type EvalStackValue =
|
||||
| ObjectRef of ManagedHeapAddress
|
||||
// Fraser thinks this isn't really a thing in CoreCLR
|
||||
// | TransientPointer of TransientPointerSource
|
||||
/// Mapping of field name to value
|
||||
| UserDefinedValueType of (string * EvalStackValue) list
|
||||
| UserDefinedValueType of EvalStackValue list
|
||||
|
||||
override this.ToString () =
|
||||
match this with
|
||||
@@ -22,11 +21,7 @@ type EvalStackValue =
|
||||
| EvalStackValue.ManagedPointer managedPointerSource -> $"Pointer(%O{managedPointerSource})"
|
||||
| EvalStackValue.ObjectRef managedHeapAddress -> $"ObjectRef(%O{managedHeapAddress})"
|
||||
| EvalStackValue.UserDefinedValueType evalStackValues ->
|
||||
let desc =
|
||||
evalStackValues
|
||||
|> List.map (snd >> string<EvalStackValue>)
|
||||
|> String.concat " | "
|
||||
|
||||
let desc = evalStackValues |> List.map string<EvalStackValue> |> String.concat " | "
|
||||
$"Struct(%s{desc})"
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
@@ -92,8 +87,8 @@ module EvalStackValue =
|
||||
/// Then truncates to int64.
|
||||
let convToUInt64 (value : EvalStackValue) : int64 option =
|
||||
match value with
|
||||
| EvalStackValue.Int32 i -> Some (int64 (uint32 i))
|
||||
| EvalStackValue.Int64 int64 -> Some int64
|
||||
| EvalStackValue.Int32 i -> if i >= 0 then Some (int64 i) else failwith "TODO"
|
||||
| EvalStackValue.Int64 int64 -> failwith "todo"
|
||||
| EvalStackValue.NativeInt nativeIntSource -> failwith "todo"
|
||||
| EvalStackValue.Float f -> failwith "todo"
|
||||
| EvalStackValue.ManagedPointer managedPointerSource -> failwith "todo"
|
||||
@@ -107,7 +102,7 @@ module EvalStackValue =
|
||||
| CliNumericType.Int32 _ ->
|
||||
match popped with
|
||||
| EvalStackValue.Int32 i -> CliType.Numeric (CliNumericType.Int32 i)
|
||||
| EvalStackValue.UserDefinedValueType [ popped ] -> toCliTypeCoerced target (snd popped)
|
||||
| EvalStackValue.UserDefinedValueType [ popped ] -> toCliTypeCoerced target popped
|
||||
| i -> failwith $"TODO: %O{i}"
|
||||
| CliNumericType.Int64 _ ->
|
||||
match popped with
|
||||
@@ -182,7 +177,7 @@ module EvalStackValue =
|
||||
| _ -> failwith "TODO"
|
||||
| EvalStackValue.UserDefinedValueType fields ->
|
||||
match fields with
|
||||
| [ esv ] -> toCliTypeCoerced target (snd esv)
|
||||
| [ esv ] -> toCliTypeCoerced target esv
|
||||
| fields -> failwith $"TODO: don't know how to coerce struct of {fields} to a pointer"
|
||||
| _ -> failwith $"TODO: {popped}"
|
||||
| CliType.Bool _ ->
|
||||
@@ -207,10 +202,7 @@ module EvalStackValue =
|
||||
CliRuntimePointerSource.Argument (sourceThread, methodFrame, var)
|
||||
|> CliRuntimePointer.Managed
|
||||
|> CliType.RuntimePointer
|
||||
| ManagedPointerSource.ArrayIndex (arr, index) ->
|
||||
CliRuntimePointerSource.ArrayIndex (arr, index)
|
||||
|> CliRuntimePointer.Managed
|
||||
|> CliType.RuntimePointer
|
||||
| ManagedPointerSource.ArrayIndex _ -> failwith "TODO"
|
||||
| EvalStackValue.NativeInt intSrc ->
|
||||
match intSrc with
|
||||
| NativeIntSource.Verbatim i -> CliType.RuntimePointer (CliRuntimePointer.Unmanaged i)
|
||||
@@ -242,22 +234,12 @@ module EvalStackValue =
|
||||
match popped with
|
||||
| EvalStackValue.UserDefinedValueType popped ->
|
||||
if fields.Length <> popped.Length then
|
||||
failwith
|
||||
$"mismatch: popped value type {popped} (length %i{popped.Length}) into {fields} (length %i{fields.Length})"
|
||||
failwith "mismatch"
|
||||
|
||||
List.map2
|
||||
(fun (name1, v1) (name2, v2) ->
|
||||
if name1 <> name2 then
|
||||
failwith $"TODO: name mismatch, {name1} vs {name2}"
|
||||
|
||||
name1, toCliTypeCoerced v1 v2
|
||||
)
|
||||
fields
|
||||
popped
|
||||
|> CliType.ValueType
|
||||
List.map2 toCliTypeCoerced fields popped |> CliType.ValueType
|
||||
| popped ->
|
||||
match fields with
|
||||
| [ _, target ] -> toCliTypeCoerced target popped
|
||||
| [ target ] -> toCliTypeCoerced target popped
|
||||
| _ -> failwith $"TODO: {popped} into value type {target}"
|
||||
|
||||
let rec ofCliType (v : CliType) : EvalStackValue =
|
||||
@@ -298,10 +280,7 @@ module EvalStackValue =
|
||||
|> EvalStackValue.ManagedPointer
|
||||
| CliRuntimePointerSource.Heap addr -> EvalStackValue.ObjectRef addr
|
||||
| CliRuntimePointerSource.Null -> EvalStackValue.ManagedPointer ManagedPointerSource.Null
|
||||
| CliType.ValueType fields ->
|
||||
fields
|
||||
|> List.map (fun (name, f) -> name, ofCliType f)
|
||||
|> EvalStackValue.UserDefinedValueType
|
||||
| CliType.ValueType fields -> fields |> List.map ofCliType |> EvalStackValue.UserDefinedValueType
|
||||
|
||||
type EvalStack =
|
||||
{
|
||||
|
||||
@@ -151,4 +151,4 @@ module EvalStackValueComparisons =
|
||||
| EvalStackValue.ManagedPointer var1, EvalStackValue.NativeInt var2 ->
|
||||
failwith $"TODO (CEQ): managed pointer vs nativeint"
|
||||
| EvalStackValue.ManagedPointer _, _ -> failwith $"bad ceq: ManagedPointer vs {var2}"
|
||||
| EvalStackValue.UserDefinedValueType _, _ -> failwith $"bad ceq: {var1} vs {var2}"
|
||||
| EvalStackValue.UserDefinedValueType _, _ -> failwith $"bad ceq: UserDefinedValueType vs {var2}"
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
namespace WoofWare.PawPrint
|
||||
|
||||
open System
|
||||
open System.Collections.Immutable
|
||||
|
||||
/// Represents a location in the code where an exception occurred
|
||||
type ExceptionStackFrame<'typeGen, 'methodGen, 'methodVar
|
||||
when 'typeGen : comparison and 'typeGen :> IComparable<'typeGen>> =
|
||||
type ExceptionStackFrame =
|
||||
{
|
||||
Method : WoofWare.PawPrint.MethodInfo<'typeGen, 'methodGen, 'methodVar>
|
||||
Method : WoofWare.PawPrint.MethodInfo<ConcreteTypeHandle, ConcreteTypeHandle, ConcreteTypeHandle>
|
||||
/// The number of bytes into the IL of the method we were in
|
||||
IlOffset : int
|
||||
}
|
||||
|
||||
/// Represents a CLI exception being propagated
|
||||
type CliException<'typeGen, 'methodGen, 'methodVar when 'typeGen : comparison and 'typeGen :> IComparable<'typeGen>> =
|
||||
type CliException =
|
||||
{
|
||||
/// The exception object allocated on the heap
|
||||
ExceptionObject : ManagedHeapAddress
|
||||
/// Stack trace built during unwinding
|
||||
StackTrace : ExceptionStackFrame<'typeGen, 'methodGen, 'methodVar> list
|
||||
StackTrace : ExceptionStackFrame list
|
||||
}
|
||||
|
||||
/// Represents what to do after executing a finally/filter block
|
||||
type ExceptionContinuation<'typeGen, 'methodGen, 'methodVar
|
||||
when 'typeGen : comparison and 'typeGen :> IComparable<'typeGen>> =
|
||||
type ExceptionContinuation =
|
||||
| ResumeAfterFinally of targetPC : int
|
||||
| PropagatingException of exn : CliException<'typeGen, 'methodGen, 'methodVar>
|
||||
| ResumeAfterFilter of handlerPC : int * exn : CliException<'typeGen, 'methodGen, 'methodVar>
|
||||
| PropagatingException of exn : CliException
|
||||
| ResumeAfterFilter of handlerPC : int * exn : CliException
|
||||
|
||||
/// Helper functions for exception handling
|
||||
[<RequireQualifiedAccess>]
|
||||
@@ -47,7 +44,7 @@ module ExceptionHandling =
|
||||
let findExceptionHandler
|
||||
(currentPC : int)
|
||||
(exceptionTypeCrate : TypeInfoCrate)
|
||||
(method : WoofWare.PawPrint.MethodInfo<'typeGen, 'methodGeneric, 'methodVar>)
|
||||
(method : WoofWare.PawPrint.MethodInfo<'typeGeneric, 'methodGeneric, 'methodVar>)
|
||||
(assemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
: (WoofWare.PawPrint.ExceptionRegion * bool) option // handler, isFinally
|
||||
=
|
||||
@@ -125,7 +122,7 @@ module ExceptionHandling =
|
||||
/// Get the active exception regions at a given offset
|
||||
let getActiveRegionsAtOffset
|
||||
(offset : int)
|
||||
(method : WoofWare.PawPrint.MethodInfo<'a, 'b, 'c>)
|
||||
(method : WoofWare.PawPrint.MethodInfo<'typeGeneric, 'methodGeneric, 'methodVar>)
|
||||
: WoofWare.PawPrint.ExceptionRegion list
|
||||
=
|
||||
match method.Instructions with
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,7 +28,7 @@ and MethodState =
|
||||
/// Track which exception regions are currently active (innermost first)
|
||||
ActiveExceptionRegions : ExceptionRegion list
|
||||
/// When executing a finally/fault/filter, we need to know where to return
|
||||
ExceptionContinuation : ExceptionContinuation<ConcreteTypeHandle, ConcreteTypeHandle, ConcreteTypeHandle> option
|
||||
ExceptionContinuation : ExceptionContinuation option
|
||||
}
|
||||
|
||||
member this.IlOpIndex = this._IlOpIndex
|
||||
@@ -64,7 +64,7 @@ and MethodState =
|
||||
EvaluationStack = EvalStack.Empty
|
||||
}
|
||||
|
||||
static member setExceptionContinuation (cont : ExceptionContinuation<_, _, _>) (state : MethodState) : MethodState =
|
||||
static member setExceptionContinuation (cont : ExceptionContinuation) (state : MethodState) : MethodState =
|
||||
{ state with
|
||||
ExceptionContinuation = Some cont
|
||||
}
|
||||
@@ -136,7 +136,7 @@ and MethodState =
|
||||
/// If `method` is an instance method, `args` must be of length 1+numParams.
|
||||
/// If `method` is static, `args` must be of length numParams.
|
||||
static member Empty
|
||||
(concreteTypes : AllConcreteTypes)
|
||||
(types : AllConcreteTypes)
|
||||
(corelib : BaseClassTypes<DumpedAssembly>)
|
||||
(loadedAssemblies : ImmutableDictionary<string, DumpedAssembly>)
|
||||
(containingAssembly : DumpedAssembly)
|
||||
@@ -165,18 +165,20 @@ and MethodState =
|
||||
// I think valid code should remain valid if we unconditionally localsInit - it should be undefined
|
||||
// to use an uninitialised value? Not checked this; TODO.
|
||||
|
||||
let requiredAssemblies = ResizeArray<WoofWare.PawPrint.AssemblyReference> ()
|
||||
|
||||
let localVars =
|
||||
let result = ImmutableArray.CreateBuilder ()
|
||||
|
||||
for var in localVariableSig do
|
||||
// Note: This assumes all types have already been concretized
|
||||
// If this fails with "ConcreteTypeHandle not found", it means
|
||||
// we need to ensure types are concretized before creating the MethodState
|
||||
let zero, _ = CliType.zeroOf concreteTypes loadedAssemblies corelib var
|
||||
result.Add zero
|
||||
CliType.zeroOf types var |> result.Add
|
||||
|
||||
result.ToImmutable ()
|
||||
|
||||
if requiredAssemblies.Count > 0 then
|
||||
Error (requiredAssemblies |> Seq.toList)
|
||||
else
|
||||
|
||||
let activeRegions = ExceptionHandling.getActiveRegionsAtOffset 0 method
|
||||
|
||||
{
|
||||
|
||||
@@ -438,8 +438,8 @@ module NullaryIlOp =
|
||||
|> Tuple.withRight WhatWeDid.Executed
|
||||
|> ExecutionResult.Stepped
|
||||
| Sub ->
|
||||
let val2, state = IlMachineState.popEvalStack currentThread state
|
||||
let val1, state = IlMachineState.popEvalStack currentThread state
|
||||
let val2, state = IlMachineState.popEvalStack currentThread state
|
||||
let result = BinaryArithmetic.execute ArithmeticOperation.sub val1 val2
|
||||
|
||||
state
|
||||
@@ -475,119 +475,11 @@ module NullaryIlOp =
|
||||
| Mul_ovf_un -> failwith "TODO: Mul_ovf_un unimplemented"
|
||||
| Div -> failwith "TODO: Div unimplemented"
|
||||
| Div_un -> failwith "TODO: Div_un unimplemented"
|
||||
| Shr ->
|
||||
let shift, state = IlMachineState.popEvalStack currentThread state
|
||||
let number, state = IlMachineState.popEvalStack currentThread state
|
||||
|
||||
let shift =
|
||||
match shift with
|
||||
| EvalStackValue.Int32 i -> i
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim i) -> int<int64> i
|
||||
| _ -> failwith $"Not allowed shift of {shift}"
|
||||
|
||||
let result =
|
||||
// See table III.6
|
||||
match number with
|
||||
| EvalStackValue.Int32 i -> i >>> shift |> EvalStackValue.Int32
|
||||
| EvalStackValue.Int64 i -> i >>> shift |> EvalStackValue.Int64
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim i) ->
|
||||
(i >>> shift) |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| _ -> failwith $"Not allowed to shift {number}"
|
||||
|
||||
let state =
|
||||
state
|
||||
|> IlMachineState.pushToEvalStack' result currentThread
|
||||
|> IlMachineState.advanceProgramCounter currentThread
|
||||
|
||||
(state, WhatWeDid.Executed) |> ExecutionResult.Stepped
|
||||
| Shr -> failwith "TODO: Shr unimplemented"
|
||||
| Shr_un -> failwith "TODO: Shr_un unimplemented"
|
||||
| Shl ->
|
||||
let shift, state = IlMachineState.popEvalStack currentThread state
|
||||
let number, state = IlMachineState.popEvalStack currentThread state
|
||||
|
||||
let shift =
|
||||
match shift with
|
||||
| EvalStackValue.Int32 i -> i
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim i) -> int<int64> i
|
||||
| _ -> failwith $"Not allowed shift of {shift}"
|
||||
|
||||
let result =
|
||||
// See table III.6
|
||||
match number with
|
||||
| EvalStackValue.Int32 i -> i <<< shift |> EvalStackValue.Int32
|
||||
| EvalStackValue.Int64 i -> i <<< shift |> EvalStackValue.Int64
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim i) ->
|
||||
(i <<< shift) |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| _ -> failwith $"Not allowed to shift {number}"
|
||||
|
||||
let state =
|
||||
state
|
||||
|> IlMachineState.pushToEvalStack' result currentThread
|
||||
|> IlMachineState.advanceProgramCounter currentThread
|
||||
|
||||
(state, WhatWeDid.Executed) |> ExecutionResult.Stepped
|
||||
| And ->
|
||||
let v2, state = IlMachineState.popEvalStack currentThread state
|
||||
let v1, state = IlMachineState.popEvalStack currentThread state
|
||||
|
||||
let result =
|
||||
match v1, v2 with
|
||||
| EvalStackValue.Int32 v1, EvalStackValue.Int32 v2 -> v1 &&& v2 |> EvalStackValue.Int32
|
||||
| EvalStackValue.Int32 v1, EvalStackValue.NativeInt (NativeIntSource.Verbatim v2) ->
|
||||
int64<int32> v1 &&& v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.Int32 _, EvalStackValue.NativeInt _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v2}"
|
||||
| EvalStackValue.Int64 v1, EvalStackValue.Int64 v2 -> v1 &&& v2 |> EvalStackValue.Int64
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim v1), EvalStackValue.Int32 v2 ->
|
||||
v1 &&& int64<int32> v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.NativeInt _, EvalStackValue.Int32 _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v1}"
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim v1),
|
||||
EvalStackValue.NativeInt (NativeIntSource.Verbatim v2) ->
|
||||
v1 &&& v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim _), EvalStackValue.NativeInt _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v2}"
|
||||
| EvalStackValue.NativeInt _, EvalStackValue.NativeInt (NativeIntSource.Verbatim _) ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v1}"
|
||||
| _, _ -> failwith $"refusing to do binary operation on {v1} and {v2}"
|
||||
|
||||
let state =
|
||||
state
|
||||
|> IlMachineState.pushToEvalStack' result currentThread
|
||||
|> IlMachineState.advanceProgramCounter currentThread
|
||||
|
||||
(state, WhatWeDid.Executed) |> ExecutionResult.Stepped
|
||||
| Or ->
|
||||
let v2, state = IlMachineState.popEvalStack currentThread state
|
||||
let v1, state = IlMachineState.popEvalStack currentThread state
|
||||
|
||||
let result =
|
||||
match v1, v2 with
|
||||
| EvalStackValue.Int32 v1, EvalStackValue.Int32 v2 -> v1 ||| v2 |> EvalStackValue.Int32
|
||||
| EvalStackValue.Int32 v1, EvalStackValue.NativeInt (NativeIntSource.Verbatim v2) ->
|
||||
int64<int32> v1 ||| v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.Int32 _, EvalStackValue.NativeInt _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v2}"
|
||||
| EvalStackValue.Int64 v1, EvalStackValue.Int64 v2 -> v1 ||| v2 |> EvalStackValue.Int64
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim v1), EvalStackValue.Int32 v2 ->
|
||||
v1 ||| int64<int32> v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.NativeInt _, EvalStackValue.Int32 _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v1}"
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim v1),
|
||||
EvalStackValue.NativeInt (NativeIntSource.Verbatim v2) ->
|
||||
v1 ||| v2 |> NativeIntSource.Verbatim |> EvalStackValue.NativeInt
|
||||
| EvalStackValue.NativeInt (NativeIntSource.Verbatim _), EvalStackValue.NativeInt _ ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v2}"
|
||||
| EvalStackValue.NativeInt _, EvalStackValue.NativeInt (NativeIntSource.Verbatim _) ->
|
||||
failwith $"can't do binary operation on non-verbatim native int {v1}"
|
||||
| _, _ -> failwith $"refusing to do binary operation on {v1} and {v2}"
|
||||
|
||||
let state =
|
||||
state
|
||||
|> IlMachineState.pushToEvalStack' result currentThread
|
||||
|> IlMachineState.advanceProgramCounter currentThread
|
||||
|
||||
(state, WhatWeDid.Executed) |> ExecutionResult.Stepped
|
||||
| Shl -> failwith "TODO: Shl unimplemented"
|
||||
| And -> failwith "TODO: And unimplemented"
|
||||
| Or -> failwith "TODO: Or unimplemented"
|
||||
| Xor -> failwith "TODO: Xor unimplemented"
|
||||
| Conv_I ->
|
||||
let popped, state = IlMachineState.popEvalStack currentThread state
|
||||
|
||||
@@ -17,7 +17,11 @@ module Program =
|
||||
let argsAllocations, state =
|
||||
(state, args)
|
||||
||> Seq.mapFold (fun state arg ->
|
||||
IlMachineState.allocateManagedObject corelib.String (failwith "TODO: assert fields and populate") state
|
||||
IlMachineState.allocateManagedObject
|
||||
(corelib.String
|
||||
|> TypeInfo.mapGeneric (fun _ _ -> failwith "there are no generics here"))
|
||||
(failwith "TODO: assert fields and populate")
|
||||
state
|
||||
// TODO: set the char values in memory
|
||||
)
|
||||
|
||||
@@ -79,177 +83,77 @@ module Program =
|
||||
| None -> failwith "No entry point in input DLL"
|
||||
| Some d -> d
|
||||
|
||||
let mainMethodFromMetadata = dumped.Methods.[entryPoint]
|
||||
let mainMethod = dumped.Methods.[entryPoint]
|
||||
|
||||
if mainMethodFromMetadata.Signature.GenericParameterCount > 0 then
|
||||
if mainMethod.Signature.GenericParameterCount > 0 then
|
||||
failwith "Refusing to execute generic main method"
|
||||
|
||||
let state = IlMachineState.initial loggerFactory dotnetRuntimeDirs dumped
|
||||
|
||||
// Find the core library by traversing the type hierarchy of the main method's declaring type
|
||||
// until we reach System.Object
|
||||
let rec handleBaseTypeInfo
|
||||
(state : IlMachineState)
|
||||
(baseTypeInfo : BaseTypeInfo)
|
||||
(currentAssembly : DumpedAssembly)
|
||||
(continueWithGeneric :
|
||||
IlMachineState
|
||||
-> TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>
|
||||
-> DumpedAssembly
|
||||
-> IlMachineState * BaseClassTypes<DumpedAssembly> option)
|
||||
(continueWithResolved :
|
||||
IlMachineState
|
||||
-> TypeInfo<TypeDefn, TypeDefn>
|
||||
-> DumpedAssembly
|
||||
-> IlMachineState * BaseClassTypes<DumpedAssembly> option)
|
||||
: IlMachineState * BaseClassTypes<DumpedAssembly> option
|
||||
=
|
||||
match baseTypeInfo with
|
||||
| BaseTypeInfo.TypeRef typeRefHandle ->
|
||||
// Look up the TypeRef from the handle
|
||||
let typeRef = currentAssembly.TypeRefs.[typeRefHandle]
|
||||
let mainMethod' =
|
||||
mainMethod
|
||||
|> MethodInfo.mapTypeGenerics (fun _ -> failwith "Refusing to execute generic main method")
|
||||
|> MethodInfo.mapMethodGenerics (fun _ -> failwith "Refusing to execute generic main method")
|
||||
|
||||
let rec go state =
|
||||
// Resolve the type reference to find which assembly it's in
|
||||
match
|
||||
Assembly.resolveTypeRef state._LoadedAssemblies currentAssembly typeRef ImmutableArray.Empty
|
||||
with
|
||||
| TypeResolutionResult.FirstLoadAssy assyRef ->
|
||||
// Need to load this assembly first
|
||||
let handle, definedIn = assyRef.Handle
|
||||
|
||||
let state, _, _ =
|
||||
IlMachineState.loadAssembly
|
||||
loggerFactory
|
||||
state._LoadedAssemblies.[definedIn.FullName]
|
||||
handle
|
||||
state
|
||||
|
||||
go state
|
||||
| TypeResolutionResult.Resolved (resolvedAssembly, resolvedType) ->
|
||||
continueWithResolved state resolvedType resolvedAssembly
|
||||
|
||||
go state
|
||||
| BaseTypeInfo.TypeDef typeDefHandle ->
|
||||
// Base type is in the same assembly
|
||||
let baseType = currentAssembly.TypeDefs.[typeDefHandle]
|
||||
continueWithGeneric state baseType currentAssembly
|
||||
| BaseTypeInfo.TypeSpec _ -> failwith "Type specs not yet supported in base type traversal"
|
||||
| BaseTypeInfo.ForeignAssemblyType (assemblyName, typeDefHandle) ->
|
||||
// Base type is in a foreign assembly
|
||||
match state._LoadedAssemblies.TryGetValue assemblyName.FullName with
|
||||
| true, foreignAssembly ->
|
||||
let baseType = foreignAssembly.TypeDefs.[typeDefHandle]
|
||||
continueWithGeneric state baseType foreignAssembly
|
||||
| false, _ -> failwith $"Foreign assembly {assemblyName.FullName} not loaded"
|
||||
|
||||
let rec findCoreLibraryAssemblyFromGeneric
|
||||
(state : IlMachineState)
|
||||
(currentType : TypeInfo<WoofWare.PawPrint.GenericParameter, TypeDefn>)
|
||||
(currentAssembly : DumpedAssembly)
|
||||
=
|
||||
match currentType.BaseType with
|
||||
| None ->
|
||||
// We've reached the root (System.Object), so this assembly contains the core library
|
||||
let baseTypes = Corelib.getBaseTypes currentAssembly
|
||||
state, Some baseTypes
|
||||
| Some baseTypeInfo ->
|
||||
handleBaseTypeInfo
|
||||
state
|
||||
baseTypeInfo
|
||||
currentAssembly
|
||||
findCoreLibraryAssemblyFromGeneric
|
||||
findCoreLibraryAssemblyFromResolved
|
||||
|
||||
and findCoreLibraryAssemblyFromResolved
|
||||
(state : IlMachineState)
|
||||
(currentType : TypeInfo<TypeDefn, TypeDefn>)
|
||||
(currentAssembly : DumpedAssembly)
|
||||
=
|
||||
match currentType.BaseType with
|
||||
| None ->
|
||||
// We've reached the root (System.Object), so this assembly contains the core library
|
||||
let baseTypes = Corelib.getBaseTypes currentAssembly
|
||||
state, Some baseTypes
|
||||
| Some baseTypeInfo ->
|
||||
handleBaseTypeInfo
|
||||
state
|
||||
baseTypeInfo
|
||||
currentAssembly
|
||||
findCoreLibraryAssemblyFromGeneric
|
||||
findCoreLibraryAssemblyFromResolved
|
||||
let mainMethod, state =
|
||||
mainMethod'
|
||||
|> MethodInfo.mapVarGenerics state (fun state generic -> failwith "")
|
||||
|
||||
let rec computeState (baseClassTypes : BaseClassTypes<DumpedAssembly> option) (state : IlMachineState) =
|
||||
match baseClassTypes with
|
||||
| Some baseTypes ->
|
||||
// We already have base class types, can directly create the concretized method
|
||||
// Use the original method from metadata, but convert FakeUnit to TypeDefn
|
||||
let rawMainMethod =
|
||||
mainMethodFromMetadata
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
// The thread's state is slightly fake: we will need to put arguments onto the stack before actually
|
||||
// executing the main method.
|
||||
// We construct the thread here before we are entirely ready, because we need a thread from which to
|
||||
// initialise the class containing the main method.
|
||||
// Once we've obtained e.g. the String and Array classes, we can populate the args array.
|
||||
match
|
||||
MethodState.Empty
|
||||
state.ConcreteTypes
|
||||
(Option.toObj baseClassTypes)
|
||||
state._LoadedAssemblies
|
||||
dumped
|
||||
// pretend there are no instructions, so we avoid preparing anything
|
||||
{ mainMethod with
|
||||
Instructions = Some (MethodInstructions.onlyRet ())
|
||||
}
|
||||
ImmutableArray.Empty
|
||||
(ImmutableArray.CreateRange [ CliType.ObjectRef None ])
|
||||
None
|
||||
with
|
||||
| Ok meth -> IlMachineState.addThread meth dumped.Name state, baseClassTypes
|
||||
| Error requiresRefs ->
|
||||
let state =
|
||||
(state, requiresRefs)
|
||||
||> List.fold (fun state ref ->
|
||||
let handle, referencingAssy = ref.Handle
|
||||
let referencingAssy = state.LoadedAssembly referencingAssy |> Option.get
|
||||
|
||||
let state, _, _ =
|
||||
IlMachineState.loadAssembly loggerFactory referencingAssy handle state
|
||||
|
||||
let state, concretizedMainMethod, _ =
|
||||
IlMachineState.concretizeMethodWithTypeGenerics
|
||||
loggerFactory
|
||||
baseTypes
|
||||
ImmutableArray.Empty // No type generics for main method's declaring type
|
||||
{ rawMainMethod with
|
||||
Instructions = Some (MethodInstructions.onlyRet ())
|
||||
}
|
||||
None
|
||||
dumped.Name
|
||||
ImmutableArray.Empty
|
||||
state
|
||||
)
|
||||
|
||||
// Create the method state with the concretized method
|
||||
match
|
||||
MethodState.Empty
|
||||
state.ConcreteTypes
|
||||
baseTypes
|
||||
state._LoadedAssemblies
|
||||
dumped
|
||||
concretizedMainMethod
|
||||
ImmutableArray.Empty
|
||||
(ImmutableArray.CreateRange [ CliType.ObjectRef None ])
|
||||
None
|
||||
with
|
||||
| Ok concretizedMeth -> IlMachineState.addThread concretizedMeth dumped.Name state, Some baseTypes
|
||||
| Error _ -> failwith "Unexpected failure creating method state with concretized method"
|
||||
| None ->
|
||||
// We need to discover the core library by traversing the type hierarchy
|
||||
let mainMethodType =
|
||||
dumped.TypeDefs.[mainMethodFromMetadata.DeclaringType.Definition.Get]
|
||||
let corelib =
|
||||
let coreLib =
|
||||
state._LoadedAssemblies.Keys
|
||||
|> Seq.tryFind (fun x -> x.StartsWith ("System.Private.CoreLib, ", StringComparison.Ordinal))
|
||||
|
||||
let state, baseTypes =
|
||||
findCoreLibraryAssemblyFromGeneric state mainMethodType dumped
|
||||
coreLib
|
||||
|> Option.map (fun coreLib -> state._LoadedAssemblies.[coreLib] |> Corelib.getBaseTypes)
|
||||
|
||||
computeState baseTypes state
|
||||
computeState corelib state
|
||||
|
||||
let (state, mainThread), baseClassTypes = state |> computeState None
|
||||
|
||||
// Now that we have base class types, concretize the main method for use in the rest of the function
|
||||
let state, concretizedMainMethod, mainTypeHandle =
|
||||
match baseClassTypes with
|
||||
| Some baseTypes ->
|
||||
let rawMainMethod =
|
||||
mainMethodFromMetadata
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|
||||
IlMachineState.concretizeMethodWithTypeGenerics
|
||||
loggerFactory
|
||||
baseTypes
|
||||
ImmutableArray.Empty // No type generics for main method's declaring type
|
||||
rawMainMethod
|
||||
None
|
||||
dumped.Name
|
||||
ImmutableArray.Empty
|
||||
state
|
||||
| None -> failwith "Expected base class types to be available at this point"
|
||||
|
||||
let rec loadInitialState (state : IlMachineState) =
|
||||
match
|
||||
state
|
||||
|> IlMachineState.loadClass loggerFactory (Option.toObj baseClassTypes) mainTypeHandle mainThread
|
||||
|> IlMachineState.loadClass
|
||||
loggerFactory
|
||||
(Option.toObj baseClassTypes)
|
||||
(AllConcreteTypes.lookup' mainMethod.DeclaringType state.ConcreteTypes
|
||||
|> Option.get)
|
||||
mainThread
|
||||
with
|
||||
| StateLoadResult.NothingToDo ilMachineState -> ilMachineState
|
||||
| StateLoadResult.FirstLoadThis ilMachineState -> loadInitialState ilMachineState
|
||||
@@ -269,12 +173,12 @@ module Program =
|
||||
| Some c -> c
|
||||
|
||||
let arrayAllocation, state =
|
||||
match mainMethodFromMetadata.Signature.ParameterTypes |> Seq.toList with
|
||||
match mainMethod'.Signature.ParameterTypes |> Seq.toList with
|
||||
| [ TypeDefn.OneDimensionalArrayLowerBoundZero (TypeDefn.PrimitiveType PrimitiveType.String) ] ->
|
||||
allocateArgs argv baseClassTypes state
|
||||
| _ -> failwith "Main method must take an array of strings; other signatures not yet implemented"
|
||||
|
||||
match mainMethodFromMetadata.Signature.ReturnType with
|
||||
match mainMethod'.Signature.ReturnType with
|
||||
| TypeDefn.PrimitiveType PrimitiveType.Int32 -> ()
|
||||
| _ -> failwith "Main method must return int32; other types not currently supported"
|
||||
|
||||
@@ -287,7 +191,7 @@ module Program =
|
||||
logger.LogInformation "Main method class now initialised"
|
||||
|
||||
// Now that BCL initialisation has taken place and the user-code classes are constructed,
|
||||
// overwrite the main thread completely using the already-concretized method.
|
||||
// overwrite the main thread completely.
|
||||
let methodState =
|
||||
match
|
||||
MethodState.Empty
|
||||
@@ -295,7 +199,7 @@ module Program =
|
||||
baseClassTypes
|
||||
state._LoadedAssemblies
|
||||
dumped
|
||||
concretizedMainMethod
|
||||
mainMethod
|
||||
ImmutableArray.Empty
|
||||
(ImmutableArray.Create (CliType.OfManagedObject arrayAllocation))
|
||||
None
|
||||
@@ -313,7 +217,12 @@ module Program =
|
||||
{ state with
|
||||
ThreadState = state.ThreadState |> Map.add mainThread threadState
|
||||
}
|
||||
|> IlMachineState.ensureTypeInitialised loggerFactory baseClassTypes mainThread mainTypeHandle
|
||||
|> IlMachineState.ensureTypeInitialised
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
mainThread
|
||||
(AllConcreteTypes.lookup' methodState.ExecutingMethod.DeclaringType state.ConcreteTypes
|
||||
|> Option.get)
|
||||
|
||||
match init with
|
||||
| WhatWeDid.SuspendedForClassInit -> failwith "TODO: suspended for class init"
|
||||
|
||||
@@ -4,5 +4,3 @@ namespace WoofWare.PawPrint
|
||||
module internal Tuple =
|
||||
let withLeft<'a, 'b> (x : 'a) (y : 'b) : 'a * 'b = x, y
|
||||
let withRight<'a, 'b> (y : 'b) (x : 'a) = x, y
|
||||
let lmap<'a, 'b, 'c> (f : 'a -> 'c) (x : 'a, y : 'b) : 'c * 'b = f x, y
|
||||
let rmap<'a, 'b, 'c> (f : 'b -> 'c) (x : 'a, y : 'b) : 'a * 'c = x, f y
|
||||
|
||||
@@ -20,90 +20,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
match op with
|
||||
| Call ->
|
||||
let state, methodToCall, methodGenerics, typeArgsFromMetadata =
|
||||
match metadataToken with
|
||||
| MetadataToken.MethodSpecification h ->
|
||||
let spec = activeAssy.MethodSpecs.[h]
|
||||
|
||||
match spec.Method with
|
||||
| MetadataToken.MethodDef token ->
|
||||
let method =
|
||||
activeAssy.Methods.[token]
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|
||||
state, method, Some spec.Signature, None
|
||||
| MetadataToken.MemberReference ref ->
|
||||
let state, _, method, extractedTypeArgs =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
(state.ActiveAssembly thread)
|
||||
ref
|
||||
state
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Call a field"
|
||||
| Choice1Of2 method -> state, method, Some spec.Signature, Some extractedTypeArgs
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
| MetadataToken.MemberReference h ->
|
||||
let state, _, method, extractedTypeArgs =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
(state.ActiveAssembly thread)
|
||||
h
|
||||
state
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Call a field"
|
||||
| Choice1Of2 method -> state, method, None, Some extractedTypeArgs
|
||||
|
||||
| MetadataToken.MethodDef defn ->
|
||||
match activeAssy.Methods.TryGetValue defn with
|
||||
| true, method ->
|
||||
let method = method |> MethodInfo.mapTypeGenerics (fun _ -> failwith "not generic")
|
||||
state, method, None, None
|
||||
| false, _ -> failwith $"could not find method in {activeAssy.Name}"
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
|
||||
let state, concretizedMethod, declaringTypeHandle =
|
||||
IlMachineState.concretizeMethodForExecution
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
methodToCall
|
||||
methodGenerics
|
||||
typeArgsFromMetadata
|
||||
state
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes declaringTypeHandle thread state with
|
||||
| NothingToDo state ->
|
||||
let state, _ =
|
||||
state.WithThreadSwitchedToAssembly methodToCall.DeclaringType.Assembly thread
|
||||
|
||||
let threadState = state.ThreadState.[thread]
|
||||
|
||||
IlMachineState.callMethod
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
None
|
||||
None
|
||||
false
|
||||
true
|
||||
concretizedMethod.Generics
|
||||
concretizedMethod
|
||||
thread
|
||||
threadState
|
||||
state,
|
||||
WhatWeDid.Executed
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
|
||||
| Callvirt ->
|
||||
|
||||
// TODO: this is presumably super incomplete
|
||||
let state, methodToCall, methodGenerics, typeArgsFromMetadata =
|
||||
let state, methodToCall, methodGenerics =
|
||||
match metadataToken with
|
||||
| MetadataToken.MethodSpecification h ->
|
||||
let spec = activeAssy.MethodSpecs.[h]
|
||||
@@ -114,9 +31,74 @@ module internal UnaryMetadataIlOp =
|
||||
activeAssy.Methods.[token]
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> spec.Signature.[i])
|
||||
|
||||
state, method, Some spec.Signature, None
|
||||
state, method, spec.Signature
|
||||
| MetadataToken.MemberReference ref ->
|
||||
let state, _, method, extractedTypeArgs =
|
||||
let state, _, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
(state.ActiveAssembly thread)
|
||||
ref
|
||||
state
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Call a field"
|
||||
| Choice1Of2 method -> state, method, spec.Signature
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
| MetadataToken.MemberReference h ->
|
||||
let state, _, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
(state.ActiveAssembly thread)
|
||||
h
|
||||
state
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Call a field"
|
||||
| Choice1Of2 method -> state, method, ImmutableArray.Empty
|
||||
|
||||
| MetadataToken.MethodDef defn ->
|
||||
match activeAssy.Methods.TryGetValue defn with
|
||||
| true, method ->
|
||||
let method = method |> MethodInfo.mapTypeGenerics (fun _ -> failwith "not generic")
|
||||
state, method, ImmutableArray.Empty
|
||||
| false, _ -> failwith $"could not find method in {activeAssy.Name}"
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes methodToCall.DeclaringType thread state with
|
||||
| NothingToDo state ->
|
||||
state.WithThreadSwitchedToAssembly methodToCall.DeclaringType.Assembly thread
|
||||
|> fst
|
||||
|> IlMachineState.callMethodInActiveAssembly
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
true
|
||||
methodGenerics
|
||||
methodToCall
|
||||
None
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
|
||||
| Callvirt ->
|
||||
|
||||
// TODO: this is presumably super incomplete
|
||||
let state, method, generics =
|
||||
match metadataToken with
|
||||
| MetadataToken.MethodSpecification h ->
|
||||
let spec = activeAssy.MethodSpecs.[h]
|
||||
|
||||
match spec.Method with
|
||||
| MetadataToken.MethodDef token ->
|
||||
let method =
|
||||
activeAssy.Methods.[token]
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> spec.Signature.[i])
|
||||
|
||||
state, method, spec.Signature
|
||||
| MetadataToken.MemberReference ref ->
|
||||
let state, _, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
@@ -127,10 +109,10 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Callvirt a field"
|
||||
| Choice1Of2 method -> state, method, Some spec.Signature, Some extractedTypeArgs
|
||||
| Choice1Of2 method -> state, method, spec.Signature
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
| MetadataToken.MemberReference h ->
|
||||
let state, _, method, extractedTypeArgs =
|
||||
let state, _, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
@@ -141,58 +123,35 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
match method with
|
||||
| Choice2Of2 _field -> failwith "tried to Callvirt a field"
|
||||
| Choice1Of2 method -> state, method, None, Some extractedTypeArgs
|
||||
| Choice1Of2 method -> state, method, ImmutableArray.Empty
|
||||
|
||||
| MetadataToken.MethodDef defn ->
|
||||
match activeAssy.Methods.TryGetValue defn with
|
||||
| true, method ->
|
||||
let method = method |> MethodInfo.mapTypeGenerics (fun _ -> failwith "not generic")
|
||||
state, method, None, None
|
||||
state, method, ImmutableArray.Empty
|
||||
| false, _ -> failwith $"could not find method in {activeAssy.Name}"
|
||||
| k -> failwith $"Unrecognised kind: %O{k}"
|
||||
|
||||
// TODO: this is pretty inefficient, we're concretising here and then immediately after in callMethodInActiveAssembly
|
||||
let state, concretizedMethod, declaringTypeHandle =
|
||||
IlMachineState.concretizeMethodForExecution
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
methodToCall
|
||||
methodGenerics
|
||||
typeArgsFromMetadata
|
||||
state
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes declaringTypeHandle thread state with
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes method.DeclaringType thread state with
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
| NothingToDo state ->
|
||||
|
||||
state.WithThreadSwitchedToAssembly methodToCall.DeclaringType.Assembly thread
|
||||
state.WithThreadSwitchedToAssembly method.DeclaringType.Assembly thread
|
||||
|> fst
|
||||
|> IlMachineState.callMethodInActiveAssembly
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
true
|
||||
methodGenerics
|
||||
methodToCall
|
||||
None
|
||||
typeArgsFromMetadata
|
||||
|> IlMachineState.callMethodInActiveAssembly loggerFactory baseClassTypes thread true generics method None
|
||||
|
||||
| Castclass -> failwith "TODO: Castclass unimplemented"
|
||||
| Newobj ->
|
||||
let logger = loggerFactory.CreateLogger "Newobj"
|
||||
|
||||
let state, assy, ctor, typeArgsFromMetadata =
|
||||
let state, assy, ctor =
|
||||
match metadataToken with
|
||||
| MethodDef md ->
|
||||
let method = activeAssy.Methods.[md]
|
||||
|
||||
state,
|
||||
activeAssy.Name,
|
||||
MethodInfo.mapTypeGenerics (fun _ -> failwith "non-generic method") method,
|
||||
None
|
||||
state, activeAssy.Name, MethodInfo.mapTypeGenerics (fun _ -> failwith "non-generic method") method
|
||||
| MemberReference mr ->
|
||||
let state, name, method, extractedTypeArgs =
|
||||
let state, name, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
@@ -202,24 +161,12 @@ module internal UnaryMetadataIlOp =
|
||||
state
|
||||
|
||||
match method with
|
||||
| Choice1Of2 mr -> state, name, mr, Some extractedTypeArgs
|
||||
| Choice1Of2 mr -> state, name, mr
|
||||
| Choice2Of2 _field -> failwith "unexpectedly NewObj found a constructor which is a field"
|
||||
| x -> failwith $"Unexpected metadata token for constructor: %O{x}"
|
||||
|
||||
let currentMethod = state.ThreadState.[thread].MethodState.ExecutingMethod
|
||||
|
||||
let state, concretizedCtor, declaringTypeHandle =
|
||||
IlMachineState.concretizeMethodForExecution
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
ctor
|
||||
None
|
||||
typeArgsFromMetadata
|
||||
state
|
||||
|
||||
let state, init =
|
||||
IlMachineState.ensureTypeInitialised loggerFactory baseClassTypes thread declaringTypeHandle state
|
||||
IlMachineState.ensureTypeInitialised loggerFactory baseClassTypes thread ctor.DeclaringType state
|
||||
|
||||
match init with
|
||||
| WhatWeDid.BlockedOnClassInit state -> failwith "TODO: another thread is running the initialiser"
|
||||
@@ -236,8 +183,7 @@ module internal UnaryMetadataIlOp =
|
||||
ctorType.Name
|
||||
)
|
||||
|
||||
let typeGenerics =
|
||||
concretizedCtor.DeclaringType.Generics |> ImmutableArray.CreateRange
|
||||
let typeGenerics = ctor.DeclaringType.Generics |> ImmutableArray.CreateRange
|
||||
|
||||
let state, fieldZeros =
|
||||
((state, []), ctorType.Fields)
|
||||
@@ -280,10 +226,9 @@ module internal UnaryMetadataIlOp =
|
||||
baseClassTypes
|
||||
thread
|
||||
true
|
||||
None
|
||||
ImmutableArray.Empty
|
||||
ctor
|
||||
(Some allocatedAddr)
|
||||
typeArgsFromMetadata
|
||||
|
||||
match whatWeDid with
|
||||
| SuspendedForClassInit -> failwith "unexpectedly suspended while initialising constructor"
|
||||
@@ -325,30 +270,14 @@ module internal UnaryMetadataIlOp =
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> failwith "TODO: delegate"
|
||||
|
||||
let result =
|
||||
if defn.Generics.IsEmpty then
|
||||
TypeDefn.FromDefinition (
|
||||
ComparableTypeDefinitionHandle.Make defn.TypeDefHandle,
|
||||
defn.Assembly.FullName,
|
||||
signatureTypeKind
|
||||
)
|
||||
else
|
||||
// Preserve the generic instantiation by converting GenericParameters to TypeDefn.GenericTypeParameter
|
||||
let genericDef =
|
||||
TypeDefn.FromDefinition (
|
||||
ComparableTypeDefinitionHandle.Make defn.TypeDefHandle,
|
||||
defn.Assembly.FullName,
|
||||
signatureTypeKind
|
||||
)
|
||||
|
||||
let genericArgs =
|
||||
defn.Generics
|
||||
|> Seq.mapi (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|> ImmutableArray.CreateRange
|
||||
|
||||
TypeDefn.GenericInstantiation (genericDef, genericArgs)
|
||||
TypeDefn.FromDefinition (
|
||||
ComparableTypeDefinitionHandle.Make defn.TypeDefHandle,
|
||||
defn.Assembly.Name,
|
||||
signatureTypeKind
|
||||
)
|
||||
|
||||
state, result, assy
|
||||
| MetadataToken.TypeSpecification spec ->
|
||||
@@ -357,18 +286,6 @@ module internal UnaryMetadataIlOp =
|
||||
| MetadataToken.TypeReference ref ->
|
||||
let ref = state.ActiveAssembly(thread).TypeRefs.[ref]
|
||||
|
||||
// Convert ConcreteTypeHandles back to TypeDefn for metadata operations
|
||||
let typeGenerics =
|
||||
newMethodState.ExecutingMethod.DeclaringType.Generics
|
||||
|> Seq.map (fun handle ->
|
||||
Concretization.concreteHandleToTypeDefn
|
||||
baseClassTypes
|
||||
handle
|
||||
state.ConcreteTypes
|
||||
state._LoadedAssemblies
|
||||
)
|
||||
|> ImmutableArray.CreateRange
|
||||
|
||||
let state, assy, resolved =
|
||||
IlMachineState.resolveTypeFromRef
|
||||
loggerFactory
|
||||
@@ -386,7 +303,7 @@ module internal UnaryMetadataIlOp =
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> failwith "TODO: delegate"
|
||||
|
||||
let result =
|
||||
TypeDefn.FromDefinition (
|
||||
@@ -472,7 +389,7 @@ module internal UnaryMetadataIlOp =
|
||||
| ResolvedBaseType.Enum
|
||||
| ResolvedBaseType.ValueType -> SignatureTypeKind.ValueType
|
||||
| ResolvedBaseType.Object -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> SignatureTypeKind.Class
|
||||
| ResolvedBaseType.Delegate -> failwith "todo"
|
||||
|
||||
TypeDefn.FromDefinition (ComparableTypeDefinitionHandle.Make td, activeAssy.Name.FullName, sigType)
|
||||
| MetadataToken.TypeSpecification handle -> state.ActiveAssembly(thread).TypeSpecs.[handle].Signature
|
||||
@@ -514,7 +431,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
state, field
|
||||
| MetadataToken.MemberReference mr ->
|
||||
let state, _, field, _ =
|
||||
let state, _, field =
|
||||
IlMachineState.resolveMember loggerFactory baseClassTypes thread activeAssy mr state
|
||||
|
||||
match field with
|
||||
@@ -535,8 +452,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
let valueToStore, state = IlMachineState.popEvalStack thread state
|
||||
|
||||
let state, declaringTypeHandle, typeGenerics =
|
||||
IlMachineState.concretizeFieldForExecution loggerFactory baseClassTypes thread field state
|
||||
let typeGenerics = field.DeclaringType.Generics |> ImmutableArray.CreateRange
|
||||
|
||||
let state, zero =
|
||||
IlMachineState.cliTypeZeroOf
|
||||
@@ -554,7 +470,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
if field.Attributes.HasFlag FieldAttributes.Static then
|
||||
let state =
|
||||
IlMachineState.setStatic declaringTypeHandle field.Name valueToStore state
|
||||
IlMachineState.setStatic field.DeclaringType field.Name valueToStore state
|
||||
|
||||
state, WhatWeDid.Executed
|
||||
else
|
||||
@@ -611,7 +527,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
state, field
|
||||
| MetadataToken.MemberReference mr ->
|
||||
let state, _, method, _ =
|
||||
let state, _, method =
|
||||
IlMachineState.resolveMember
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
@@ -640,15 +556,17 @@ module internal UnaryMetadataIlOp =
|
||||
field.Signature
|
||||
)
|
||||
|
||||
let state, declaringTypeHandle, typeGenerics =
|
||||
IlMachineState.concretizeFieldForExecution loggerFactory baseClassTypes thread field state
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes declaringTypeHandle thread state with
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes field.DeclaringType thread state with
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
| NothingToDo state ->
|
||||
|
||||
let popped, state = IlMachineState.popEvalStack thread state
|
||||
|
||||
let typeGenerics =
|
||||
match field.DeclaringType.Generics with
|
||||
| [] -> None
|
||||
| l -> Some (ImmutableArray.CreateRange l)
|
||||
|
||||
let state, zero =
|
||||
IlMachineState.cliTypeZeroOf
|
||||
loggerFactory
|
||||
@@ -662,7 +580,7 @@ module internal UnaryMetadataIlOp =
|
||||
let toStore = EvalStackValue.toCliTypeCoerced zero popped
|
||||
|
||||
let state =
|
||||
IlMachineState.setStatic declaringTypeHandle field.Name toStore state
|
||||
IlMachineState.setStatic field.DeclaringType field.Name toStore state
|
||||
|> IlMachineState.advanceProgramCounter thread
|
||||
|
||||
state, WhatWeDid.Executed
|
||||
@@ -677,7 +595,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
state, field
|
||||
| MetadataToken.MemberReference mr ->
|
||||
let state, assyName, field, _ =
|
||||
let state, assyName, field =
|
||||
IlMachineState.resolveMember loggerFactory baseClassTypes thread activeAssy mr state
|
||||
|
||||
match field with
|
||||
@@ -699,15 +617,14 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
let currentObj, state = IlMachineState.popEvalStack thread state
|
||||
|
||||
let state, declaringTypeHandle, typeGenerics =
|
||||
IlMachineState.concretizeFieldForExecution loggerFactory baseClassTypes thread field state
|
||||
let typeGenerics =
|
||||
match field.DeclaringType.Generics with
|
||||
| [] -> None
|
||||
| l -> Some (ImmutableArray.CreateRange l)
|
||||
|
||||
if field.Attributes.HasFlag FieldAttributes.Static then
|
||||
let declaringTypeHandle, state =
|
||||
IlMachineState.concretizeFieldDeclaringType loggerFactory baseClassTypes field.DeclaringType state
|
||||
|
||||
let state, staticField =
|
||||
match IlMachineState.getStatic declaringTypeHandle field.Name state with
|
||||
match IlMachineState.getStatic field.DeclaringType field.Name state with
|
||||
| Some v -> state, v
|
||||
| None ->
|
||||
let state, zero =
|
||||
@@ -720,7 +637,7 @@ module internal UnaryMetadataIlOp =
|
||||
ImmutableArray.Empty // field can't have its own generics
|
||||
state
|
||||
|
||||
let state = IlMachineState.setStatic declaringTypeHandle field.Name zero state
|
||||
let state = IlMachineState.setStatic field.DeclaringType field.Name zero state
|
||||
state, zero
|
||||
|
||||
let state = state |> IlMachineState.pushToEvalStack staticField thread
|
||||
@@ -755,11 +672,7 @@ module internal UnaryMetadataIlOp =
|
||||
IlMachineState.pushToEvalStack currentValue thread state
|
||||
| ManagedPointerSource.Null -> failwith "TODO: raise NullReferenceException"
|
||||
| EvalStackValue.ObjectRef managedHeapAddress -> failwith $"todo: {managedHeapAddress}"
|
||||
| EvalStackValue.UserDefinedValueType fields ->
|
||||
let result =
|
||||
fields |> List.pick (fun (k, v) -> if k = field.Name then Some v else None)
|
||||
|
||||
IlMachineState.pushToEvalStack' result thread state
|
||||
| EvalStackValue.UserDefinedValueType _ as udvt -> IlMachineState.pushToEvalStack' udvt thread state
|
||||
|
||||
state
|
||||
|> IlMachineState.advanceProgramCounter thread
|
||||
@@ -781,7 +694,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
state, field
|
||||
| MetadataToken.MemberReference mr ->
|
||||
let state, _, field, _ =
|
||||
let state, _, field =
|
||||
IlMachineState.resolveMember loggerFactory baseClassTypes thread activeAssy mr state
|
||||
|
||||
match field with
|
||||
@@ -803,15 +716,17 @@ module internal UnaryMetadataIlOp =
|
||||
field.Signature
|
||||
)
|
||||
|
||||
let state, declaringTypeHandle, typeGenerics =
|
||||
IlMachineState.concretizeFieldForExecution loggerFactory baseClassTypes thread field state
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes declaringTypeHandle thread state with
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes field.DeclaringType thread state with
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
| NothingToDo state ->
|
||||
|
||||
let typeGenerics =
|
||||
match field.DeclaringType.Generics with
|
||||
| [] -> None
|
||||
| l -> Some (ImmutableArray.CreateRange l)
|
||||
|
||||
let fieldValue, state =
|
||||
match IlMachineState.getStatic declaringTypeHandle field.Name state with
|
||||
match IlMachineState.getStatic field.DeclaringType field.Name state with
|
||||
| None ->
|
||||
let state, newVal =
|
||||
IlMachineState.cliTypeZeroOf
|
||||
@@ -823,7 +738,7 @@ module internal UnaryMetadataIlOp =
|
||||
ImmutableArray.Empty // field can't have its own generics
|
||||
state
|
||||
|
||||
newVal, IlMachineState.setStatic declaringTypeHandle field.Name newVal state
|
||||
newVal, IlMachineState.setStatic field.DeclaringType field.Name newVal state
|
||||
| Some v -> v, state
|
||||
|
||||
do
|
||||
@@ -862,13 +777,14 @@ module internal UnaryMetadataIlOp =
|
||||
let state, assy, elementType =
|
||||
match metadataToken with
|
||||
| MetadataToken.TypeDefinition defn ->
|
||||
state,
|
||||
assy,
|
||||
assy.TypeDefs.[defn]
|
||||
|> TypeInfo.mapGeneric (fun _ p -> TypeDefn.GenericTypeParameter p.SequenceNumber)
|
||||
let ty =
|
||||
assy.TypeDefs.[defn]
|
||||
|> TypeInfo.mapGeneric (fun _ i -> declaringTypeGenerics.[i.SequenceNumber])
|
||||
|
||||
state, assy, ty
|
||||
| MetadataToken.TypeSpecification spec ->
|
||||
let state, assy, ty =
|
||||
IlMachineState.resolveTypeFromSpecConcrete
|
||||
IlMachineState.resolveTypeFromSpec
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
spec
|
||||
@@ -902,7 +818,13 @@ module internal UnaryMetadataIlOp =
|
||||
_.Name
|
||||
(fun x y -> x.TypeDefs.[y])
|
||||
(fun x y -> x.TypeRefs.[y] |> failwithf "%+A")
|
||||
elementType
|
||||
(elementType
|
||||
|> TypeInfo.mapGeneric (fun i _ ->
|
||||
{
|
||||
Name = "<unknown>"
|
||||
SequenceNumber = i
|
||||
}
|
||||
))
|
||||
|
||||
let state, zeroOfType =
|
||||
IlMachineState.cliTypeZeroOf
|
||||
@@ -932,13 +854,14 @@ module internal UnaryMetadataIlOp =
|
||||
let state, assy, elementType =
|
||||
match metadataToken with
|
||||
| MetadataToken.TypeDefinition defn ->
|
||||
state,
|
||||
assy,
|
||||
assy.TypeDefs.[defn]
|
||||
|> TypeInfo.mapGeneric (fun _ p -> TypeDefn.GenericTypeParameter p.SequenceNumber)
|
||||
let ty =
|
||||
assy.TypeDefs.[defn]
|
||||
|> TypeInfo.mapGeneric (fun _ i -> declaringTypeGenerics.[i.SequenceNumber])
|
||||
|
||||
state, assy, ty
|
||||
| MetadataToken.TypeSpecification spec ->
|
||||
let state, assy, ty =
|
||||
IlMachineState.resolveTypeFromSpecConcrete
|
||||
IlMachineState.resolveTypeFromSpec
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
spec
|
||||
@@ -974,7 +897,7 @@ module internal UnaryMetadataIlOp =
|
||||
else
|
||||
failwith "TODO: raise an out of bounds"
|
||||
|
||||
IlMachineState.pushToEvalStack toPush thread state
|
||||
failwith $"TODO: Ldelem {index} {arr} resulted in {toPush}"
|
||||
|> IlMachineState.advanceProgramCounter thread
|
||||
|> Tuple.withRight WhatWeDid.Executed
|
||||
| Initobj -> failwith "TODO: Initobj unimplemented"
|
||||
@@ -992,8 +915,10 @@ module internal UnaryMetadataIlOp =
|
||||
|> FieldInfo.mapTypeGenerics (fun _ _ -> failwith "generics not allowed on FieldDefinition")
|
||||
| t -> failwith $"Unexpectedly asked to load a non-field: {t}"
|
||||
|
||||
let state, declaringTypeHandle, typeGenerics =
|
||||
IlMachineState.concretizeFieldForExecution loggerFactory baseClassTypes thread field state
|
||||
let declaringTypeHandle =
|
||||
match AllConcreteTypes.lookup' field.DeclaringType state.ConcreteTypes with
|
||||
| None -> failwith "unexpectedly haven't concretised type when loading its field"
|
||||
| Some t -> t
|
||||
|
||||
match IlMachineState.loadClass loggerFactory baseClassTypes declaringTypeHandle thread state with
|
||||
| FirstLoadThis state -> state, WhatWeDid.SuspendedForClassInit
|
||||
@@ -1006,6 +931,8 @@ module internal UnaryMetadataIlOp =
|
||||
|> IlMachineState.advanceProgramCounter thread
|
||||
|> Tuple.withRight WhatWeDid.Executed
|
||||
| None ->
|
||||
let typeGenerics = field.DeclaringType.Generics |> ImmutableArray.CreateRange
|
||||
|
||||
// Field is not yet initialised
|
||||
let state, zero =
|
||||
IlMachineState.cliTypeZeroOf
|
||||
@@ -1027,37 +954,11 @@ module internal UnaryMetadataIlOp =
|
||||
| Ldftn ->
|
||||
let logger = loggerFactory.CreateLogger "Ldftn"
|
||||
|
||||
let (method : MethodInfo<TypeDefn, WoofWare.PawPrint.GenericParameter, TypeDefn>), methodGenerics =
|
||||
let method =
|
||||
match metadataToken with
|
||||
| MetadataToken.MethodDef handle ->
|
||||
let method =
|
||||
activeAssy.Methods.[handle]
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|
||||
method, None
|
||||
| MetadataToken.MethodSpecification h ->
|
||||
let spec = activeAssy.MethodSpecs.[h]
|
||||
|
||||
match spec.Method with
|
||||
| MetadataToken.MethodDef token ->
|
||||
let method =
|
||||
activeAssy.Methods.[token]
|
||||
|> MethodInfo.mapTypeGenerics (fun i _ -> TypeDefn.GenericTypeParameter i)
|
||||
|
||||
method, Some spec.Signature
|
||||
| k -> failwith $"Unrecognised MethodSpecification kind: %O{k}"
|
||||
| MetadataToken.MethodDef handle -> activeAssy.Methods.[handle]
|
||||
| t -> failwith $"Unexpectedly asked to Ldftn a non-method: {t}"
|
||||
|
||||
let state, concretizedMethod, _declaringTypeHandle =
|
||||
IlMachineState.concretizeMethodForExecution
|
||||
loggerFactory
|
||||
baseClassTypes
|
||||
thread
|
||||
method
|
||||
methodGenerics
|
||||
None
|
||||
state
|
||||
|
||||
logger.LogDebug (
|
||||
"Pushed pointer to function {LdFtnAssembly}.{LdFtnType}.{LdFtnMethodName}",
|
||||
method.DeclaringType.Assembly.Name,
|
||||
@@ -1067,7 +968,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
state
|
||||
|> IlMachineState.pushToEvalStack'
|
||||
(EvalStackValue.NativeInt (NativeIntSource.FunctionPointer concretizedMethod))
|
||||
(EvalStackValue.NativeInt (NativeIntSource.FunctionPointer method))
|
||||
thread
|
||||
|> IlMachineState.advanceProgramCounter thread
|
||||
|> Tuple.withRight WhatWeDid.Executed
|
||||
@@ -1100,7 +1001,6 @@ module internal UnaryMetadataIlOp =
|
||||
let currentMethod = state.ThreadState.[thread].MethodState
|
||||
|
||||
let methodGenerics = currentMethod.Generics
|
||||
|
||||
let typeGenerics = currentMethod.ExecutingMethod.DeclaringType.Generics
|
||||
|
||||
if not (methodGenerics.IsEmpty && typeGenerics.IsEmpty) then
|
||||
@@ -1113,10 +1013,7 @@ module internal UnaryMetadataIlOp =
|
||||
|
||||
let (_, alloc), state = IlMachineState.getOrAllocateType baseClassTypes handle state
|
||||
|
||||
IlMachineState.pushToEvalStack
|
||||
(CliType.ValueType [ "m_type", CliType.ObjectRef (Some alloc) ])
|
||||
thread
|
||||
state
|
||||
IlMachineState.pushToEvalStack (CliType.ValueType [ CliType.ObjectRef (Some alloc) ]) thread state
|
||||
| _ -> failwith $"Unexpected metadata token %O{metadataToken} in LdToken"
|
||||
|
||||
state
|
||||
|
||||
@@ -52,7 +52,11 @@ module internal UnaryStringTokenIlOp =
|
||||
]
|
||||
|
||||
let addr, state =
|
||||
IlMachineState.allocateManagedObject baseClassTypes.String fields state
|
||||
IlMachineState.allocateManagedObject
|
||||
(baseClassTypes.String
|
||||
|> TypeInfo.mapGeneric (fun _ _ -> failwith "string is not generic"))
|
||||
fields
|
||||
state
|
||||
|
||||
addr,
|
||||
{ state with
|
||||
|
||||
Reference in New Issue
Block a user