public static ArrayType GetStringType(ResolutionContext ctxt, LiteralSubformat fmt = LiteralSubformat.Utf8)
		{
			ArrayType _t = null;

			if (ctxt != null && ctxt.ScopedBlock != null)
			{
				var obj = ctxt.ParseCache.LookupModuleName(ctxt.ScopedBlock.NodeRoot as DModule, "object").FirstOrDefault();

				if (obj != null)
				{
					string strType = fmt == LiteralSubformat.Utf32 ? "dstring" :
						fmt == LiteralSubformat.Utf16 ? "wstring" :
						"string";

					var strNode = obj[strType];

					if (strNode != null)
						foreach (var n in strNode) {
							_t = TypeDeclarationResolver.HandleNodeMatch(n, ctxt) as ArrayType;
							if (_t != null)
								break;
						}
				}
			}

			if (_t == null)
			{
				var ch = fmt == LiteralSubformat.Utf32 ? DTokens.Dchar :
					fmt == LiteralSubformat.Utf16 ? DTokens.Wchar : DTokens.Char;

				_t = new ArrayType(new PrimitiveType(ch, DTokens.Immutable));
			}

			return _t;
		}
Esempio n. 2
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            TypeMap typeMap;
            if (TypeMapDatabase.FindTypeMap(array, out typeMap) && typeMap.IsIgnored)
            {
                Ignore();
                return false;
            }

            if (array.SizeType != ArrayType.ArraySize.Constant)
                return true;

            var arrayElemType = array.Type.Desugar();

            Class @class;
            if (arrayElemType.TryGetClass(out @class) && @class.IsRefType)
                return true;

            PrimitiveType primitive;
            if ((arrayElemType.IsPrimitiveType(out primitive) && primitive != PrimitiveType.LongDouble) ||
                arrayElemType.IsPointerToPrimitiveType())
                return true;

            Ignore();
            return false;
        }
Esempio n. 3
0
    public void Execute()
    {
        var assemblyContainsAttribute = ModuleDefinition.Assembly.CustomAttributes.ContainsAttribute("LogMinimalMessageAttribute");
        var moduleContainsAttribute = ModuleDefinition.CustomAttributes.ContainsAttribute("LogMinimalMessageAttribute");
        if (assemblyContainsAttribute || moduleContainsAttribute)
        {
            LogMinimalMessage = true;
        }
        FindReference();
        Init();
        var stringType = ModuleDefinition.TypeSystem.String.Resolve();
        ConcatMethod = ModuleDefinition.Import(stringType.FindMethod("Concat", "String", "String"));
        FormatMethod = ModuleDefinition.Import(stringType.FindMethod("Format", "String", "Object[]"));
        ObjectArray = new ArrayType(ModuleDefinition.TypeSystem.Object);

        FindExceptionType();
        foreach (var type in ModuleDefinition
            .GetTypes()
            .Where(x => (x.BaseType != null) && !x.IsEnum && !x.IsInterface))
        {
            ProcessType(type);
        }

        //TODO: ensure attributes dont exist on interfaces
        RemoveReference();
    }
        public static ArrayType GetStringType(ResolverContextStack ctxt, LiteralSubformat fmt = LiteralSubformat.Utf8)
        {
            ArrayType _t = null;

            if (ctxt != null)
            {
                var obj = ctxt.ParseCache.LookupModuleName("object").First();

                string strType = fmt == LiteralSubformat.Utf32 ? "dstring" :
                    fmt == LiteralSubformat.Utf16 ? "wstring" :
                    "string";

                var strNode = obj[strType];

                if(strNode!=null && strNode.Count != 0)
                    _t = DResolver.StripAliasSymbol(TypeDeclarationResolver.HandleNodeMatch(strNode[0], ctxt)) as ArrayType;
            }

            if (_t == null)
            {
                var ch = fmt == LiteralSubformat.Utf32 ? DTokens.Dchar :
                    fmt == LiteralSubformat.Utf16 ? DTokens.Wchar : DTokens.Char;

                _t = new ArrayType(new PrimitiveType(ch, DTokens.Immutable),
                    new ArrayDecl
                    {
                        ValueType = new MemberFunctionAttributeDecl(DTokens.Immutable)
                        {
                            InnerType = new DTokenDeclaration(ch)
                        }
                    });
            }

            return _t;
        }
Esempio n. 5
0
        public void TyfoArray()
        {
            ArrayType arr = new ArrayType(PrimitiveType.Int32, 10);
            tyreffo.WriteDeclaration(arr, "a");

            string sExp = "int32 a[10]";
            Assert.AreEqual(sExp, sw.ToString());
        }
Esempio n. 6
0
 public static void Tabularize(ArrayType a, string tasName)
 {
     ((ICDType)a.m_type).Tabularize(tasName);
     if (a.m_type.Constructed)
     {
         TypeAssigment newTas = ((ICDModule)a.m_module).CreateNewTypeAssigment(tasName, a.m_type, new List<string>());
         a.m_type = ReferenceType.CreateByName(newTas);
     }
 }
Esempio n. 7
0
 public void VisitArray(ArrayType at)
 {
     var addrEnd = rdr.Address + cbSize;
     for (int i = 0; at.IsUnbounded || i < at.Length; ++i)
     {
         if (!rdr.IsValid || addrEnd <= rdr.Address)
             return;
         at.ElementType.Accept(this);
     }
 }
Esempio n. 8
0
        /// <summary>
        /// Инициализирует новый экземпляр класса <see cref="ScalarArray"/> с указанием его типа
        /// </summary>
        /// <param name="arrayType">Значение перечисления <see cref="ArrayType"/>, определяющая тип скалярного массива</param>
        private ScalarArray(ArrayType arrayType)
            : base(true)
        {
            if (arrayType < ArrayType.Scalar || arrayType > ArrayType.Double)
            {
                throw new ArgumentOutOfRangeException("arrayType");
            }

            Type = arrayType;
        }
Esempio n. 9
0
 public void VisitArray(ArrayType at)
 {
     if (at.Length == 0)
     {
         scanner.Warn(Address, "User-specified arrays must have a non-zero size.");
         return;
     }
     for (int i = 0; i < at.Length; ++i)
     {
         at.ElementType.Accept(this);
     }
 }
Esempio n. 10
0
        public static ArrayType MakeArrayType(this TypeReference self, int rank)
        {
            if (rank == 0)
                throw new ArgumentOutOfRangeException ("rank");

            var array = new ArrayType (self);

            for (int i = 1; i < rank; i++)
                array.Dimensions.Add (new ArrayDimension ());

            return array;
        }
Esempio n. 11
0
 public override void CheckSemantic(Scope scope, List<Error> errors)
 {
     //es añadido al scope en el CheckSemantic del TypeDeclarationSecuence si no esta redefinido incorrectamente
     TigerType elementsType = scope.GetType(ElementsTypeName);
     if (elementsType == null)
     {
         errors.Add(new Error(GetChild(1), "El tipo '{0}' no está definido en el ámbito actual", ElementsTypeName));
         HasError = true;
         RelatedType = new ArrayType(UndefinedType.UndefinedInstance, ElementsTypeName);
     }
     else
         RelatedType = new ArrayType(elementsType, ElementsTypeName);
 }
        public void StructureContainingArray()
        {
            ArrayType a = new ArrayType(PrimitiveType.Int32, 4);

            StructureType s = new StructureType(null, 0) { Fields = { { 8, a } } };

            TypeVariable tv = store.CreateTypeVariable(factory);
            tv.Class.DataType = s;
            Assert.AreEqual(1, store.UsedEquivalenceClasses.Count);

            DataType dt = tv.Class.DataType.Accept(nct);
            Assert.AreEqual(1, store.UsedEquivalenceClasses.Count);
            Assert.AreEqual("(struct (8 (arr int32 4) a0008))", store.UsedEquivalenceClasses[0].DataType.ToString()); 
        }
Esempio n. 13
0
 public override DataType VisitArray(ArrayType at)
 {
     if (insideComplexType)
     {
         var nctr = new NestedComplexTypeExtractor(factory, store);
         at.Accept(nctr);
         return at;
     }
     else
     {
         insideComplexType = true;
         return base.VisitArray(at);
     }
 }
 public void CEB_BuildByteArrayFetch()
 {
     var i = new Identifier("i", PrimitiveType.Word32, null);
     DataType arrayOfBytes = new ArrayType(PrimitiveType.Byte, 0);
     StructureType str = Struct(
         Fld(0x01000, arrayOfBytes));
     CreateTv(globals, Ptr32(str), Ptr32(PrimitiveType.Byte));
     CreateTv(i, PrimitiveType.Int32, PrimitiveType.Word32);
     var ceb = new ComplexExpressionBuilder(
         PrimitiveType.Byte,
         globals.TypeVariable.DataType,
         globals.TypeVariable.OriginalDataType,
         null,
         globals, i, 0x1000);
     ceb.Dereferenced = true;
     Assert.AreEqual("globals->a1000[i]", ceb.BuildComplex().ToString());
 }
        public void ArrayOfStructures()
        {
            StructureType s = new StructureType();
            s.Fields.Add(0, PrimitiveType.Word32);
            s.Fields.Add(4, PrimitiveType.Real64);

            ArrayType a = new ArrayType(s, 0);

            TypeVariable tv = store.CreateTypeVariable(factory);
            tv.Class.DataType = a;
            Assert.AreEqual(1, store.UsedEquivalenceClasses.Count);

            tv.Class.DataType.Accept(nct);

            Assert.AreEqual(2, store.UsedEquivalenceClasses.Count);
            Assert.AreEqual("(arr Eq_2)", store.UsedEquivalenceClasses[0].DataType.ToString());
            Assert.AreEqual("(struct (0 word32 dw0000) (4 real64 r0004))", store.UsedEquivalenceClasses[1].DataType.ToString());
        }
