private INamedTypeDefinition GenerateTypeA(IUnitNamespace rootNamespace) { var nt = Host.NameTable; var typeA = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("A"), InternFactory = Host.InternFactory, IsClass = true }; var typeParameter = new GenericTypeParameter { Name = nt.GetNameFor("T"), InternFactory = Host.InternFactory, DefiningType = typeA, }; typeA.GenericParameters.Add(typeParameter); var baseGetMethod = new MethodDefinition { Name = nt.GetNameFor("Get"), IsCil = true, IsVirtual = true, Visibility = TypeMemberVisibility.Assembly, Type = typeParameter, ContainingTypeDefinition = typeA, InternFactory = Host.InternFactory, IsNewSlot = true }; typeA.Methods.Add(baseGetMethod); var il = new ILGenerator(Host); var localVar = new LocalDefinition { Type = typeParameter, Name = nt.GetNameFor("local1"), }; // tricky moment, ILGeneratorMethodBody fills internal collection of local vars only in constructor. // lines below should not be swapped il.AddVariableToCurrentScope(localVar); var body = new ILGeneratorMethodBody(il, true, 1) { MethodDefinition = baseGetMethod }; baseGetMethod.Body = body; il.Emit(OperationCode.Ldloca, localVar); il.Emit(OperationCode.Initobj, typeParameter); il.Emit(OperationCode.Ldloc_0); il.Emit(OperationCode.Ret); return(typeA); }
private INamedTypeDefinition GenerateTypeA(IUnitNamespace rootNamespace) { var nt = Host.NameTable; var typeA = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("A"), InternFactory = Host.InternFactory, IsClass = true }; var typeParameter = new GenericTypeParameter { Name = nt.GetNameFor("T"), InternFactory = Host.InternFactory, DefiningType = typeA, }; typeA.GenericParameters.Add(typeParameter); var baseGetMethod = new MethodDefinition { Name = nt.GetNameFor("Get"), IsCil = true, IsVirtual = true, Visibility = TypeMemberVisibility.Assembly, Type = typeParameter, ContainingTypeDefinition = typeA, InternFactory = Host.InternFactory, IsNewSlot = true }; typeA.Methods.Add(baseGetMethod); var il = new ILGenerator(Host); var localVar = new LocalDefinition { Type = typeParameter, Name = nt.GetNameFor("local1"), }; // tricky moment, ILGeneratorMethodBody fills internal collection of local vars only in constructor. // lines below should not be swapped il.AddVariableToCurrentScope(localVar); var body = new ILGeneratorMethodBody(il, true, 1) {MethodDefinition = baseGetMethod}; baseGetMethod.Body = body; il.Emit(OperationCode.Ldloca, localVar); il.Emit(OperationCode.Initobj, typeParameter); il.Emit(OperationCode.Ldloc_0); il.Emit(OperationCode.Ret); return typeA; }
/// <summary> /// Creates either a generic method parameter or a generic type parameter /// and adds it to the type symbol cache. /// </summary> /// <param name="typeSymbol"></param> /// <returns></returns> private GenericParameter CreateTypeDefinition(ITypeParameterSymbol typeSymbol) { Contract.Requires(typeSymbol != null); Contract.Ensures(Contract.Result <GenericParameter>() != null); GenericParameter cciType; var containingSymbol = typeSymbol.ContainingSymbol; if (containingSymbol is IMethodSymbol) { cciType = new GenericMethodParameter() { DefiningMethod = (IMethodDefinition)this.Map((IMethodSymbol)containingSymbol), Name = this.host.NameTable.GetNameFor(typeSymbol.Name), }; } else { // assume it is a class parameter? cciType = new GenericTypeParameter() { DefiningType = (ITypeDefinition)this.Map((ITypeSymbol)containingSymbol), Name = this.host.NameTable.GetNameFor(typeSymbol.Name), }; } var constraints = new List <ITypeReference>(); foreach (var c in typeSymbol.ConstraintTypes) { var c2 = this.Map(c); constraints.Add(c2); } cciType.Constraints = constraints; this.typeSymbolCache.Add(typeSymbol, cciType); return(cciType); }
public void AddGenericParamInPlace(NamespaceTypeDefinition namespaceTypeDefinition) { var oneMoreGP = new List <IGenericTypeParameter>(); var gp1 = new GenericTypeParameter() { InternFactory = this.host.InternFactory, PlatformType = this.host.PlatformType, Name = this.host.NameTable.GetNameFor("_SX_"), DefiningType = namespaceTypeDefinition, Index = 0 }; oneMoreGP.Add(gp1); if (namespaceTypeDefinition.GenericParameters != null) { foreach (GenericTypeParameter gp in namespaceTypeDefinition.GenericParameters) { gp.Index++; oneMoreGP.Add(gp); } } namespaceTypeDefinition.GenericParameters = oneMoreGP; }
public (Method, IOrType <TypeReference, IError>, IOrType <TypeReference, IError>) CreateGenericMethod(IStaticScope parent, Func <IStaticScope, IOrType <TypeReference, IError> > inputTypeBuilder, Func <IStaticScope, IOrType <TypeReference, IError> > outputTypeBuilder, string inputName, IConvertTo <Method, IOrType <WeakMethodDefinition, WeakImplementationDefinition, WeakEntryPointDefinition, WeakGenericMethodDefinition> > converter, IReadOnlyList <TypeAndConverter> placeholders) { var(method, inputType, outputType) = CreateMethod(parent, inputTypeBuilder, outputTypeBuilder, inputName, converter); var i = 0; foreach (var placeholder in placeholders) { var placeholderType = new GenericTypeParameter(this, $"generic-parameter-{placeholder.key}", i++, Prototypist.Toolbox.OrType.Make <MethodType, Type, Method, InferredType>(method)); HasGenericType(Prototypist.Toolbox.OrType.Make <MethodType, Type, Method>(method), placeholder.key, placeholderType); } // why doesn't this have genericOverlays ({4BFD0274-B70F-4BD8-B290-63B69FF74FE7}) // the overlays are t1 and t2 of the base method "method [t1,t2]" // they are never references anywhere so we don't care to overlay them // we build the right MethodType // at {2E20DFFB-7BD2-4351-9CAF-10A63491ABCF} // this isn't great // it would be a little work to build the genericOverlays // genericOverlays take a looked up type not a key return(method, inputType, outputType); }
public override IMember CreateInstance(IArgumentSet args) => GenericTypeParameter.FromTypeVar(args, args.Eval?.Module ?? DeclaringModule);
private NestedTypeDefinition CreateClosureClass(bool makeGeneric) { CustomAttribute compilerGeneratedAttribute = new CustomAttribute(); compilerGeneratedAttribute.Constructor = this.CompilerGeneratedCtor; NestedTypeDefinition result = new NestedTypeDefinition(); string signature = MemberHelper.GetMethodSignature(this.method, NameFormattingOptions.Signature | NameFormattingOptions.ReturnType | NameFormattingOptions.TypeParameters); //result.Name = this.host.NameTable.GetNameFor("closureclass"); result.Name = this.host.NameTable.GetNameFor(signature + " closure " + this.counter); this.counter++; result.Attributes = new List <ICustomAttribute>(1) { compilerGeneratedAttribute }; result.BaseClasses = new List <ITypeReference>(1) { this.host.PlatformType.SystemObject }; result.ContainingTypeDefinition = this.generatedclosureClass != null ? this.generatedclosureClass : method.ContainingTypeDefinition; result.Fields = new List <IFieldDefinition>(); if (makeGeneric) { result.GenericParameters = new List <IGenericTypeParameter>(); } result.Methods = new List <IMethodDefinition>(); result.InternFactory = this.host.InternFactory; result.IsBeforeFieldInit = true; result.IsClass = true; result.IsSealed = true; result.Layout = LayoutKind.Auto; result.StringFormat = StringFormatKind.Ansi; result.Visibility = TypeMemberVisibility.Private; //BoundField/*?*/ capturedThis; //var thisTypeReference = TypeDefinition.SelfInstance(this.method.ContainingTypeDefinition, this.host.InternFactory); //if (this.closureLocals.Count == 0 && this.FieldForCapturedLocalOrParameter.TryGetValue(thisTypeReference.InternedKey, out capturedThis)) { // result.Fields.Add(capturedThis.Field); // capturedThis.Field.ContainingTypeDefinition = result; // capturedThis.Field.Type = this.Visit(capturedThis.Field.Type); //} if (makeGeneric) { List <IGenericMethodParameter> genericMethodParameters = new List <IGenericMethodParameter>(); ushort count = 0; if (this.method.IsGeneric) { foreach (var genericMethodParameter in this.method.GenericParameters) { genericMethodParameters.Add(genericMethodParameter); GenericTypeParameter newTypeParam = new GenericTypeParameter() { Name = this.host.NameTable.GetNameFor(genericMethodParameter.Name.Value + "_"), Index = (count++), InternFactory = this.host.InternFactory, PlatformType = this.host.PlatformType, }; this.genericTypeParameterMapping[genericMethodParameter.InternedKey] = newTypeParam; newTypeParam.DefiningType = result; result.GenericParameters.Add(newTypeParam); } } this.copyTypeToClosure = new CopyTypeFromIteratorToClosure(this.host, genericTypeParameterMapping); if (this.method.IsGeneric) { // Duplicate Constraints foreach (var genericMethodParameter in genericMethodParameters) { GenericTypeParameter correspondingTypeParameter = (GenericTypeParameter)this.genericTypeParameterMapping[genericMethodParameter.InternedKey]; if (genericMethodParameter.Constraints != null) { correspondingTypeParameter.Constraints = new List <ITypeReference>(); foreach (ITypeReference t in genericMethodParameter.Constraints) { correspondingTypeParameter.Constraints.Add(copyTypeToClosure.Visit(t)); } } } } } this.generatedclosureClass = result; classList.Add(result); return(result); }
/// <summary> /// Create the iterator closure class and add it to the private helper types list. /// </summary> private IteratorClosureInformation CreateIteratorClosure(BlockStatement blockStatement) { IteratorClosureInformation result = new IteratorClosureInformation(this.host); CustomAttribute compilerGeneratedAttribute = new CustomAttribute(); compilerGeneratedAttribute.Constructor = this.CompilerGeneratedCtor; // Create the closure class with CompilerGeneratedAttribute, the list of generic type parameters isomorphic to // those of the iterator method. NestedTypeDefinition iteratorClosureType = new NestedTypeDefinition() { ExplicitImplementationOverrides = new List<IMethodImplementation>(), Fields = new List<IFieldDefinition>(), GenericParameters = new List<IGenericTypeParameter>(), Interfaces = new List<ITypeReference>(), Methods = new List<IMethodDefinition>(), NestedTypes = new List<INestedTypeDefinition>(), }; this.privateHelperTypes.Add(iteratorClosureType); result.ClosureDefinition = iteratorClosureType; List<IGenericMethodParameter> genericMethodParameters = new List<IGenericMethodParameter>(); ushort count = 0; foreach (var genericMethodParameter in method.GenericParameters) { genericMethodParameters.Add(genericMethodParameter); GenericTypeParameter newTypeParam = new GenericTypeParameter() { Name = this.host.NameTable.GetNameFor(genericMethodParameter.Name.Value + "_"), InternFactory = this.host.InternFactory, PlatformType = this.host.PlatformType, Index = (count++), }; this.genericTypeParameterMapping[genericMethodParameter.InternedKey] = newTypeParam; newTypeParam.DefiningType = iteratorClosureType; iteratorClosureType.GenericParameters.Add(newTypeParam); } this.copyTypeToClosure = new CopyTypeFromIteratorToClosure(this.host, this.genericTypeParameterMapping); // Duplicate Constraints foreach (var genericMethodParameter in genericMethodParameters) { GenericTypeParameter correspondingTypeParameter = (GenericTypeParameter)this.genericTypeParameterMapping[genericMethodParameter.InternedKey]; if (genericMethodParameter.Constraints != null) { correspondingTypeParameter.Constraints = new List<ITypeReference>(); foreach (ITypeReference t in genericMethodParameter.Constraints) { correspondingTypeParameter.Constraints.Add(copyTypeToClosure.Visit(t)); } } } // elementTypes contains only one element, the argument type of the return type (the T in IEnumerable<T>) of the iterator method, or simply System.Object if the // iterator is not generic. IEnumerable<ITypeReference> elementTypes = GetClosureEnumeratorTypeArguments(method.Type); // elementType of the IEnumerable. ITypeReference elementType = null; foreach (ITypeReference t in elementTypes) { elementType = t; break; } result.ElementType = this.copyTypeToClosure.Visit(elementType); // Set up the iterator closure class. // TODO: name generation to follow the convention of csc. iteratorClosureType.Name = this.host.NameTable.GetNameFor("<" + this.method.Name.Value + ">" + "ic__" + this.privateHelperTypes.Count); iteratorClosureType.Attributes = new List<ICustomAttribute>(1) { compilerGeneratedAttribute }; iteratorClosureType.BaseClasses = new List<ITypeReference>(1) { this.host.PlatformType.SystemObject }; iteratorClosureType.ContainingTypeDefinition = this.method.ContainingTypeDefinition; iteratorClosureType.ExplicitImplementationOverrides = new List<IMethodImplementation>(7); iteratorClosureType.InternFactory = this.host.InternFactory; iteratorClosureType.IsBeforeFieldInit = true; iteratorClosureType.IsClass = true; iteratorClosureType.IsSealed = true; iteratorClosureType.Layout = LayoutKind.Auto; iteratorClosureType.StringFormat = StringFormatKind.Ansi; iteratorClosureType.Visibility = TypeMemberVisibility.Private; /* Interfaces. */ result.InitializeInterfaces(result.ElementType, this.isEnumerable); /* Fields, Methods, and Properties. */ CreateIteratorClosureFields(result); CreateIteratorClosureConstructor(result); CreateIteratorClosureMethods(result, blockStatement); CreateIteratorClosureProperties(result); return result; }
/// <summary> /// Creates a new nested type definition with a default constructor and no other members and adds it to this.closureClasses. /// If this.method is generic, then the closure class is generic as well, with the same /// number of type parameters (constrained in the same way) as the generic method. /// Initializes this.currentClosure, this.currentClosureInstance and this.currentClosureSelfInstance. /// </summary> private void CreateClosureClass() { if (this.closureClasses == null) this.closureClasses = new List<ITypeDefinition>(); NestedTypeDefinition closure = new NestedTypeDefinition(); var containingType = this.method.ContainingTypeDefinition; closure.Name = this.host.NameTable.GetNameFor("<"+this.method.Name+">c__DisplayClass"+closure.GetHashCode()); closure.Attributes = new List<ICustomAttribute>(1) { this.compilerGenerated }; closure.BaseClasses = new List<ITypeReference>(1) { this.host.PlatformType.SystemObject }; closure.ContainingTypeDefinition = containingType; closure.Fields = new List<IFieldDefinition>(); closure.InternFactory = this.host.InternFactory; closure.IsBeforeFieldInit = true; closure.IsClass = true; closure.IsSealed = true; closure.Layout = LayoutKind.Auto; closure.Methods = new List<IMethodDefinition>(); closure.StringFormat = StringFormatKind.Ansi; closure.Visibility = TypeMemberVisibility.Private; this.closureClasses.Add(closure); this.currentClosureClass = closure; //generics if (this.method.IsGeneric) { Dictionary<ushort, IGenericParameterReference> genericMethodParameterMap = new Dictionary<ushort, IGenericParameterReference>(); this.genericMethodParameterMap = genericMethodParameterMap; bool foundConstraints = false; var genericTypeParameters = new List<IGenericTypeParameter>(this.method.GenericParameterCount); closure.GenericParameters = genericTypeParameters; foreach (var genericMethodParameter in this.method.GenericParameters) { var copyOfGenericMethodParameter = this.copier.Copy(genericMethodParameter); //so that we have mutable constraints to rewrite var genericTypeParameter = new GenericTypeParameter(); genericTypeParameter.Copy(copyOfGenericMethodParameter, this.host.InternFactory); genericTypeParameter.DefiningType = closure; if (genericTypeParameter.Constraints != null && genericTypeParameter.Constraints.Count > 0) foundConstraints = true; genericTypeParameters.Add(genericTypeParameter); genericMethodParameterMap.Add(copyOfGenericMethodParameter.Index, genericTypeParameter); } if (foundConstraints) { //Fix up any self references that might lurk inside constraints. closure.GenericParameters = new GenericParameterRewriter(this.host, genericMethodParameterMap).Rewrite(genericTypeParameters); } var instanceType = closure.InstanceType; var genericArguments = IteratorHelper.GetConversionEnumerable<IGenericMethodParameter, ITypeReference>(this.method.GenericParameters); this.currentClosureInstance = new Immutable.GenericTypeInstanceReference(instanceType.GenericType, genericArguments, this.host.InternFactory); this.currentClosureSelfInstance = instanceType; } else { //if any of the containing types are generic, we need an instance or a specialized nested type. this.currentClosureInstance = NestedTypeDefinition.SelfInstance(closure, this.host.InternFactory); this.currentClosureSelfInstance = this.currentClosureInstance; } //default constructor var block = new BlockStatement(); block.Statements.Add( new ExpressionStatement() { Expression = new MethodCall() { ThisArgument = new ThisReference() { Type = this.currentClosureSelfInstance }, MethodToCall = this.objectCtor, Type = this.host.PlatformType.SystemVoid } } ); var constructorBody = new SourceMethodBody(this.host, this.sourceLocationProvider) { LocalsAreZeroed = true, IsNormalized = true, Block = block }; var defaultConstructor = new MethodDefinition() { Body = constructorBody, ContainingTypeDefinition = closure, CallingConvention = CallingConvention.HasThis, InternFactory = this.host.InternFactory, IsCil = true, IsHiddenBySignature = true, IsRuntimeSpecial = true, IsSpecialName = true, Name = this.host.NameTable.Ctor, Type = this.host.PlatformType.SystemVoid, Visibility = TypeMemberVisibility.Public, }; constructorBody.MethodDefinition = defaultConstructor; closure.Methods.Add(defaultConstructor); }
protected override Assembly Generate() { var nt = Host.NameTable; var mscorlib = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity); var assembly = new Assembly { Name = nt.GetNameFor(AssemblyName), ModuleName = nt.GetNameFor(DllName), Kind = ModuleKind.DynamicallyLinkedLibrary, TargetRuntimeVersion = mscorlib.TargetRuntimeVersion, MetadataFormatMajorVersion = 2 }; assembly.AssemblyReferences.Add(mscorlib); var rootNamespace = new RootUnitNamespace(); assembly.UnitNamespaceRoot = rootNamespace; rootNamespace.Unit = assembly; // define module var module = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("<Module>"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(module); // define X<T> var xType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("X"), InternFactory = Host.InternFactory, IsClass = true }; var typeParameter = new GenericTypeParameter { Name = nt.GetNameFor("T"), InternFactory = Host.InternFactory, IsClass = true, DefiningType = xType }; xType.GenericParameters.Add(typeParameter); assembly.AllTypes.Add(xType); var aType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("A"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(aType); var bType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("B"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(bType); aType.BaseClasses.Add(new GenericTypeInstanceReference { GenericType = xType, GenericArguments = { bType }, InternFactory = Host.InternFactory }); bType.BaseClasses.Add(new GenericTypeInstanceReference { GenericType = xType, GenericArguments = { aType }, InternFactory = Host.InternFactory }); return assembly; }
/** * Call back method that must be called when the given <code> * GenericTypeParameter</code> will become the next <i>traverse * candidate</i>. * * @param pGenericTypeParameter The <code>GenericTypeParameter</code> object * that will become the next <i>traverse * candidate</i>. */ public void performAction( GenericTypeParameter pGenericTypeParameter) { // Nothing to do. }
public void HasGenericType(IOrType <MethodType, Type, Method> parent, NameKey key, GenericTypeParameter type) { parent.Switch(x => x.Generics.Add(key, type), x => x.Generics.Add(key, type), x => x.Generics.Add(key, type)); }
public void AssertIs(GenericTypeParameter assignedFrom, GenericTypeParameter assignedTo) { problem.assignments.Add(( Prototypist.Toolbox.OrType.Make <ILookUpType, IOrType <MethodType, Type, Object, OrType, InferredType, GenericTypeParameter, Method, IError> >(Prototypist.Toolbox.OrType.Make <MethodType, Type, Object, OrType, InferredType, GenericTypeParameter, Method, IError>(assignedFrom)), Prototypist.Toolbox.OrType.Make <ILookUpType, IOrType <MethodType, Type, Object, OrType, InferredType, GenericTypeParameter, IError> >(Prototypist.Toolbox.OrType.Make <MethodType, Type, Object, OrType, InferredType, GenericTypeParameter, IError>(assignedTo)))); }
private NestedTypeDefinition CreateClosureClass(bool makeGeneric) { CustomAttribute compilerGeneratedAttribute = new CustomAttribute(); compilerGeneratedAttribute.Constructor = this.CompilerGeneratedCtor; NestedTypeDefinition result = new NestedTypeDefinition(); string signature = MemberHelper.GetMethodSignature(this.method, NameFormattingOptions.Signature | NameFormattingOptions.ReturnType | NameFormattingOptions.TypeParameters); //result.Name = this.host.NameTable.GetNameFor("closureclass"); result.Name = this.host.NameTable.GetNameFor(signature + " closure " + this.counter); this.counter++; result.Attributes = new List<ICustomAttribute>(1) { compilerGeneratedAttribute }; result.BaseClasses = new List<ITypeReference>(1) { this.host.PlatformType.SystemObject }; result.ContainingTypeDefinition = this.generatedclosureClass != null ? this.generatedclosureClass : method.ContainingTypeDefinition; result.Fields = new List<IFieldDefinition>(); if (makeGeneric) result.GenericParameters = new List<IGenericTypeParameter>(); result.Methods = new List<IMethodDefinition>(); result.InternFactory = this.host.InternFactory; result.IsBeforeFieldInit = true; result.IsClass = true; result.IsSealed = true; result.Layout = LayoutKind.Auto; result.StringFormat = StringFormatKind.Ansi; result.Visibility = TypeMemberVisibility.Private; //BoundField/*?*/ capturedThis; //var thisTypeReference = TypeDefinition.SelfInstance(this.method.ContainingTypeDefinition, this.host.InternFactory); //if (this.closureLocals.Count == 0 && this.FieldForCapturedLocalOrParameter.TryGetValue(thisTypeReference.InternedKey, out capturedThis)) { // result.Fields.Add(capturedThis.Field); // capturedThis.Field.ContainingTypeDefinition = result; // capturedThis.Field.Type = this.Visit(capturedThis.Field.Type); //} if (makeGeneric) { List<IGenericMethodParameter> genericMethodParameters = new List<IGenericMethodParameter>(); ushort count = 0; if (this.method.IsGeneric) { foreach (var genericMethodParameter in this.method.GenericParameters) { genericMethodParameters.Add(genericMethodParameter); GenericTypeParameter newTypeParam = new GenericTypeParameter() { Name = this.host.NameTable.GetNameFor(genericMethodParameter.Name.Value + "_"), Index = (count++), InternFactory = this.host.InternFactory, PlatformType = this.host.PlatformType, }; this.genericTypeParameterMapping[genericMethodParameter.InternedKey] = newTypeParam; newTypeParam.DefiningType = result; result.GenericParameters.Add(newTypeParam); } } this.copyTypeToClosure = new CopyTypeFromIteratorToClosure(this.host, genericTypeParameterMapping); if (this.method.IsGeneric) { // Duplicate Constraints foreach (var genericMethodParameter in genericMethodParameters) { GenericTypeParameter correspondingTypeParameter = (GenericTypeParameter)this.genericTypeParameterMapping[genericMethodParameter.InternedKey]; if (genericMethodParameter.Constraints != null) { correspondingTypeParameter.Constraints = new List<ITypeReference>(); foreach (ITypeReference t in genericMethodParameter.Constraints) { correspondingTypeParameter.Constraints.Add(copyTypeToClosure.Visit(t)); } } } } } this.generatedclosureClass = result; classList.Add(result); return result; }
/// <summary> /// Creates either a generic method parameter or a generic type parameter /// and adds it to the type symbol cache. /// </summary> /// <param name="typeSymbol"></param> /// <returns></returns> private GenericParameter CreateTypeDefinition(R.ITypeParameterSymbol typeSymbol) { Contract.Requires(typeSymbol != null); Contract.Ensures(Contract.Result<GenericParameter>() != null); GenericParameter cciType; var containingSymbol = typeSymbol.ContainingSymbol; if (containingSymbol is R.IMethodSymbol) { cciType = new GenericMethodParameter() { DefiningMethod = (IMethodDefinition)this.Map((R.IMethodSymbol)containingSymbol), Name = this.host.NameTable.GetNameFor(typeSymbol.Name), }; } else { // assume it is a class parameter? cciType = new GenericTypeParameter() { DefiningType = (ITypeDefinition)this.Map((R.ITypeSymbol)containingSymbol), Name = this.host.NameTable.GetNameFor(typeSymbol.Name), }; } var constraints = new List<ITypeReference>(); foreach (var c in typeSymbol.ConstraintTypes) { var c2 = this.Map(c); constraints.Add(c2); } cciType.Constraints = constraints; this.typeSymbolCache.Add(typeSymbol, cciType); return cciType; }
/// <inheritdoc/> public IEnumerable <ImplementedFunction> CreateOverloads(Function function) { if (!function.Parameters.Any(p => p.Type.IsIntPtr())) { yield break; } var baseParameters = function.Parameters; var newIntPtrParameters = new List <Parameter>(baseParameters); var newGenericArray1DParameters = new List <Parameter>(baseParameters); var newGenericArray2DParameters = new List <Parameter>(baseParameters); var newGenericArray3DParameters = new List <Parameter>(baseParameters); var newGenericTypeParameters = new List <GenericTypeParameter>(); for (var i = 0; i < baseParameters.Count; ++i) { var parameter = baseParameters[i]; if (!parameter.Type.IsIntPtr() || parameter.Type.IsOut) { continue; } var genericTypeParameterName = baseParameters.Count(p => p.Type.IsIntPtr()) > 1 ? $"T{newGenericTypeParameters.Count + 1}" : "T"; var genericTypeParameter = new GenericTypeParameter( genericTypeParameterName, new[] { "unmanaged" }); newGenericTypeParameters.Add(genericTypeParameter); var newIntPtrParameterType = new TypeSignatureBuilder(parameter.Type) .WithIndirectionLevel(1) .WithName("void") .Build(); // TODO: Simplify and generalize this var newGenericArray1DParameterType = new TypeSignatureBuilder(parameter.Type) .WithIndirectionLevel(0) .WithArrayDimensions(1) .WithName(genericTypeParameterName) .Build(); var newGenericArray2DParameterType = new TypeSignatureBuilder(parameter.Type) .WithIndirectionLevel(0) .WithArrayDimensions(2) .WithName(genericTypeParameterName) .Build(); var newGenericArray3DParameterType = new TypeSignatureBuilder(parameter.Type) .WithIndirectionLevel(0) .WithArrayDimensions(3) .WithName(genericTypeParameterName) .Build(); newIntPtrParameters[i] = new ParameterSignatureBuilder(parameter) .WithType(newIntPtrParameterType) .Build(); newGenericArray1DParameters[i] = new ParameterSignatureBuilder(parameter) .WithType(newGenericArray1DParameterType) .Build(); newGenericArray2DParameters[i] = new ParameterSignatureBuilder(parameter) .WithType(newGenericArray2DParameterType) .Build(); newGenericArray3DParameters[i] = new ParameterSignatureBuilder(parameter) .WithType(newGenericArray3DParameterType) .Build(); } yield return(ToPointer ( new FunctionSignatureBuilder(function) .WithParameters(newIntPtrParameters) .Build(), function )); yield return(Fixed ( new FunctionSignatureBuilder(function) .WithParameters(newGenericArray1DParameters) .WithGenericTypeParameters(newGenericTypeParameters) .Build() )); yield return(Fixed ( new FunctionSignatureBuilder(function) .WithParameters(newGenericArray2DParameters) .WithGenericTypeParameters(newGenericTypeParameters) .Build() )); yield return(Fixed ( new FunctionSignatureBuilder(function) .WithParameters(newGenericArray3DParameters) .WithGenericTypeParameters(newGenericTypeParameters) .Build() )); }
protected override Assembly Generate() { var nt = Host.NameTable; var mscorlib = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity); var assembly = new Assembly { Name = nt.GetNameFor(AssemblyName), ModuleName = nt.GetNameFor(DllName), Kind = ModuleKind.DynamicallyLinkedLibrary, TargetRuntimeVersion = mscorlib.TargetRuntimeVersion, MetadataFormatMajorVersion = 2 }; assembly.AssemblyReferences.Add(mscorlib); var rootNamespace = new RootUnitNamespace(); assembly.UnitNamespaceRoot = rootNamespace; rootNamespace.Unit = assembly; // define module var module = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("<Module>"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(module); // define X<T> var xType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("X"), InternFactory = Host.InternFactory, IsClass = true }; var typeParameter = new GenericTypeParameter { Name = nt.GetNameFor("T"), InternFactory = Host.InternFactory, IsClass = true, DefiningType = xType }; xType.GenericParameters.Add(typeParameter); assembly.AllTypes.Add(xType); var aType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("A"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(aType); var bType = new NamespaceTypeDefinition { ContainingUnitNamespace = rootNamespace, Name = nt.GetNameFor("B"), InternFactory = Host.InternFactory, IsClass = true }; assembly.AllTypes.Add(bType); aType.BaseClasses.Add(new GenericTypeInstanceReference { GenericType = xType, GenericArguments = { bType }, InternFactory = Host.InternFactory }); bType.BaseClasses.Add(new GenericTypeInstanceReference { GenericType = xType, GenericArguments = { aType }, InternFactory = Host.InternFactory }); return(assembly); }
/** * Call back method that must be called as soon as the given <code> * GenericTypeParameter</code> object has been traversed. * * @param pGenericTypeParameter The <code>GenericTypeParameter</code> * object that has just been traversed. */ public void actionPerformed( GenericTypeParameter pGenericTypeParameter) { // Nothing to do. }
private TypeScriptType GetTypeScriptType(Type type) { TypeScriptType tst; if (TypeHelper.Is(type, typeof(string))) { tst = new StringType(); } else if (TypeHelper.Is(type, typeof(bool))) { tst = new BooleanType(); } else if (TypeHelper.Is(type, typeof(int), typeof(decimal), typeof(double), typeof(long), typeof(float), typeof(short), typeof(byte), typeof(uint), typeof(ushort), typeof(ulong), typeof(sbyte) )) { tst = new NumberType(); } else if (TypeHelper.Is(type, typeof(DateTime))) { tst = new DateTimeType(); } else if (TypeHelper.Is(type, typeof(TimeSpan))) { tst = new TimeSpanType(); } else if (type.IsGenericParameter) { tst = new GenericTypeParameter(); } else if (TypeHelper.IsDictionary(type)) { tst = new DictionaryType(); } else if (TypeHelper.IsEnumerable(type)) { tst = new ArrayType(); } else if (TypeHelper.IsEnum(type)) { tst = new EnumType(); } else { var processType = _options.TypeFilter(type); if (processType) { if (type.IsInterface) { tst = new InterfaceType(type); } else { tst = new CustomType(type); } } else { tst = new AnyType(); } } if (TypeHelper.IsNullableValueType(type)) { ((ValueType)tst).IsNullable = true; type = Nullable.GetUnderlyingType(type); } tst.ClrType = type; return tst; }
private void SpecializeMembers() { var location = new Location(this, default); // TypeVar var fn = PythonFunctionType.Specialize("TypeVar", this, GetMemberDocumentation("TypeVar")); var o = new PythonFunctionOverload(fn.Name, location); // When called, create generic parameter type. For documentation // use original TypeVar declaration so it appear as a tooltip. o.SetReturnValueProvider((interpreter, overload, args) => GenericTypeParameter.FromTypeVar(args, interpreter)); fn.AddOverload(o); _members["TypeVar"] = fn; // NewType fn = PythonFunctionType.Specialize("NewType", this, GetMemberDocumentation("NewType")); o = new PythonFunctionOverload(fn.Name, location); // When called, create generic parameter type. For documentation // use original TypeVar declaration so it appear as a tooltip. o.SetReturnValueProvider((interpreter, overload, args) => CreateTypeAlias(args.Values <IMember>())); fn.AddOverload(o); _members["NewType"] = fn; // Type fn = PythonFunctionType.Specialize("Type", this, GetMemberDocumentation("Type")); o = new PythonFunctionOverload(fn.Name, location); // When called, create generic parameter type. For documentation // use original TypeVar declaration so it appear as a tooltip. o.SetReturnValueProvider((interpreter, overload, args) => { var a = args.Values <IMember>(); return(a.Count == 1 ? a[0] : Interpreter.UnknownType); }); fn.AddOverload(o); _members["Type"] = fn; _members["Iterator"] = new GenericType("Iterator", CreateIteratorType, this); _members["Iterable"] = new GenericType("Iterable", typeArgs => CreateListType("Iterable", BuiltinTypeId.List, typeArgs, false), this); _members["Sequence"] = new GenericType("Sequence", typeArgs => CreateListType("Sequence", BuiltinTypeId.List, typeArgs, false), this); _members["MutableSequence"] = new GenericType("MutableSequence", typeArgs => CreateListType("MutableSequence", BuiltinTypeId.List, typeArgs, true), this); _members["List"] = new GenericType("List", typeArgs => CreateListType("List", BuiltinTypeId.List, typeArgs, true), this); _members["MappingView"] = new GenericType("MappingView", typeArgs => CreateDictionary("MappingView", typeArgs, false), this); _members["KeysView"] = new GenericType("KeysView", CreateKeysViewType, this); _members["ValuesView"] = new GenericType("ValuesView", CreateValuesViewType, this); _members["ItemsView"] = new GenericType("ItemsView", CreateItemsViewType, this); _members["Set"] = new GenericType("Set", typeArgs => CreateListType("Set", BuiltinTypeId.Set, typeArgs, true), this); _members["MutableSet"] = new GenericType("MutableSet", typeArgs => CreateListType("MutableSet", BuiltinTypeId.Set, typeArgs, true), this); _members["FrozenSet"] = new GenericType("FrozenSet", typeArgs => CreateListType("FrozenSet", BuiltinTypeId.Set, typeArgs, false), this); _members["Tuple"] = new GenericType("Tuple", CreateTupleType, this); _members["Mapping"] = new GenericType("Mapping", typeArgs => CreateDictionary("Mapping", typeArgs, false), this); _members["MutableMapping"] = new GenericType("MutableMapping", typeArgs => CreateDictionary("MutableMapping", typeArgs, true), this); _members["Dict"] = new GenericType("Dict", typeArgs => CreateDictionary("Dict", typeArgs, true), this); _members["OrderedDict"] = new GenericType("OrderedDict", typeArgs => CreateDictionary("OrderedDict", typeArgs, true), this); _members["DefaultDict"] = new GenericType("DefaultDict", typeArgs => CreateDictionary("DefaultDict", typeArgs, true), this); _members["Union"] = new GenericType("Union", CreateUnion, this); _members["Counter"] = Specialized.Function("Counter", this, GetMemberDocumentation("Counter"), new PythonInstance(Interpreter.GetBuiltinType(BuiltinTypeId.Int))); _members["SupportsInt"] = Interpreter.GetBuiltinType(BuiltinTypeId.Int); _members["SupportsFloat"] = Interpreter.GetBuiltinType(BuiltinTypeId.Float); _members["SupportsComplex"] = Interpreter.GetBuiltinType(BuiltinTypeId.Complex); _members["SupportsBytes"] = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); _members["ByteString"] = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); fn = PythonFunctionType.Specialize("NamedTuple", this, GetMemberDocumentation("NamedTuple")); o = new PythonFunctionOverload(fn.Name, location); o.SetReturnValueProvider((interpreter, overload, args) => CreateNamedTuple(args.Values <IMember>())); fn.AddOverload(o); _members["NamedTuple"] = fn; _members["Any"] = new AnyType(this); // AnyStr var str = Interpreter.GetBuiltinType(BuiltinTypeId.Str); var bytes = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); var unicode = Interpreter.GetBuiltinType(BuiltinTypeId.Unicode); var anyStrName = new PythonConstant("AnyStr", str); var anyStrArgs = Interpreter.LanguageVersion.Is3x() ? new IMember[] { anyStrName, str, bytes } : new IMember[] { anyStrName, str, unicode }; _members["AnyStr"] = GenericTypeParameter.FromTypeVar(new ArgumentSet(anyStrArgs), this); _members["Optional"] = new GenericType("Optional", CreateOptional, this); _members["Type"] = new GenericType("Type", CreateType, this); _members["Generic"] = new GenericType("Generic", CreateGenericClassParameter, this); }
public string GetTypeName(GenericTypeParameter tst) { return tst.ClrType.Name; }
private void SpecializeMembers() { var location = new Location(this); // TypeVar var fn = PythonFunctionType.Specialize("TypeVar", this, GetMemberDocumentation("TypeVar")); var o = new PythonFunctionOverload(fn, location); o.SetParameters(new List <ParameterInfo> { new ParameterInfo("name", Interpreter.GetBuiltinType(BuiltinTypeId.Str), ParameterKind.Normal, null), new ParameterInfo("constraints", Interpreter.GetBuiltinType(BuiltinTypeId.Str), ParameterKind.List, null), new ParameterInfo("bound", Interpreter.GetBuiltinType(BuiltinTypeId.Str), ParameterKind.KeywordOnly, new PythonConstant(null, Interpreter.GetBuiltinType(BuiltinTypeId.NoneType))), new ParameterInfo("covariant", Interpreter.GetBuiltinType(BuiltinTypeId.Bool), ParameterKind.KeywordOnly, new PythonConstant(false, Interpreter.GetBuiltinType(BuiltinTypeId.Bool))), new ParameterInfo("contravariant", Interpreter.GetBuiltinType(BuiltinTypeId.Bool), ParameterKind.KeywordOnly, new PythonConstant(false, Interpreter.GetBuiltinType(BuiltinTypeId.Bool))) }); // When called, create generic parameter type. For documentation // use original TypeVar declaration so it appear as a tooltip. o.SetReturnValueProvider((declaringModule, overload, args, indexSpan) => GenericTypeParameter.FromTypeVar(args, declaringModule, indexSpan)); fn.AddOverload(o); _members["TypeVar"] = fn; // NewType _members["NewType"] = SpecializeNewType(location); // Type fn = PythonFunctionType.Specialize("Type", this, GetMemberDocumentation("Type")); o = new PythonFunctionOverload(fn, location); // When called, create generic parameter type. For documentation // use original TypeVar declaration so it appear as a tooltip. o.SetReturnValueProvider((declaringModule, overload, args, indexSpan) => { var a = args.Values <IMember>(); return(a.Count == 1 ? a[0] : Interpreter.UnknownType); }); fn.AddOverload(o); _members["Type"] = fn; _members["Iterator"] = new SpecializedGenericType("Iterator", CreateIteratorType, this); _members["Iterable"] = new SpecializedGenericType("Iterable", typeArgs => CreateListType("Iterable", BuiltinTypeId.List, typeArgs, false), this); _members["Sequence"] = new SpecializedGenericType("Sequence", typeArgs => CreateListType("Sequence", BuiltinTypeId.List, typeArgs, false), this); _members["MutableSequence"] = new SpecializedGenericType("MutableSequence", typeArgs => CreateListType("MutableSequence", BuiltinTypeId.List, typeArgs, true), this); _members["List"] = new SpecializedGenericType("List", typeArgs => CreateListType("List", BuiltinTypeId.List, typeArgs, true), this); _members["MappingView"] = new SpecializedGenericType("MappingView", typeArgs => CreateDictionary("MappingView", typeArgs, false), this); _members["KeysView"] = new SpecializedGenericType("KeysView", CreateKeysViewType, this); _members["ValuesView"] = new SpecializedGenericType("ValuesView", CreateValuesViewType, this); _members["ItemsView"] = new SpecializedGenericType("ItemsView", CreateItemsViewType, this); _members["AbstractSet"] = new SpecializedGenericType("AbstractSet", typeArgs => CreateListType("AbstractSet", BuiltinTypeId.Set, typeArgs, true), this); _members["Set"] = new SpecializedGenericType("Set", typeArgs => CreateListType("Set", BuiltinTypeId.Set, typeArgs, true), this); _members["MutableSet"] = new SpecializedGenericType("MutableSet", typeArgs => CreateListType("MutableSet", BuiltinTypeId.Set, typeArgs, true), this); _members["FrozenSet"] = new SpecializedGenericType("FrozenSet", typeArgs => CreateListType("FrozenSet", BuiltinTypeId.Set, typeArgs, false), this); _members["Tuple"] = new SpecializedGenericType("Tuple", CreateTupleType, this); _members["Mapping"] = new SpecializedGenericType("Mapping", typeArgs => CreateDictionary("Mapping", typeArgs, false), this); _members["MutableMapping"] = new SpecializedGenericType("MutableMapping", typeArgs => CreateDictionary("MutableMapping", typeArgs, true), this); _members["Dict"] = new SpecializedGenericType("Dict", typeArgs => CreateDictionary("Dict", typeArgs, true), this); _members["OrderedDict"] = new SpecializedGenericType("OrderedDict", typeArgs => CreateDictionary("OrderedDict", typeArgs, true), this); _members["DefaultDict"] = new SpecializedGenericType("DefaultDict", typeArgs => CreateDictionary("DefaultDict", typeArgs, true), this); _members["Union"] = new SpecializedGenericType("Union", CreateUnion, this); _members["Counter"] = Specialized.Function("Counter", this, GetMemberDocumentation("Counter"), Interpreter.GetBuiltinType(BuiltinTypeId.Int)).CreateInstance(ArgumentSet.WithoutContext); // TODO: make these classes that support __float__, etc per spec. //_members["SupportsInt"] = Interpreter.GetBuiltinType(BuiltinTypeId.Int); //_members["SupportsFloat"] = Interpreter.GetBuiltinType(BuiltinTypeId.Float); //_members["SupportsComplex"] = Interpreter.GetBuiltinType(BuiltinTypeId.Complex); //_members["SupportsBytes"] = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); _members["ByteString"] = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); fn = PythonFunctionType.Specialize("NamedTuple", this, GetMemberDocumentation("NamedTuple")); o = new PythonFunctionOverload(fn, location); o.SetReturnValueProvider((declaringModule, overload, args, indexSpan) => CreateNamedTuple(args.Values <IMember>(), declaringModule, indexSpan)); fn.AddOverload(o); _members["NamedTuple"] = fn; _members["Any"] = new AnyType(this); _members["AnyStr"] = CreateAnyStr(); _members["Optional"] = new SpecializedGenericType("Optional", CreateOptional, this); _members["Type"] = new SpecializedGenericType("Type", CreateType, this); _members["Generic"] = new SpecializedGenericType("Generic", CreateGenericClassBase, this); }
public static (IGenericTypeParameter, IGenericTypeParameterBuilder) Create() { var res = new GenericTypeParameter(); return(res, res); }