Esempio n. 16
0
    public void Execute()
    {
		FindReference();
		Init();
        var stringType = ModuleDefinition.TypeSystem.String.Resolve();
        ConcatMethod = ModuleDefinition.Import(stringType.FindMethod("Concat", "String", "String"));
        FormatMethod = ModuleDefinition.Import(stringType.FindMethod("Format", "String", "Object[]"));
        ObjectArray = new ArrayType(ModuleDefinition.TypeSystem.Object);

        FindExceptionType();
        foreach (var type in ModuleDefinition
            .GetTypes()
            .Where(x => (x.BaseType != null) && !x.IsEnum && !x.IsInterface))
        {
            ProcessType(type);
        }

        //TODO: ensure attributes don't exist on interfaces
        RemoveReference();
    }
Esempio n. 17
0
        public static void PrintCInitialize(ArrayType pThis, PEREffectiveConstraint cns,
            Asn1Value defauleVal, StreamWriterLevel c, string typeName, string varName, int lev, int arrayDepth)
        {
            long min = pThis.minItems(cns);
            long max = pThis.maxItems(cns);
            string i = "i" + arrayDepth.ToString();
            string prefix = "";
            bool topLevel = !varName.Contains("->");
            if (topLevel)
                prefix = varName + "->";
            else
            {
                prefix = varName + ".";
            }

            ArrayValue arVal = defauleVal as ArrayValue;
            if (arVal == null)
            {
                c.P(lev);
                c.WriteLine("{0}nCount = 0;", prefix);

                c.P(lev); c.WriteLine("for({0}=0;{0}<{1};{0}++)", i, pThis.maxItems(cns));
                c.P(lev); c.WriteLine("{");
                ((ISCCType)pThis.m_type).PrintCInitialize(pThis.m_type.PEREffectiveConstraint, pThis.m_type.GetOneValidValue(), c,
                    typeName + "_arr", prefix + "arr[" + i + "]", lev + 1, arrayDepth + 1);
                c.P(lev); c.WriteLine("}");
            }
            else
            {
                c.P(lev);
                c.WriteLine("{0}nCount = {1};", prefix, arVal.m_children.Count);
                for (int k = 0; k < arVal.m_children.Count; k++)
                {
                    c.P(lev); c.WriteLine("{");
                    ((ISCCType)pThis.m_type).PrintCInitialize(pThis.m_type.PEREffectiveConstraint, arVal.m_children[k], c,
                        typeName + "_arr", prefix + "arr[" + k.ToString() + "]", lev + 1, arrayDepth + 1);
                    c.P(lev); c.WriteLine("}");
                }
            }
        }
Esempio n. 18
0
 public void TestIsValue()
 {
     object[][] values = new object[][]
     {
        new object[] {new int[4], true, "int[4]" },
        new object[] {new bool[4], false , "bool[4]"},
        new object[] {new int[2,2] {{1, 2},{3,4}}, false, "int[2,2] {{1, 2},{3,4}}"},
        new object[] {new int[][] {new int[] {1,2},new int[] {3,4}}, false, "int[] {1,2},new int[] {3,4}}"},
        new object[] {new object[] {1,2}, true, "object[] {1,2}"},
        new object[] {new object[] {1,true}, false, "object[] {1,true}"},
        new object[] {new object[] {1,null}, true, "object[] {1,null}"},
        new object[] {new object[,] {{1,2},{3,4}}, false, "object[,] {{1,2},{3,4}}"},
     };
      ArrayType type = new ArrayType(1, SimpleType.Integer);
      for (int i = 0; i < values.Length; i++)
      {
     object value = values[i][0];
     bool result = (bool)values[i][1];
     string descr = (string) values[i][2];
     Assert.AreEqual(result, type.IsValue(value), descr);
      }
 }
Esempio n. 19
0
    public void LoadSystemTypes()
    {
        var mscorlib = AssemblyResolver.Resolve("mscorlib");
        var typeType = mscorlib.MainModule.Types.FirstOrDefault(x => x.Name == "Type");
        if (typeType == null)
        {
            var runtime = AssemblyResolver.Resolve("System.Runtime");
            typeType = runtime.MainModule.Types.First(x => x.Name == "Type");
        }
        var funcDefinition = typeType.Module.Types.First(x => x.Name == "Func`1");
        var genericInstanceType = new GenericInstanceType(funcDefinition);
        genericInstanceType.GenericArguments.Add(ModuleDefinition.TypeSystem.String);
        GenericFunc = ModuleDefinition.ImportReference(genericInstanceType);

        var methodReference = new MethodReference("Invoke", funcDefinition.FindMethod("Invoke").ReturnType, genericInstanceType) { HasThis = true };
        FuncInvokeMethod = ModuleDefinition.ImportReference(methodReference);

        GetTypeFromHandle = typeType.Methods
            .First(x => x.Name == "GetTypeFromHandle" &&
                        x.Parameters.Count == 1 &&
                        x.Parameters[0].ParameterType.Name == "RuntimeTypeHandle");
        GetTypeFromHandle = ModuleDefinition.ImportReference(GetTypeFromHandle);


        var stringType = ModuleDefinition.TypeSystem.String.Resolve();
        ConcatMethod = ModuleDefinition.ImportReference(stringType.FindMethod("Concat", "String", "String"));
        FormatMethod = ModuleDefinition.ImportReference(stringType.FindMethod("Format", "String", "Object[]"));
        ObjectArray = new ArrayType(ModuleDefinition.TypeSystem.Object);

        var exceptionType = mscorlib.MainModule.Types.FirstOrDefault(x => x.Name == "Exception");
        if (exceptionType == null)
        {
            var runtime = AssemblyResolver.Resolve("System.Runtime");
            exceptionType = runtime.MainModule.Types.First(x => x.Name == "Exception");
        }
        ExceptionType = ModuleDefinition.ImportReference(exceptionType);

    }
Esempio n. 20
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
                return false;

            switch (array.SizeType)
            {
                case ArrayType.ArraySize.Constant:
                    var supportBefore = Context.SupportBefore;
                    supportBefore.WriteLine("if ({0} != nullptr)", Context.ArgName);
                    supportBefore.WriteStartBraceIndent();
                    supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
                    supportBefore.WriteLineIndent("{0}[i] = {1}[i]{2};",
                        Context.ReturnVarName, Context.ArgName,
                        array.Type.IsPointerToPrimitiveType(PrimitiveType.Void) ? ".ToPointer()" : string.Empty);
                    supportBefore.WriteCloseBraceIndent();
                    break;
                default:
                    Context.Return.Write("null");
                    break;
            }
            return true;
        }
Esempio n. 21
0
    public void Execute()
    {
        var assemblyContainsAttribute = ModuleDefinition.Assembly.CustomAttributes.ContainsAttribute("Anotar.Catel.LogMinimalMessageAttribute");
        var moduleContainsAttribute = ModuleDefinition.CustomAttributes.ContainsAttribute("Anotar.Catel.LogMinimalMessageAttribute");
        if (assemblyContainsAttribute || moduleContainsAttribute)
        {
            LogMinimalMessage = true;
        }
        FindReference();
        Init();
        var stringType = ModuleDefinition.TypeSystem.String.Resolve();
        ConcatMethod = ModuleDefinition.Import(stringType.FindMethod("Concat", "String", "String"));
        FormatMethod = ModuleDefinition.Import(stringType.FindMethod("Format", "String", "Object[]"));
        ObjectArray = new ArrayType(ModuleDefinition.TypeSystem.Object);

        var mscorlib = AssemblyResolver.Resolve("mscorlib");
        var mscorlibTypes = mscorlib.MainModule.Types;
        var typeType = mscorlibTypes.First(x => x.Name == "Type");
        getTypeFromHandle = typeType.Methods
                                    .First(x => x.Name == "GetTypeFromHandle" &&
                                                x.Parameters.Count == 1 &&
                                                x.Parameters[0].ParameterType.Name == "RuntimeTypeHandle");
        getTypeFromHandle = ModuleDefinition.Import(getTypeFromHandle);


        var msCoreLibDefinition = AssemblyResolver.Resolve("mscorlib");
        ExceptionType = ModuleDefinition.Import(msCoreLibDefinition.MainModule.Types.First(x => x.Name == "Exception"));
        foreach (var type in ModuleDefinition
            .GetTypes()
            .Where(x => (x.BaseType != null) && !x.IsEnum && !x.IsInterface))
        {
            ProcessType(type);
        }

        RemoveReference();
    }
Esempio n. 22
0
 protected ArrayType(ArrayType.Internal* native, bool skipVTables = false)
     : base((CppSharp.Parser.AST.Type.Internal*) null)
 {
     __PointerAdjustment = 0;
     if (native == null)
         return;
     __Instance = new global::System.IntPtr(native);
 }
Esempio n. 23
0
 public static ArrayType __CreateInstance(ArrayType.Internal native, bool skipVTables = false)
 {
     return new ArrayType(native, skipVTables);
 }
 public override TypePrinterResult VisitArrayType(ArrayType array,
                                                  TypeQualifiers quals)
 {
     return(string.Format("{0}[]", array.Type.Visit(this)));
 }
Esempio n. 25
0
 public virtual TypePrinterResult VisitArrayType(ArrayType array,
                                                 TypeQualifiers quals)
 {
     throw new NotImplementedException();
 }
Esempio n. 26
0
 protected virtual void Visit(ArrayType arrayType, Context context)
 {
     VisitTypeReference(arrayType.ElementType, context.ElementType(arrayType));
 }
Esempio n. 27
0
 /// <summary>
 /// CoreCLR has no Array`1 type to hang the various generic interfaces off.
 /// Return nothing at compile time so the runtime figures it out.
 /// </summary>
 protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type)
 {
     return(BaseTypeRuntimeInterfacesAlgorithm.Instance);
 }
Esempio n. 28
0
        public override MethodIL EmitIL()
        {
            ILEmitter    emitter    = new ILEmitter();
            ILCodeStream codeStream = emitter.NewCodeStream();

            ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType();

            ILLocalVariable delegateArrayLocal   = emitter.NewLocal(invocationListArrayType);
            ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
            ILLocalVariable iteratorLocal        = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
            ILLocalVariable delegateToCallLocal  = emitter.NewLocal(SystemDelegateType);

            ILLocalVariable returnValueLocal = 0;

            if (!Signature.ReturnType.IsVoid)
            {
                returnValueLocal = emitter.NewLocal(Signature.ReturnType);
            }

            // Fill in delegateArrayLocal
            // Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject

            // ldarg.0 (this pointer)
            // ldfld Delegate.HelperObjectField
            // castclass Delegate[]
            // stloc delegateArrayLocal
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
            codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType));
            codeStream.EmitStLoc(delegateArrayLocal);

            // Fill in invocationCountLocal
            // int invocationCountLocal = this.m_extraFunctionPointerOrData
            // ldarg.0 (this pointer)
            // ldfld Delegate.m_extraFunctionPointerOrData
            // stloc invocationCountLocal
            codeStream.EmitLdArg(0);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
            codeStream.EmitStLoc(invocationCountLocal);

            // Fill in iteratorLocal
            // int iteratorLocal = 0;

            // ldc.0
            // stloc iteratorLocal
            codeStream.EmitLdc(0);
            codeStream.EmitStLoc(iteratorLocal);

            // Loop across every element of the array.
            ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel();

            codeStream.EmitLabel(startOfLoopLabel);

            // Implement as do/while loop. We only have this stub in play if we're in the multicast situation
            // Find the delegate to call
            // Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal];

            // ldloc delegateArrayLocal
            // ldloc iteratorLocal
            // ldelem System.Delegate
            // stloc delegateToCallLocal
            codeStream.EmitLdLoc(delegateArrayLocal);
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType));
            codeStream.EmitStLoc(delegateToCallLocal);

            // Call the delegate
            // returnValueLocal = delegateToCallLocal(...);

            // ldloc delegateToCallLocal
            // ldfld System.Delegate.m_firstParameter
            // ldarg 1, n
            // ldloc delegateToCallLocal
            // ldfld System.Delegate.m_functionPointer
            // calli returnValueType thiscall (all the params)
            // IF there is a return value
            // stloc returnValueLocal

            codeStream.EmitLdLoc(delegateToCallLocal);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField));

            for (int i = 0; i < Signature.Length; i++)
            {
                codeStream.EmitLdArg(i + 1);
            }

            codeStream.EmitLdLoc(delegateToCallLocal);
            codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField));

            CalliIntrinsic.EmitTransformedCalli(emitter, codeStream, Signature);
            //codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature));

            if (returnValueLocal != 0)
            {
                codeStream.EmitStLoc(returnValueLocal);
            }

            // Increment iteratorLocal
            // ++iteratorLocal;

            // ldloc iteratorLocal
            // ldc.i4.1
            // add
            // stloc iteratorLocal
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.EmitLdc(1);
            codeStream.Emit(ILOpcode.add);
            codeStream.EmitStLoc(iteratorLocal);

            // Check to see if the loop is done
            codeStream.EmitLdLoc(invocationCountLocal);
            codeStream.EmitLdLoc(iteratorLocal);
            codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel);

            // Return to caller. If the delegate has a return value, be certain to return that.
            // return returnValueLocal;

            // ldloc returnValueLocal
            // ret
            if (returnValueLocal != 0)
            {
                codeStream.EmitLdLoc(returnValueLocal);
            }

            codeStream.Emit(ILOpcode.ret);

            return(emitter.Link(this));
        }
Esempio n. 29
0
 public override void BeginArray(int size, ArrayType arrayType)
 {
     _stack.push(new ArrayWriter(size, arrayType));
 }
Esempio n. 30
0
        internal static TypeReference ResolveType(TypeReference original, Mono.Collections.Generic.Collection <GenericParameter> parameters, Mono.Collections.Generic.Collection <TypeReference> arguments)
        {
            TypeSpecification   spec        = original as TypeSpecification;
            ArrayType           array       = original as ArrayType;
            ByReferenceType     reference   = original as ByReferenceType;
            GenericInstanceType genericType = original as GenericInstanceType;

            if (parameters.Count != arguments.Count)
            {
                throw new System.ArgumentException("Parameters and Arguments must have the same number of elements.");
            }

            if (spec != null)
            {
                TypeReference resolved = ResolveType(spec.ElementType, parameters, arguments);

                if (genericType != null)
                {
                    GenericInstanceType result = new GenericInstanceType(genericType.ElementType);
                    bool found;
                    for (int i = 0; i < genericType.ElementType.GenericParameters.Count; i++)
                    {
                        found = false;
                        for (int k = 0; k < parameters.Count; k++)
                        {
                            if (genericType.ElementType.GenericParameters [i].Name == parameters [k].Name)
                            {
                                found = true;
                                result.GenericArguments.Add(arguments [k]);
                                break;
                            }
                        }
                        if (!found)
                        {
                            result.GenericArguments.Add(genericType.ElementType.GenericParameters [i]);
                        }
                    }
                    return(result);
                }

                if (resolved == spec.ElementType)
                {
                    return(spec);
                }

                if (array != null)
                {
                    return(new ArrayType(resolved, array.Dimensions.Count));
                }
                else if (reference != null)
                {
                    return(new ByReferenceType(resolved));
                }
                else
                {
                    throw new System.NotImplementedException();
                }
            }
            else
            {
                for (int i = 0; i < parameters.Count; i++)
                {
                    if (parameters [i] == original)
                    {
                        return(arguments [i]);
                    }
                }
                return(original);
            }
        }
Esempio n. 31
0
 // todo: fix all the VarEnum/int casting nonsense
 private static CppType Factory(CppType arrayItem, ArrayType array, TypeStyle style, bool optional, wsdlParser.qname xmlType)
 {
     return(new CppTypeArray((int)VarEnum.VT_ARRAY, arrayItem, array, style, optional, xmlType));
 }
Esempio n. 32
0
 public ManagedArrayType(ArrayType array, TypedefType typedef)
 {
     Decayed  = new QualifiedType(array);
     Original = new QualifiedType(typedef);
 }
Esempio n. 33
0
        static void AppendTypeName(StringBuilder b, IType type, bool explicitInterfaceImpl)
        {
            switch (type.Kind)
            {
            case TypeKind.Dynamic:
                b.Append(explicitInterfaceImpl ? "System#Object" : "System.Object");
                break;

            case TypeKind.TypeParameter:
                ITypeParameter tp = (ITypeParameter)type;
                if (explicitInterfaceImpl)
                {
                    b.Append(tp.Name);
                }
                else
                {
                    b.Append('`');
                    if (tp.OwnerType == SymbolKind.Method)
                    {
                        b.Append('`');
                    }
                    b.Append(tp.Index);
                }
                break;

            case TypeKind.Array:
                ArrayType array = (ArrayType)type;
                AppendTypeName(b, array.ElementType, explicitInterfaceImpl);
                b.Append('[');
                if (array.Dimensions > 1)
                {
                    for (int i = 0; i < array.Dimensions; i++)
                    {
                        if (i > 0)
                        {
                            b.Append(explicitInterfaceImpl ? '@' : ',');
                        }
                        if (!explicitInterfaceImpl)
                        {
                            b.Append("0:");
                        }
                    }
                }
                b.Append(']');
                break;

            case TypeKind.Pointer:
                AppendTypeName(b, ((PointerType)type).ElementType, explicitInterfaceImpl);
                b.Append('*');
                break;

            case TypeKind.ByReference:
                AppendTypeName(b, ((ByReferenceType)type).ElementType, explicitInterfaceImpl);
                b.Append('@');
                break;

            default:
                IType declType = type.DeclaringType;
                if (declType != null)
                {
                    AppendTypeName(b, declType, explicitInterfaceImpl);
                    b.Append(explicitInterfaceImpl ? '#' : '.');
                    b.Append(type.Name);
                    AppendTypeParameters(b, type, declType.TypeParameterCount, explicitInterfaceImpl);
                }
                else
                {
                    if (explicitInterfaceImpl)
                    {
                        b.Append(type.FullName.Replace('.', '#'));
                    }
                    else
                    {
                        b.Append(type.FullName);
                    }
                    AppendTypeParameters(b, type, 0, explicitInterfaceImpl);
                }
                break;
            }
        }
Esempio n. 34
0
 public ArrayTypeParameterDataProvider(int startOffset, CSharpCompletionTextEditorExtension ext, ArrayType arrayType) : base(ext, startOffset)
 {
     this.arrayType = arrayType;
 }
Esempio n. 35
0
 /// <summary>
 /// String constructor.
 /// Used for generating string results 'internally'.
 /// </summary>
 public ArrayValue(ArrayType stringTypeResult, string content) : base(stringTypeResult)
 {
     StringFormat = LiteralSubformat.Utf8;
     StringValue  = content;
 }
Esempio n. 36
0
 public ArrayValue(ArrayType resolvedArrayType, params ISymbolValue[] elements) : base(resolvedArrayType)
 {
     Elements = elements;
 }
Esempio n. 37
0
 public static CppType Create(int vt, string name, ArrayType array, TypeStyle style, bool optional, wsdlParser.qname xmlType)
 {
     return(Factory(vt, name, array, style, optional, xmlType));
 }
Esempio n. 38
0
        private static TypeSpecifier ParseType(ITypeSymbol type)
        {
            var tType       = type as ITypeParameterSymbol;
            var namedType   = type as INamedTypeSymbol;
            var arrayType   = type as IArrayTypeSymbol;
            var pointerType = type as IPointerTypeSymbol;
            var isGeneric   = namedType != null && namedType.IsGenericType;

            if (isGeneric)
            {
                var ret = new GenericType();

                var name_      = type.Name;
                var namespace_ = Utils.ToStr(type.ContainingNamespace);
                ret.OuterType = new SimpleType
                {
                    Namespace = namespace_,
                    TypeName  = name_,
                };

                ret.InnerType = namedType.TypeArguments.Select(_ => ParseType(_)).Where(_ => _ != null).ToList();

                if (ret.InnerType.Count() != namedType.TypeArguments.Count())
                {
                    throw new Exception();
                }

                return(ret);
            }
            else if (type.TypeKind == TypeKind.Array)
            {
                var ret        = new ArrayType();
                var name_      = arrayType.ElementType.Name;
                var namespace_ = Utils.ToStr(arrayType.ElementType.ContainingNamespace);
                ret.BaseType = new SimpleType
                {
                    Namespace = namespace_,
                    TypeName  = name_,
                };

                return(ret);
            }
            else if (type.TypeKind == TypeKind.Pointer)
            {
                // ポインタは配列にする。
                var ret        = new ArrayType();
                var name_      = pointerType.PointedAtType.Name;
                var namespace_ = Utils.ToStr(pointerType.PointedAtType.ContainingNamespace);
                ret.BaseType = new SimpleType
                {
                    Namespace = namespace_,
                    TypeName  = name_,
                };

                return(ret);
            }
            else if (type.TypeKind == TypeKind.TypeParameter)
            {
                var name_ = type.Name;
                var ret   = new GenericTypenameType
                {
                    Name = name_,
                };

                return(ret);
            }
            else
            {
                var name_      = type.Name;
                var namespace_ = Utils.ToStr(type.ContainingNamespace);
                var ret        = new SimpleType
                {
                    Namespace = namespace_,
                    TypeName  = name_,
                };

                switch (type.TypeKind)
                {
                case TypeKind.Class:
                    ret.TypeKind = SimpleTypeKind.Class;
                    break;

                case TypeKind.Enum:
                    ret.TypeKind = SimpleTypeKind.Enum;
                    break;

                case TypeKind.Error:
                    ret.TypeKind = SimpleTypeKind.Error;
                    break;

                case TypeKind.Interface:
                    ret.TypeKind = SimpleTypeKind.Interface;
                    break;

                case TypeKind.Struct:
                    ret.TypeKind = SimpleTypeKind.Struct;
                    break;

                case TypeKind.TypeParameter:
                    ret.TypeKind = SimpleTypeKind.TypeParameter;
                    // 基本的にGenericsの型なのでNamespaceは必要ない
                    ret.Namespace = string.Empty;
                    break;

                default:
                    ret.TypeKind = SimpleTypeKind.Other;
                    break;
                }

                return(ret);
            }
        }
Esempio n. 39
0
 public QueuedArrayType(ArrayType arrayType)
 {
     ArrayType = arrayType;
 }
Esempio n. 40
0
 public static ArrayType __CreateInstance(ArrayType.Internal native)
 {
     return new ArrayType(native);
 }
Esempio n. 41
0
        public bool ReplaceAll(DecompilerEventListener eventListener)
        {
            changed        = false;
            classesVisited = new HashSet <EquivalenceClass>();

            // Replace the DataType of all the equivalence classes
            foreach (TypeVariable tv in store.TypeVariables)
            {
                if (eventListener.IsCanceled())
                {
                    return(false);
                }
                EquivalenceClass eq = tv.Class;
                if (!classesVisited.Contains(eq))
                {
                    classesVisited.Add(eq);
                    var dt = Replace(eq.DataType);
                    eq.DataType = dt;
                }
            }

            // Replace the DataType of all the TypeVariables
            foreach (TypeVariable tv in store.TypeVariables)
            {
                if (eventListener.IsCanceled())
                {
                    return(false);
                }
                tv.DataType = Replace(tv.DataType);
            }

            foreach (EquivalenceClass eq in classesVisited)
            {
                if (eventListener.IsCanceled())
                {
                    return(false);
                }
                if (eq != program.Globals.TypeVariable.Class &&
                    (eq.DataType is PrimitiveType ||
                     eq.DataType is VoidType ||
                     eq.DataType is EquivalenceClass ||
                     eq.DataType is CodeType))
                {
                    eq.DataType = null;
                    changed     = true;
                    continue;
                }

                Pointer ptr = eq.DataType as Pointer;
                if (ptr != null)
                {
                    eq.DataType = ptr.Pointee;
                    changed     = true;
                    continue;
                }

                MemberPointer mp = eq.DataType as MemberPointer;
                if (mp != null)
                {
                    eq.DataType = mp.Pointee;
                    changed     = true;
                }

                ArrayType array = eq.DataType as ArrayType;
                if (array != null)
                {
                    eq.DataType = array.ElementType;
                    changed     = true;
                }
            }
            return(changed);
        }
Esempio n. 42
0
 private ArrayType(ArrayType.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Esempio n. 43
0
        QualifiedType VisitType(IKVM.Reflection.Type managedType)
        {
            var isString = managedType.HasElementType && IKVM.Reflection.Type.GetTypeCode(
                managedType.GetElementType()) == TypeCode.String;

            if (managedType.IsByRef && isString)
            {
                managedType = managedType.GetElementType();
            }

            // If true type is an array, a pointer, or is passed by reference.
            if (managedType.HasElementType)
            {
                var managedElementType = managedType.GetElementType();
                var elementType        = VisitType(managedElementType);

                if (managedType.IsByRef || managedType.IsPointer)
                {
                    var ptrType = new PointerType(elementType)
                    {
                        Modifier = (Options.GeneratorKind == GeneratorKind.CPlusPlus) ?
                                   PointerType.TypeModifier.LVReference :
                                   PointerType.TypeModifier.Pointer
                    };

                    return(new QualifiedType(ptrType));
                }
                else if (managedType.IsArray)
                {
                    if (Options.GeneratorKind == GeneratorKind.Java)
                    {
                        return(new QualifiedType(new UnsupportedType {
                            Description = managedType.FullName
                        }));
                    }

                    var array = new ArrayType
                    {
                        SizeType      = ArrayType.ArraySize.Variable,
                        QualifiedType = elementType
                    };

                    return(new QualifiedType(array));
                }

                throw new NotImplementedException();
            }

            if (managedType.IsEnum)
            {
                var @enum = Visit(managedType.GetTypeInfo());
                return(new QualifiedType(new TagType(@enum)));
            }

            CppSharp.AST.Type type       = null;
            TypeQualifiers    qualifiers = new TypeQualifiers();

            switch (IKVM.Reflection.Type.GetTypeCode(managedType))
            {
            case TypeCode.Empty:
                type = new BuiltinType(PrimitiveType.Null);
                break;

            case TypeCode.Object:
            case TypeCode.DateTime:
                if (managedType.FullName == "System.Void")
                {
                    type = new BuiltinType(PrimitiveType.Void);
                    break;
                }
                var currentUnit = GetTranslationUnit(CurrentAssembly);
                if (managedType.Assembly != ManagedAssemblies[currentUnit] ||
                    managedType.IsGenericType)
                {
                    type = new UnsupportedType {
                        Description = managedType.FullName
                    };
                    break;
                }
                var decl = Visit(managedType.GetTypeInfo());
                type = new TagType(decl);
                break;

            case TypeCode.DBNull:
                type = new UnsupportedType()
                {
                    Description = "DBNull"
                };
                break;

            case TypeCode.Boolean:
                type = new BuiltinType(PrimitiveType.Bool);
                break;

            case TypeCode.Char:
                type = new BuiltinType(PrimitiveType.Char);
                break;

            case TypeCode.SByte:
                type = new BuiltinType(PrimitiveType.SChar);
                break;

            case TypeCode.Byte:
                type = new BuiltinType(PrimitiveType.UChar);
                break;

            case TypeCode.Int16:
                type = new BuiltinType(PrimitiveType.Short);
                break;

            case TypeCode.UInt16:
                type = new BuiltinType(PrimitiveType.UShort);
                break;

            case TypeCode.Int32:
                type = new BuiltinType(PrimitiveType.Int);
                break;

            case TypeCode.UInt32:
                type = new BuiltinType(PrimitiveType.UInt);
                break;

            case TypeCode.Int64:
                type = new BuiltinType(PrimitiveType.Long);
                break;

            case TypeCode.UInt64:
                type = new BuiltinType(PrimitiveType.ULong);
                break;

            case TypeCode.Single:
                type = new BuiltinType(PrimitiveType.Float);
                break;

            case TypeCode.Double:
                type = new BuiltinType(PrimitiveType.Double);
                break;

            case TypeCode.String:
                type = new BuiltinType(PrimitiveType.String);
                break;

            case TypeCode.Decimal:
                type = new BuiltinType(PrimitiveType.Decimal);
                break;
            }

            return(new QualifiedType(type, qualifiers));
        }
Esempio n. 44
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
            {
                return(false);
            }

            switch (array.SizeType)
            {
            case ArrayType.ArraySize.Constant:
                if (Context.MarshalKind != MarshalKind.NativeField &&
                    Context.MarshalKind != MarshalKind.ReturnVariableArray)
                {
                    goto case ArrayType.ArraySize.Incomplete;
                }

                var    supportBefore = Context.Before;
                string value         = Generator.GeneratedIdentifier("value");
                var    arrayType     = array.Type.Desugar();
                supportBefore.WriteLine($"{arrayType}[] {value} = null;");
                supportBefore.WriteLine($"if ({Context.ReturnVarName} != null)");
                supportBefore.WriteOpenBraceAndIndent();
                supportBefore.WriteLine($"{value} = new {arrayType}[{array.Size}];");
                supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
                if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
                {
                    supportBefore.WriteLineIndent($@"{value}[i] = new global::System.IntPtr({
                            Context.ReturnVarName}[i]);");
                }
                else
                {
                    var   finalArrayType = arrayType.GetPointee() ?? arrayType;
                    Class @class;
                    if ((finalArrayType.TryGetClass(out @class)) && @class.IsRefType)
                    {
                        if (arrayType == finalArrayType)
                        {
                            supportBefore.WriteLineIndent(
                                "{0}[i] = {1}.{2}(*(({1}.{3}*)&({4}[i * sizeof({1}.{3})])));",
                                value, array.Type, Helpers.CreateInstanceIdentifier,
                                Helpers.InternalStruct, Context.ReturnVarName);
                        }
                        else
                        {
                            supportBefore.WriteLineIndent(
                                $@"{value}[i] = {finalArrayType}.{Helpers.CreateInstanceIdentifier}(({
                                        typePrinter.IntPtrType}) {Context.ReturnVarName}[i]);");
                        }
                    }
                    else
                    {
                        if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = {
                                    Context.ReturnVarName}[i] != 0;");
                        }
                        else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                                 Context.Context.Options.MarshalCharAsManagedChar)
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = global::System.Convert.ToChar({
                                    Context.ReturnVarName}[i]);");
                        }
                        else
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = {
                                    Context.ReturnVarName}[i];");
                        }
                    }
                }
                supportBefore.UnindentAndWriteCloseBrace();
                Context.Return.Write(value);
                break;

            case ArrayType.ArraySize.Incomplete:
                // const char* and const char[] are the same so we can use a string
                if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
                    array.QualifiedType.Qualifiers.IsConst)
                {
                    var pointer = new PointerType {
                        QualifiedPointee = array.QualifiedType
                    };
                    Context.ReturnType = new QualifiedType(pointer);
                    return(this.VisitPointerType(pointer, quals));
                }
                MarshalArray(array);
                break;

            case ArrayType.ArraySize.Variable:
                Context.Return.Write(Context.ReturnVarName);
                break;
            }

            return(true);
        }
Esempio n. 45
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
            {
                return(false);
            }

            var arrayType = array.Type.Desugar();

            switch (array.SizeType)
            {
            case ArrayType.ArraySize.Constant:
                if (string.IsNullOrEmpty(Context.ReturnVarName))
                {
                    goto case ArrayType.ArraySize.Incomplete;
                }
                else
                {
                    var supportBefore = Context.Before;
                    supportBefore.WriteLine("if ({0} != null)", Context.ArgName);
                    supportBefore.WriteStartBraceIndent();
                    Class @class;
                    if (arrayType.TryGetClass(out @class) && @class.IsRefType)
                    {
                        supportBefore.WriteLine("if (value.Length != {0})", array.Size);
                        ThrowArgumentOutOfRangeException();
                    }
                    supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
                    if (@class != null && @class.IsRefType)
                    {
                        supportBefore.WriteLineIndent(
                            "*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
                            Context.ReturnVarName, arrayType, Helpers.InternalStruct,
                            Context.ArgName, Helpers.InstanceIdentifier);
                    }
                    else
                    {
                        if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                            Context.Context.Options.MarshalCharAsManagedChar)
                        {
                            supportBefore.WriteLineIndent(
                                "{0}[i] = global::System.Convert.ToSByte({1}[i]);",
                                Context.ReturnVarName, Context.ArgName);
                        }
                        else
                        {
                            supportBefore.WriteLineIndent("{0}[i] = {1}[i]{2};",
                                                          Context.ReturnVarName,
                                                          Context.ArgName,
                                                          arrayType.IsPointerToPrimitiveType(PrimitiveType.Void)
                                        ? ".ToPointer()"
                                        : string.Empty);
                        }
                    }
                    supportBefore.WriteCloseBraceIndent();
                }
                break;

            case ArrayType.ArraySize.Incomplete:
                MarshalArray(array);
                break;

            default:
                Context.Return.Write("null");
                break;
            }
            return(true);
        }
Esempio n. 46
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
            {
                return(false);
            }

            switch (array.SizeType)
            {
            case ArrayType.ArraySize.Constant:
                if (Context.MarshalKind == MarshalKind.NativeField ||
                    Context.MarshalKind == MarshalKind.ReturnVariableArray)
                {
                    var    supportBefore = Context.Before;
                    string value         = Generator.GeneratedIdentifier("value");
                    supportBefore.WriteLine("{0}[] {1} = null;", array.Type, value, array.Size);
                    supportBefore.WriteLine("if ({0} != null)", Context.ReturnVarName);
                    supportBefore.WriteStartBraceIndent();
                    supportBefore.WriteLine("{0} = new {1}[{2}];", value, array.Type, array.Size);
                    supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
                    if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
                    {
                        supportBefore.WriteLineIndent("{0}[i] = new global::System.IntPtr({1}[i]);",
                                                      value, Context.ReturnVarName);
                    }
                    else
                    {
                        var   arrayType = array.Type.Desugar();
                        Class @class;
                        if (arrayType.TryGetClass(out @class) && @class.IsRefType)
                        {
                            supportBefore.WriteLineIndent(
                                "{0}[i] = {1}.{2}(*(({1}.{3}*)&({4}[i * sizeof({1}.{3})])));",
                                value, array.Type, Helpers.CreateInstanceIdentifier,
                                Helpers.InternalStruct, Context.ReturnVarName);
                        }
                        else
                        {
                            if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                                Context.Context.Options.MarshalCharAsManagedChar)
                            {
                                supportBefore.WriteLineIndent(
                                    "{0}[i] = global::System.Convert.ToChar({1}[i]);",
                                    value, Context.ReturnVarName);
                            }
                            else
                            {
                                supportBefore.WriteLineIndent("{0}[i] = {1}[i];",
                                                              value, Context.ReturnVarName);
                            }
                        }
                    }
                    supportBefore.WriteCloseBraceIndent();
                    Context.Return.Write(value);
                }
                else
                {
                    goto case ArrayType.ArraySize.Incomplete;
                }
                break;

            case ArrayType.ArraySize.Incomplete:
                // const char* and const char[] are the same so we can use a string
                if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
                    array.QualifiedType.Qualifiers.IsConst)
                {
                    return(VisitPointerType(new PointerType
                    {
                        QualifiedPointee = array.QualifiedType
                    }, quals));
                }
                MarshalArray(array);
                break;

            case ArrayType.ArraySize.Variable:
                Context.Return.Write(Context.ReturnVarName);
                break;
            }

            return(true);
        }
Esempio n. 47
0
 protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type)
 {
     if (_arrayOfTRuntimeInterfacesAlgorithm == null)
     {
         _arrayOfTRuntimeInterfacesAlgorithm = new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetKnownType("System", "Array`1"));
     }
     return(_arrayOfTRuntimeInterfacesAlgorithm);
 }
Esempio n. 48
0
        public override TypePrinterResult VisitArrayType(ArrayType array,
                                                         TypeQualifiers quals)
        {
            Type arrayType = array.Type.Desugar();

            if (ContextKind == TypePrinterContextKind.Native &&
                array.SizeType == ArrayType.ArraySize.Constant)
            {
                PrimitiveType primitiveType;
                if ((arrayType.IsPointerToPrimitiveType(out primitiveType) &&
                     !(arrayType is FunctionType)) ||
                    (arrayType.IsPrimitiveType() && MarshalKind != MarshalKind.NativeField))
                {
                    if (primitiveType == PrimitiveType.Void)
                    {
                        return("void*");
                    }
                    return(string.Format("{0}", array.Type.Visit(this, quals)));
                }

                if (Parameter != null)
                {
                    return(string.Format("global::System.IntPtr"));
                }

                Enumeration @enum;
                if (arrayType.TryGetEnum(out @enum))
                {
                    return(new TypePrinterResult
                    {
                        Type = string.Format("fixed {0}", @enum.BuiltinType),
                        NameSuffix = string.Format("[{0}]", array.Size)
                    });
                }

                Class @class;
                if (arrayType.TryGetClass(out @class))
                {
                    return(new TypePrinterResult
                    {
                        Type = "fixed byte",
                        NameSuffix = string.Format("[{0}]", array.Size * @class.Layout.Size)
                    });
                }

                var arrayElemType = array.Type.Visit(this, quals).ToString();

                // C# does not support fixed arrays of machine pointer type (void* or IntPtr).
                // In that case, replace it by a pointer to an integer type of the same size.
                if (arrayElemType == IntPtrType)
                {
                    arrayElemType = Context.TargetInfo.PointerWidth == 64 ? "long" : "int";
                }

                // Do not write the fixed keyword multiple times for nested array types
                var fixedKeyword = array.Type is ArrayType ? string.Empty : "fixed ";
                return(new TypePrinterResult
                {
                    Type = string.Format("{0}{1}", fixedKeyword, arrayElemType),
                    NameSuffix = string.Format("[{0}]", array.Size)
                });
            }

            // const char* and const char[] are the same so we can use a string
            if (array.SizeType == ArrayType.ArraySize.Incomplete &&
                arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                array.QualifiedType.Qualifiers.IsConst)
            {
                return("string");
            }

            if (arrayType.IsPointerToPrimitiveType(PrimitiveType.Char))
            {
                return("char**");
            }

            return(string.Format("{0}{1}", array.Type.Visit(this),
                                 array.SizeType == ArrayType.ArraySize.Constant ? "[]" :
                                 (ContextKind == TypePrinterContextKind.Managed ? "*" : string.Empty)));

            // C# only supports fixed arrays in unsafe sections
            // and they are constrained to a set of built-in types.
        }
Esempio n. 49
0
        protected ArrayHeader DefineArray(uint array, ArrayType type, int dim2, int dim1)
        {
//            Debug.WriteLine("DefineArray: {0} {1} {2} {3}", array, type, dim2, dim1);
            Debug.Assert(0 <= type && (int)type <= 5);

            NukeArray(array);

            var id = FindFreeArrayId();

            int size;
            if (Game.Version == 8)
            {
                if ((array & 0x80000000) != 0)
                {
                    throw new InvalidOperationException("Can't define bit variable as array pointer");
                }
                size = (type == ArrayType.IntArray) ? 4 : 1;
            }
            else
            {
                if ((array & 0x8000) != 0)
                {
                    throw new InvalidOperationException("Can't define bit variable as array pointer");
                }

                size = (type == ArrayType.IntArray) ? 2 : 1;
            }

            WriteVariable(array, id);

            size *= dim2 + 1;
            size *= dim1 + 1;

            _strings[id] = new byte[size + 6 /*sizeof(ArrayHeader)*/];
            var ah = new ArrayHeader(_strings[id]);
            ah.Type = type;
            ah.Dim1 = dim1 + 1;
            ah.Dim2 = dim2 + 1;
            return ah;
        }
        private void GetXmlDocParameterPathRecursive(
            TypeReference tpType,
            bool ExplicitMode,
            StringBuilder CurrPath)
        {
            if (tpType == null)
            {
                return;
            }

            if (tpType.GenericParameters.Count > 0)
            {
                CurrPath.Append(
                    tpType.Namespace +
                    ((CanAppendSpecialExplicitChar() && ExplicitMode) ? "#" : ".") +
                    StripGenericName(tpType.Name));

                // list parameters or types
                bool firstAppend = true;
                CurrPath.Append("{");
                foreach (GenericParameter TempType in tpType.GenericParameters)
                {
                    if (!firstAppend)
                    {
                        CurrPath.Append(",");
                    }

                    CurrPath.Append(GetXmlDocParameterPath(TempType, ExplicitMode));
                    firstAppend = false;
                }
                CurrPath.Append("}");
            }
            else if (tpType is GenericInstanceType)
            {
                GenericInstanceType thisGenericType = tpType as GenericInstanceType;

                // if nested, scan enclosing type
                if (tpType.DeclaringType != null)
                {
                    CurrPath.Append(GetXmlDocParameterPath(tpType.DeclaringType, ExplicitMode));
                }

                // determine namespace
                string strNamespace = string.Empty;
                if ((tpType.Namespace != null && tpType.Namespace.Length > 0) || tpType.DeclaringType != null)
                {
                    strNamespace = tpType.Namespace +
                                   ((CanAppendSpecialExplicitChar() && ExplicitMode) ? "#" : ".");
                }

                CurrPath.Append(strNamespace + StripGenericName(thisGenericType.Name));

                // list parameters or types
                bool firstAppend = true;
                CurrPath.Append("{");
                foreach (TypeReference tempTypeRef in thisGenericType.GenericArguments)
                {
                    if (!firstAppend)
                    {
                        CurrPath.Append(",");
                    }

                    CurrPath.Append(GetXmlDocParameterPath(tempTypeRef, ExplicitMode));
                    firstAppend = false;
                }
                CurrPath.Append("}");
            }
            else if (tpType is GenericParameter)
            {
                GenericParameter thisGenParam = tpType as GenericParameter;

                if (ExplicitMode)
                {
                    // in explicit mode we print parameter name
                    CurrPath.Append(thisGenParam.Name);
                }
                else
                {
                    // in non-explicit mode we print parameter order
                    int paramOrder = 0;

                    // find
                    for (int i = 0; i < thisGenParam.Owner.GenericParameters.Count; i++)
                    {
                        if (thisGenParam.Owner.GenericParameters[i].Name == tpType.Name)
                        {
                            paramOrder = i;
                            break;
                        }
                    }
                    if (thisGenParam.Owner is MethodReference)
                    {
                        CurrPath.Append("``" + paramOrder);
                    }
                    else
                    {
                        CurrPath.Append("`" + paramOrder);
                    }
                }
            }
            else if (tpType is PointerType)
            {
                // parameter is pointer type
                CurrPath.Append(GetXmlDocParameterPath((tpType as PointerType).ElementType, ExplicitMode));
                CurrPath.Append("*");
            }
            else if (tpType is ArrayType)
            {
                ArrayType thisArrayType = tpType as ArrayType;
                if (thisArrayType.ElementType != null)
                {
                    CurrPath.Append(GetXmlDocParameterPath(thisArrayType.ElementType, ExplicitMode));
                }

                int iRank = thisArrayType.Rank;
                if (iRank == 1)
                {
                    CurrPath.Append("[]");
                }
                else
                {
                    bool firstAppend = true;
                    CurrPath.Append("[");

                    for (int i = 0; i < (ExplicitMode ? iRank - 1 : iRank); i++)
                    {
                        // in explicit mode for .NET3.5/VS2008,
                        // there is no separator char "," used for multi-dimensional array,
                        // so there are three cases when comma shall be added:
                        // firstAppend = false; ExplicitMode = false; CanAppendSpecialExplicitChar() = true;
                        // firstAppend = false; ExplicitMode = false; CanAppendSpecialExplicitChar() = false;
                        // firstAppend = false; ExplicitMode = true; CanAppendSpecialExplicitChar() = false;
                        // below this is stored in decent manner
                        if (!firstAppend && (!ExplicitMode || !CanAppendSpecialExplicitChar()))
                        {
                            CurrPath.Append(",");
                        }

                        CurrPath.Append(((CanAppendSpecialExplicitChar() && ExplicitMode) ? "@" : "0:"));
                        if (thisArrayType.Dimensions[i].UpperBound > 0)
                        {
                            CurrPath.Append(thisArrayType.Dimensions[i].UpperBound.ToString());
                        }
                        firstAppend = false;
                    }

                    CurrPath.Append("]");
                }
            }
//            else if (!tpType.IsValueType)
//            {
//                // parameter is passed by reference
//                CurrPath.Append(GetXmlDocParameterPath((tpType as ReferenceType).ElementType, false));
//                CurrPath.Append("@");
//            }
//            else if (tpType is ModifierOptional)
//            {
//                // parameter has optional modifier
//                ModifierOptional thisModOpt = tpType as ModifierOptional;
//
//                CurrPath.Append(GetXmlDocParameterPath(thisModOpt.ElementType, ExplicitMode));
//                CurrPath.Append("!");
//                CurrPath.Append(GetXmlDocParameterPath(thisModOpt.ModifierType, ExplicitMode));
//            }
//            else if (tpType is ModifierRequired)
//            {
//                // parameter has required modifier
//                ModifierRequired thisModReq = tpType as ModifierRequired;
//
//                CurrPath.Append(GetXmlDocParameterPath(thisModReq.ElementType, ExplicitMode));
//                CurrPath.Append("|");
//                CurrPath.Append(GetXmlDocParameterPath(thisModReq.ModifierType, ExplicitMode));
//            }
            else if (tpType is FunctionPointerType)
            {
                // type is function pointer
                FunctionPointerType thisFuncPtr = tpType as FunctionPointerType;
//                string tempString = string.Empty;

                // return type
                CurrPath.Append("=FUNC:");
                CurrPath.Append(GetXmlDocParameterPath(thisFuncPtr.ReturnType, ExplicitMode));

                // method's parameters
                if (thisFuncPtr.Parameters.Count > 0)
                {
                    bool firstAppend = true;
                    CurrPath.Append("(");

                    foreach (ParameterDefinition tempParam in thisFuncPtr.Parameters)
                    {
                        if (!firstAppend)
                        {
                            CurrPath.Append(",");
                        }

                        CurrPath.Append(GetXmlDocParameterPath(tempParam.ParameterType, ExplicitMode));
                        firstAppend = false;
                    }

                    CurrPath.Append(")");
                }
                else
                {
                    CurrPath.Append("(System.Void)");
                }
            }
            else if (tpType is PinnedType)
            {
                // type is pinned type
                CurrPath.Append(GetXmlDocParameterPath((tpType as PinnedType).ElementType, ExplicitMode));
                CurrPath.Append("^");
            }
            else if (tpType is TypeReference)
            {
                // if nested, scan enclosing type
                if (tpType.DeclaringType != null)
                {
                    CurrPath.Append(GetXmlDocParameterPath(tpType.DeclaringType, ExplicitMode));
                }

                // determine namespace
                string strNamespace = string.Empty;
                if ((tpType.Namespace != null && tpType.Namespace.Length > 0) || tpType.DeclaringType != null)
                {
                    strNamespace = tpType.Namespace +
                                   ((CanAppendSpecialExplicitChar() && ExplicitMode) ? "#" : ".");
                }

                // concrete type
                CurrPath.Append(
                    strNamespace +
                    ((CanAppendSpecialExplicitChar() && ExplicitMode) ? tpType.Name.Replace(".", "#") : tpType.Name));
            }
        }
Esempio n. 51
0
 private static void* __CopyValue(ArrayType.__Internal native)
 {
     var ret = Marshal.AllocHGlobal(28);
     global::CppSharp.Parser.AST.ArrayType.__Internal.cctor_2(ret, new global::System.IntPtr(&native));
     return ret.ToPointer();
 }
Esempio n. 52
0
 protected string GetNameOfType(ArrayType type)
 {
     return(GetNameOfType(type.ElementType as dynamic) + "[]");
 }
Esempio n. 53
0
 private ArrayType(ArrayType.Internal native, bool skipVTables = false)
     : this(__CopyValue(native), skipVTables)
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Esempio n. 54
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
            {
                return(false);
            }

            switch (array.SizeType)
            {
            case ArrayType.ArraySize.Constant:
                if (string.IsNullOrEmpty(Context.ReturnVarName))
                {
                    goto case ArrayType.ArraySize.Incomplete;
                }

                var supportBefore = Context.Before;
                supportBefore.WriteLine($"if ({Context.ArgName} != null)");
                supportBefore.WriteOpenBraceAndIndent();
                Class @class;
                var   arrayType      = array.Type.Desugar();
                var   finalArrayType = arrayType.GetPointee() ?? arrayType;
                if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
                {
                    supportBefore.WriteLine($"if (value.Length != {array.Size})");
                    ThrowArgumentOutOfRangeException();
                }
                supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
                if (@class != null && @class.IsRefType)
                {
                    if (finalArrayType == arrayType)
                    {
                        supportBefore.WriteLineIndent(
                            "*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
                            Context.ReturnVarName, arrayType, Helpers.InternalStruct,
                            Context.ArgName, Helpers.InstanceIdentifier);
                    }
                    else
                    {
                        supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = ({
                                (Context.Context.TargetInfo.PointerWidth == 64 ? "long" : "int")}) {
                                Context.ArgName}[i].{Helpers.InstanceIdentifier};");
                    }
                }
                else
                {
                    if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
                    {
                        supportBefore.WriteLineIndent($@"{
                                Context.ReturnVarName}[i] = (byte)({
                                Context.ArgName}[i] ? 1 : 0);");
                    }
                    else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                             Context.Context.Options.MarshalCharAsManagedChar)
                    {
                        supportBefore.WriteLineIndent($@"{
                                Context.ReturnVarName}[i] = global::System.Convert.ToSByte({
                                Context.ArgName}[i]);");
                    }
                    else
                    {
                        supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = {
                                Context.ArgName}[i]{
                                (arrayType.IsPointerToPrimitiveType(PrimitiveType.Void) ?
                                    ".ToPointer()" : string.Empty)};");
                    }
                }
                supportBefore.UnindentAndWriteCloseBrace();
                break;

            case ArrayType.ArraySize.Incomplete:
                MarshalArray(array);
                break;

            default:
                Context.Return.Write("null");
                break;
            }
            return(true);
        }
Esempio n. 55
0
 public static CppType CreateArray(CppType arrayItem, ArrayType array, bool optional, wsdlParser.qname xmlType)
 {
     return(Factory(arrayItem, array, TypeStyle.Primative, optional, xmlType));
 }
Esempio n. 56
0
        internal static TypeDesc GetNativeTypeFromMarshallerKind(TypeDesc type,
                                                                 MarshallerKind kind,
                                                                 MarshallerKind elementMarshallerKind,
#if !READYTORUN
                                                                 InteropStateManager interopStateManager,
#endif
                                                                 MarshalAsDescriptor marshalAs,
                                                                 bool isArrayElement = false)
        {
            TypeSystemContext context    = type.Context;
            NativeTypeKind    nativeType = NativeTypeKind.Default;

            if (marshalAs != null)
            {
                nativeType = isArrayElement ? marshalAs.ArraySubType : marshalAs.Type;
            }

            switch (kind)
            {
            case MarshallerKind.BlittableValue:
            {
                switch (nativeType)
                {
                case NativeTypeKind.I1:
                    return(context.GetWellKnownType(WellKnownType.SByte));

                case NativeTypeKind.U1:
                    return(context.GetWellKnownType(WellKnownType.Byte));

                case NativeTypeKind.I2:
                    return(context.GetWellKnownType(WellKnownType.Int16));

                case NativeTypeKind.U2:
                    return(context.GetWellKnownType(WellKnownType.UInt16));

                case NativeTypeKind.I4:
                    return(context.GetWellKnownType(WellKnownType.Int32));

                case NativeTypeKind.U4:
                    return(context.GetWellKnownType(WellKnownType.UInt32));

                case NativeTypeKind.I8:
                    return(context.GetWellKnownType(WellKnownType.Int64));

                case NativeTypeKind.U8:
                    return(context.GetWellKnownType(WellKnownType.UInt64));

                case NativeTypeKind.R4:
                    return(context.GetWellKnownType(WellKnownType.Single));

                case NativeTypeKind.R8:
                    return(context.GetWellKnownType(WellKnownType.Double));

                default:
                    return(type.UnderlyingType);
                }
            }

            case MarshallerKind.Bool:
                return(context.GetWellKnownType(WellKnownType.Int32));

            case MarshallerKind.CBool:
                return(context.GetWellKnownType(WellKnownType.Byte));

            case MarshallerKind.Enum:
            case MarshallerKind.BlittableStruct:
            case MarshallerKind.Decimal:
            case MarshallerKind.VoidReturn:
                return(type);

#if !READYTORUN
            case MarshallerKind.Struct:
            case MarshallerKind.LayoutClass:
                return(interopStateManager.GetStructMarshallingNativeType((MetadataType)type));
#endif

            case MarshallerKind.BlittableStructPtr:
                return(type.MakePointerType());

            case MarshallerKind.HandleRef:
                return(context.GetWellKnownType(WellKnownType.IntPtr));

            case MarshallerKind.UnicodeChar:
                if (nativeType == NativeTypeKind.U2)
                {
                    return(context.GetWellKnownType(WellKnownType.UInt16));
                }
                else
                {
                    return(context.GetWellKnownType(WellKnownType.Int16));
                }

            case MarshallerKind.OleDateTime:
                return(context.GetWellKnownType(WellKnownType.Double));

            case MarshallerKind.SafeHandle:
            case MarshallerKind.CriticalHandle:
                return(context.GetWellKnownType(WellKnownType.IntPtr));

            case MarshallerKind.UnicodeString:
            case MarshallerKind.UnicodeStringBuilder:
                return(context.GetWellKnownType(WellKnownType.Char).MakePointerType());

            case MarshallerKind.AnsiString:
            case MarshallerKind.AnsiStringBuilder:
            case MarshallerKind.UTF8String:
                return(context.GetWellKnownType(WellKnownType.Byte).MakePointerType());

            case MarshallerKind.BlittableArray:
            case MarshallerKind.Array:
            case MarshallerKind.AnsiCharArray:
            {
                ArrayType arrayType = type as ArrayType;
                Debug.Assert(arrayType != null, "Expecting array");

                //
                // We need to construct the unsafe array from the right unsafe array element type
                //
                TypeDesc elementNativeType = GetNativeTypeFromMarshallerKind(
                    arrayType.ElementType,
                    elementMarshallerKind,
                    MarshallerKind.Unknown,
#if !READYTORUN
                    interopStateManager,
#endif
                    marshalAs,
                    isArrayElement: true);

                return(elementNativeType.MakePointerType());
            }

            case MarshallerKind.AnsiChar:
                return(context.GetWellKnownType(WellKnownType.Byte));

            case MarshallerKind.FunctionPointer:
                return(context.GetWellKnownType(WellKnownType.IntPtr));

#if !READYTORUN
            case MarshallerKind.ByValUnicodeString:
            case MarshallerKind.ByValAnsiString:
            {
                var inlineArrayCandidate = GetInlineArrayCandidate(context.GetWellKnownType(WellKnownType.Char), elementMarshallerKind, interopStateManager, marshalAs);
                return(interopStateManager.GetInlineArrayType(inlineArrayCandidate));
            }

            case MarshallerKind.ByValAnsiCharArray:
            case MarshallerKind.ByValArray:
            {
                ArrayType arrayType = type as ArrayType;
                Debug.Assert(arrayType != null, "Expecting array");

                var inlineArrayCandidate = GetInlineArrayCandidate(arrayType.ElementType, elementMarshallerKind, interopStateManager, marshalAs);

                return(interopStateManager.GetInlineArrayType(inlineArrayCandidate));
            }
#endif

            case MarshallerKind.LayoutClassPtr:
            case MarshallerKind.AsAnyA:
            case MarshallerKind.AsAnyW:
                return(context.GetWellKnownType(WellKnownType.IntPtr));

            case MarshallerKind.Unknown:
            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 57
0
 private static ArrayType.Internal* __CopyValue(ArrayType.Internal native)
 {
     var ret = Marshal.AllocHGlobal(48);
     CppSharp.Parser.AST.ArrayType.Internal.cctor_2(ret, new global::System.IntPtr(&native));
     return (ArrayType.Internal*) ret;
 }
Esempio n. 58
0
        //=====================================================================

        /// <summary>
        /// Write out a type name
        /// </summary>
        /// <param name="type">The type for which to write out the name</param>
        /// <param name="sb">The string builder to which the name is written</param>
        private static void WriteType(TypeNode type, StringBuilder sb)
        {
            switch (type.NodeType)
            {
            case NodeType.ArrayType:
                ArrayType array = (ArrayType)type;
                WriteType(array.ElementType, sb);

                sb.Append("[");

                if (array.Rank > 1)
                {
                    for (int i = 0; i < array.Rank; i++)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }

                        sb.Append("0:");
                    }
                }

                sb.Append("]");
                break;

            case NodeType.Reference:
                Reference reference = (Reference)type;
                WriteType(reference.ElementType, sb);
                sb.Append("@");
                break;

            case NodeType.Pointer:
                Pointer pointer = (Pointer)type;
                WriteType(pointer.ElementType, sb);
                sb.Append("*");
                break;

            case NodeType.OptionalModifier:
                TypeModifier optionalModifierClause = (TypeModifier)type;
                WriteType(optionalModifierClause.ModifiedType, sb);
                sb.Append("!");
                WriteType(optionalModifierClause.Modifier, sb);
                break;

            case NodeType.RequiredModifier:
                TypeModifier requiredModifierClause = (TypeModifier)type;
                WriteType(requiredModifierClause.ModifiedType, sb);
                sb.Append("|");
                WriteType(requiredModifierClause.Modifier, sb);
                break;

            default:
                if (type.IsTemplateParameter)
                {
                    ITypeParameter gtp = (ITypeParameter)type;

                    if (gtp.DeclaringMember is TypeNode)
                    {
                        sb.Append("`");
                    }
                    else
                    if (gtp.DeclaringMember is Method)
                    {
                        sb.Append("``");
                    }
                    else
                    {
                        throw new InvalidOperationException("Generic parameter not on type or method");
                    }

                    sb.Append(gtp.ParameterListIndex);
                }
                else
                {
                    // Namespace
                    TypeNode declaringType = type.DeclaringType;

                    if (declaringType != null)
                    {
                        // Names of nested types begin with outer type name
                        WriteType(declaringType, sb);
                        sb.Append(".");
                    }
                    else
                    {
                        // Otherwise just prefix with the namespace
                        Identifier space = type.Namespace;

                        if (space != null && !String.IsNullOrEmpty(space.Name))
                        {
                            sb.Append(space.Name);
                            sb.Append(".");
                        }
                    }

                    // Name
                    sb.Append(type.GetUnmangledNameWithoutTypeParameters());

                    // Generic parameters
                    if (type.IsGeneric)
                    {
                        // Number of parameters
                        TypeNodeList parameters = type.TemplateParameters;

                        if (parameters != null)
                        {
                            sb.Append('`');
                            sb.Append(parameters.Count);
                        }

                        // Arguments
                        TypeNodeList arguments = type.TemplateArguments;

                        if (arguments != null && arguments.Count > 0)
                        {
                            sb.Append("{");

                            for (int i = 0; i < arguments.Count; i++)
                            {
                                if (i > 0)
                                {
                                    sb.Append(",");
                                }

                                WriteType(arguments[i], sb);
                            }

                            sb.Append("}");
                        }
                    }
                }
                break;
            }
        }
Esempio n. 59
0
 protected ArrayType(ArrayType.Internal* native, bool isInternalImpl = false)
     : base((CppSharp.Parser.AST.Type.Internal*) native)
 {
 }
Esempio n. 60
0
        protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory)
        {
            DependencyList dependencyList = base.ComputeNonRelocationBasedDependencies(factory);

            // Ensure that we track the necessary type symbol if we are working with a constructed type symbol.
            // The emitter will ensure we don't emit both, but this allows us assert that we only generate
            // relocs to nodes we emit.
            dependencyList.Add(factory.NecessaryTypeSymbol(_type), "NecessaryType for constructed type");

            DefType closestDefType = _type.GetClosestDefType();

            if (_type.RuntimeInterfaces.Length > 0)
            {
                dependencyList.Add(factory.InterfaceDispatchMap(_type), "Interface dispatch map");
            }

            if (_type.IsArray)
            {
                // Array EEType depends on System.Array's virtuals. Array EETypes don't point to
                // their base type (i.e. there's no reloc based dependency making this "just work").
                dependencyList.Add(factory.ConstructedTypeSymbol(_type.BaseType), "Array base type");

                ArrayType arrayType = (ArrayType)_type;
                if (arrayType.IsMdArray && arrayType.Rank == 1)
                {
                    // Allocating an MDArray of Rank 1 with zero lower bounds results in allocating
                    // an SzArray instead. Make sure the type loader can find the SzArray type.
                    dependencyList.Add(factory.ConstructedTypeSymbol(arrayType.ElementType.MakeArrayType()), "Rank 1 array");
                }
            }

            dependencyList.Add(factory.VTable(closestDefType), "VTable");

            if (closestDefType.HasInstantiation)
            {
                TypeDesc canonType           = _type.ConvertToCanonForm(CanonicalFormKind.Specific);
                TypeDesc canonClosestDefType = closestDefType.ConvertToCanonForm(CanonicalFormKind.Specific);

                // Add a dependency on the template for this type, if the canonical type should be generated into this binary.
                // If the type is an array type, the check should be on its underlying Array<T> type. This is because a copy of
                // an array type gets placed into each module but the Array<T> type only exists in the defining module and only
                // one template is needed for the Array<T> type by the dynamic type loader.
                if (canonType.IsCanonicalSubtype(CanonicalFormKind.Any) && !factory.NecessaryTypeSymbol(canonClosestDefType).RepresentsIndirectionCell)
                {
                    dependencyList.Add(factory.NativeLayout.TemplateTypeLayout(canonType), "Template Type Layout");
                }
            }

            // Generated type contains generic virtual methods that will get added to the GVM tables
            if (TypeGVMEntriesNode.TypeNeedsGVMTableEntries(_type))
            {
                dependencyList.Add(new DependencyListEntry(factory.TypeGVMEntries(_type), "Type with generic virtual methods"));
            }

            if (factory.TypeSystemContext.HasLazyStaticConstructor(_type))
            {
                // The fact that we generated an EEType means that someone can call RuntimeHelpers.RunClassConstructor.
                // We need to make sure this is possible.
                dependencyList.Add(new DependencyListEntry(factory.TypeNonGCStaticsSymbol((MetadataType)_type), "Class constructor"));
            }

            // Ask the metadata manager if we have any dependencies due to reflectability.
            factory.MetadataManager.GetDependenciesDueToReflectability(ref dependencyList, factory, _type);

            factory.InteropStubManager.AddInterestingInteropConstructedTypeDependencies(ref dependencyList, factory, _type);

            return(dependencyList);
        }