Ejemplo n.º 1
0
 public IntPtrTypeMap(TypedefNameDecl td, BindingContext ctx, TypeMapDatabase dataBase)
 {
     Type            = td.Type;
     Context         = ctx;
     TypeMapDatabase = dataBase;
     InjectedType    = new CILType(typeof(IntPtr));
 }
Ejemplo n.º 2
0
        bool HandleSpecialCILType(CILType cilType)
        {
            var type = cilType.Type;

            if (type == typeof(string))
            {
                var argId      = CGenerator.GenId(Context.ArgName);
                var contextId  = CGenerator.GenId("mono_context");
                var stringText = Context.ArgName;

                var param   = Context.Parameter;
                var isByRef = param != null && (param.IsOut || param.IsInOut);
                if (isByRef)
                {
                    stringText = string.Format("({0}->len != 0) ? {0}->str : \"\"",
                                               Context.ArgName);

                    Context.SupportAfter.WriteLine("g_string_truncate({0}, 0);", Context.ArgName);
                    Context.SupportAfter.WriteLine("g_string_append({0}, mono_string_to_utf8(" +
                                                   "(MonoString*) {1}));", Context.ArgName, argId);
                }

                Context.SupportBefore.WriteLine("MonoString* {0} = mono_string_new({1}.domain, {2});",
                                                argId, contextId, stringText);
                Context.Return.Write("{0}{1}", isByRef ? "&" : string.Empty, argId);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 3
0
        public static CILTypeSpecification GetValue(ParseTreeNode node)
        {
            CILClassName className = null;
            CILType      type      = null;

            var classNameParseTreeNode = node.GetFirstChildWithGrammarName(GrammarNames.className);

            if (classNameParseTreeNode != null)
            {
                className = ClassNameParseTreeNodeHelper.GetClassName(classNameParseTreeNode);
            }

            var typeParseTreeNode = node.GetFirstChildWithGrammarName(GrammarNames.type);

            if (typeParseTreeNode != null)
            {
                type = TypeParseTreeNodeHelper.GetType(typeParseTreeNode);
            }

            return(new CILTypeSpecification
            {
                ClassName = className,
                Type = type
            });
        }
Ejemplo n.º 4
0
 internal CILFieldImpl(
     CILReflectionContextImpl ctx,
     Int32 anID,
     CILType declaringType,
     String name,
     CILTypeBase fieldType,
     FieldAttributes attrs
     )
     : this(
         ctx,
         anID,
         new LazyWithLock <ListProxy <CILCustomAttribute> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomAttribute>()),
         new SettableValueForEnums <FieldAttributes>(attrs),
         new SettableValueForClasses <String>(name),
         () => declaringType,
         () => fieldType,
         new SettableLazy <Object>(() => null),
         new SettableValueForClasses <Byte[]>(null),
         new LazyWithLock <ListProxy <CILCustomModifier> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomModifier>()),
         new SettableLazy <Int32>(() => NO_OFFSET),
         new SettableLazy <MarshalingInfo>(() => null),
         true
         )
 {
 }
Ejemplo n.º 5
0
        public override int GetHashCode()
        {
            int hash = CILType.GetHashCode();

            if (!IsUnconstrained)
            {
                foreach (object arg in TypeParams)
                {
                    if (arg != null)
                    {
                        hash ^= arg.GetHashCode();
                    }
                    hash *= 3;
                }
            }

            TypeDescriptor[] deps = GetDependentTypes();
            foreach (TypeDescriptor dep in deps)
            {
                hash ^= dep.GetHashCode();
                hash *= 3;
            }

            return(hash);
        }
Ejemplo n.º 6
0
        internal CILCustomAttributeTypedArgumentImpl(CILType argumentType, Object value)
        {
            ArgumentValidator.ValidateNotNull("Argument type", argumentType);

            this.argumentType = argumentType;
            this.value        = value;
        }
Ejemplo n.º 7
0
        public CILVariableDecl CreateStaticGlobal(SourceInfo si, CILType type, int pointerDepth, string name)
        {
            var global = new CILVariableDecl(si, type, pointerDepth, name, true);

            AddGlobal(global);
            return(global);
        }
Ejemplo n.º 8
0
 public Boolean RemoveType(CILType type)
 {
     lock (this.types.Lock)
     {
         // ((CILTypeInternal)type).RemoveModule(); // TODO
         return(this.types.Value.Remove(type));
     }
 }
Ejemplo n.º 9
0
        public virtual bool VisitCILType(CILType type, TypeQualifiers quals)
        {
            if (!VisitType(type, quals))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 10
0
        public override bool VisitCILType(CILType type, TypeQualifiers quals)
        {
            if (HandleSpecialCILType(type))
            {
                return(true);
            }

            return(base.VisitCILType(type, quals));
        }
Ejemplo n.º 11
0
        public override TypePrinterResult VisitCILType(CILType type, TypeQualifiers quals)
        {
            var result = type.Type.FullName.Replace(".", "::");

            if (!type.Type.IsValueType)
            {
                result += "^";
            }
            return(result);
        }
Ejemplo n.º 12
0
        public CILCustomModifier AddCustomModifier(CILType type, CILCustomModifierOptionality optionality)
        {
            var result = new CILCustomModifierImpl(optionality, type);

            lock (this.customModifiers.Lock)
            {
                this.customModifiers.Value.Add(result);
            }
            return(result);
        }
Ejemplo n.º 13
0
        public CILField ChangeDeclaringType(params CILTypeBase[] args)
        {
            LogicalUtils.ThrowIfDeclaringTypeNotGeneric(this, args);
            CILField fieldToGive = this;
            CILType  dt          = this.declaringType.Value;

            if (dt.GenericDefinition != null)
            {
                fieldToGive = dt.GenericDefinition.DeclaredFields[dt.DeclaredFields.IndexOf(this)];
            }
            return(this.context.Cache.MakeFieldWithGenericDeclaringType(fieldToGive, args));
        }
Ejemplo n.º 14
0
        public CILEvent ChangeDeclaringType(params CILTypeBase[] args)
        {
            LogicalUtils.ThrowIfDeclaringTypeNotGeneric(this, args);
            CILEvent evtToGive = this;
            CILType  dt        = this.declaringType.Value;

            if (dt.GenericDefinition != null)
            {
                evtToGive = dt.GenericDefinition.DeclaredEvents[dt.DeclaredEvents.IndexOf(this)];
            }
            return(this.context.Cache.MakeEventWithGenericType(evtToGive, args));
        }
Ejemplo n.º 15
0
        public CILProperty ChangeDeclaringType(params CILTypeBase[] args)
        {
            LogicalUtils.ThrowIfDeclaringTypeNotGeneric(this, args);
            CILProperty propToGive = this;
            CILType     dt         = this.declaringType.Value;

            if (dt.GenericDefinition != null)
            {
                propToGive = dt.GenericDefinition.DeclaredProperties[dt.DeclaredProperties.IndexOf(this)];
            }
            return(this.context.Cache.MakePropertyWithGenericType(propToGive, args));
        }
Ejemplo n.º 16
0
        private void ComputeDependentTypes()
        {
            if (!CILType.IsPrimitive)
            {
                var fields = CILType.GetFields(
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                foreach (FieldInfo field in fields)
                {
                    bool consider = (CILType.IsValueType && !HasIntrinsicTypeOverride) ||
                                    field.HasCustomOrInjectedAttribute <DependentType>();
                    if (!consider)
                    {
                        continue;
                    }

                    object fieldVal = _sample == null ? null : field.GetValue(_sample);
                    if (fieldVal == null)
                    {
                        _memberTypes[field] = new TypeDescriptor(field.FieldType);
                    }
                    else
                    {
                        _memberTypes[field] = new TypeDescriptor(fieldVal);
                    }
                }

                var properties = CILType.GetProperties(
                    BindingFlags.Instance | BindingFlags.Public);

                foreach (PropertyInfo prop in properties)
                {
                    bool consider = prop.HasCustomOrInjectedAttribute <DependentType>();
                    if (!consider)
                    {
                        continue;
                    }

                    object propVal = _sample == null ? null : prop.GetValue(_sample, new object[0]);
                    if (propVal == null)
                    {
                        _memberTypes[prop] = new TypeDescriptor(prop.PropertyType);
                    }
                    else
                    {
                        _memberTypes[prop] = new TypeDescriptor(propVal);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public override TypePrinterResult VisitCILType(CILType type, TypeQualifiers quals)
        {
            switch (System.Type.GetTypeCode(type.Type))
            {
            case TypeCode.Boolean:
                return("bool");

            case TypeCode.Char:
                return("char");

            case TypeCode.SByte:
                return("sbyte");

            case TypeCode.Byte:
                return("byte");

            case TypeCode.Int16:
                return("short");

            case TypeCode.UInt16:
                return("ushort");

            case TypeCode.Int32:
                return("int");

            case TypeCode.UInt32:
                return("uint");

            case TypeCode.Int64:
                return("long");

            case TypeCode.UInt64:
                return("ulong");

            case TypeCode.Single:
                return("float");

            case TypeCode.Double:
                return("double");

            case TypeCode.Decimal:
                return("decimal");

            case TypeCode.String:
                return("string");
            }

            return(QualifiedType(type.Type.FullName));
        }
Ejemplo n.º 18
0
        public override string VisitCILType(CILType type, TypeQualifiers quals)
        {
            if (type.Type == typeof(string))
            {
                if (param != null && (param.IsOut || param.IsInOut))
                {
                    return("GString*");
                }

                return(quals.IsConst ? "const char*" : "char*");
            }

            throw new System.NotImplementedException(
                      string.Format("Unhandled .NET type: {0}", type.Type));
        }
Ejemplo n.º 19
0
 public SecurityInformation AddDeclarativeSecurity(SecurityAction action, CILType securityAttributeType)
 {
     lock (this.securityInfo.Value)
     {
         ListProxy <SecurityInformation> list;
         if (!this.securityInfo.Value.CQ.TryGetValue(action, out list))
         {
             list = this.context.CollectionsFactory.NewListProxy <SecurityInformation>();
             this.securityInfo.Value.Add(action, list);
         }
         var result = new SecurityInformation(action, securityAttributeType);
         list.Add(result);
         return(result);
     }
 }
Ejemplo n.º 20
0
 internal CILPropertyImpl(CILReflectionContextImpl ctx, Int32 anID, CILType declaringType, String aName, PropertyAttributes aPropertyAttributes)
     : this(
         ctx,
         anID,
         new LazyWithLock <ListProxy <CILCustomAttribute> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomAttribute>()),
         new SettableValueForClasses <String>(aName),
         new SettableValueForEnums <PropertyAttributes>(aPropertyAttributes),
         () => null,
         () => null,
         () => declaringType,
         new SettableLazy <Object>(() => null),
         new LazyWithLock <ListProxy <CILCustomModifier> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomModifier>()),
         true
         )
 {
 }
Ejemplo n.º 21
0
        bool HandleSpecialCILType(CILType cilType)
        {
            var type = cilType.Type;

            if (type == typeof(string))
            {
                var stringId = CGenerator.GenId("string");
                Context.SupportBefore.WriteLine("char* {0} = mono_string_to_utf8(" +
                                                "(MonoString*) {1});", stringId, Context.ArgName);

                Context.Return.Write("{0}", stringId);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 22
0
 internal CILEventImpl(CILReflectionContextImpl ctx, Int32 anID, CILType declaringType, String aName, EventAttributes anEventAttributes, CILTypeBase anEventType)
     : this(
         ctx,
         anID,
         new LazyWithLock <ListProxy <CILCustomAttribute> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomAttribute>()),
         new SettableValueForClasses <String>(aName),
         new SettableValueForEnums <EventAttributes>(anEventAttributes),
         () => anEventType,
         () => null,
         () => null,
         () => null,
         () => ctx.CollectionsFactory.NewListProxy <CILMethod>(),
         () => declaringType,
         true)
 {
 }
Ejemplo n.º 23
0
        public override TypePrinterResult VisitCILType(CILType type, TypeQualifiers quals)
        {
            if (type.Type == typeof(string))
            {
                return(quals.IsConst ? "const char*" : "char*");
            }

            switch (System.Type.GetTypeCode(type.Type))
            {
            case TypeCode.Boolean:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Bool), quals));

            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.Byte:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Char), quals));

            case TypeCode.Int16:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Short), quals));

            case TypeCode.UInt16:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.UShort), quals));

            case TypeCode.Int32:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Int), quals));

            case TypeCode.UInt32:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.UInt), quals));

            case TypeCode.Int64:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Long), quals));

            case TypeCode.UInt64:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.ULong), quals));

            case TypeCode.Single:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Float), quals));

            case TypeCode.Double:
                return(VisitBuiltinType(new BuiltinType(PrimitiveType.Double), quals));

            case TypeCode.String:
                return(quals.IsConst ? "const char*" : "char*");
            }

            return("void*");
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Constructs a type descriptor.
        /// </summary>
        /// <param name="sample">sample value from which to extract the type information</param>
        /// <param name="asPointer">whether to construct a pointer type</param>
        /// <param name="asReference">whether to construct a reference type</param>
        public TypeDescriptor(object sample, bool asPointer = false, bool asReference = false)
        {
            _sample = sample;
            CILType = sample.GetType();
            if (asReference)
            {
                CILType = CILType.MakeByRefType();
            }
            if (asPointer)
            {
                CILType = CILType.MakePointerType();
            }

            InitTypeParams();
            ComputeDependentTypes();
            Owner = RootTypeLibrary.Instance;
        }
Ejemplo n.º 25
0
 internal CILConstructorImpl(
     CILReflectionContextImpl ctx,
     Int32 anID,
     CILType declaringType,
     MethodAttributes attrs
     )
     : this(
         ctx,
         anID,
         new LazyWithLock <ListProxy <CILCustomAttribute> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomAttribute>()),
         new SettableValueForEnums <CallingConventions>(CallingConventions.Standard),
         new SettableValueForEnums <MethodAttributes>(attrs | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName),
         () => declaringType,
         () => ctx.CollectionsFactory.NewListProxy <CILParameter>(),
         () => new MethodILImpl(declaringType.Module),
         new SettableLazy <MethodImplAttributes>(() => MethodImplAttributes.IL),
         null,
         true
         )
 {
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Represents the described multi-dimensional array as array of arrays. Only applicable to array types.
        /// </summary>
        public TypeDescriptor[] MakeRank1Types()
        {
            if (Rank == 0)
            {
                throw new InvalidOperationException("This operation is possible for types with Rank >= 1");
            }

            if (Rank == 1)
            {
                return new TypeDescriptor[] { this }
            }
            ;

            if (!CILType.IsArray)
            {
                throw new InvalidOperationException("This operation is possible for arrays");
            }

            TypeDescriptor[] result    = new TypeDescriptor[Rank];
            Type             innerType = CILType.GetElementType();
            TypeDescriptor   tdElem    = Element0Type;

            for (int i = result.Length - 1; i >= 0; i--)
            {
                innerType = innerType.MakeArrayType();
                result[i] = new TypeDescriptor()
                {
                    _sample = this._sample,
                    CILType = innerType,
                    HasIntrinsicTypeOverride = false,
                    TypeParams      = new object[] { TypeParams[i] },
                    Constraints     = this.Constraints == null ? null : new Range[] { Constraints[i] },
                    IsArtificial    = true,
                    IsUnconstrained = false,
                    Element0Type    = tdElem
                };
                tdElem = result[i];
            }
            return(result);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates a sample instance of the described type.
        /// </summary>
        /// <param name="options">creation options</param>
        public object GetSampleInstance(ETypeCreationOptions options = ETypeCreationOptions.AnyObject)
        {
            Contract.Requires(
                !(options.HasFlag(ETypeCreationOptions.AdditiveNeutral) && options.HasFlag(ETypeCreationOptions.MultiplicativeNeutral)) &&
                !(options.HasFlag(ETypeCreationOptions.AdditiveNeutral) && options.HasFlag(ETypeCreationOptions.NonZero)) &&
                !(options.HasFlag(ETypeCreationOptions.MultiplicativeNeutral) && options.HasFlag(ETypeCreationOptions.NonZero)));

            if (IsArtificial)
            {
                throw new InvalidOperationException("Cannot construct a sample instance from an artificial type");
            }

            if (options.HasFlag(ETypeCreationOptions.AdditiveNeutral) ||
                options.HasFlag(ETypeCreationOptions.MultiplicativeNeutral) ||
                options.HasFlag(ETypeCreationOptions.NonZero))
            {
                var atf = CILType.GetCustomOrInjectedAttribute <IAlgebraicTypeFactory>();
                return(atf.CreateInstance(options, _sample));
            }

            if (_sample != null)
            {
                return(_sample);
            }

            if (options.HasFlag(ETypeCreationOptions.ReturnNullIfUnavailable))
            {
                return(null);
            }

            if (!options.HasFlag(ETypeCreationOptions.ForceCreation) && (IsConstrained || !IsStatic))
            {
                throw new InvalidOperationException("Cannot construct sample instance from constrained incomplete or non-static type");
            }

            object inst = Activator.CreateInstance(CILType);

            return(inst);
        }
Ejemplo n.º 28
0
        internal static String CreateTypeString(CILType type, CILModule moduleBeingEmitted, Boolean appendGArgs)
        {
            if (moduleBeingEmitted == null)
            {
                moduleBeingEmitted = type.Module;
            }

            String typeString;

            if (type == null)
            {
                typeString = null;
            }
            else
            {
                // TODO probably should forbid whitespace characters to be within type and assembly names?
                var builder = new StringBuilder();
                CreateTypeString(type, moduleBeingEmitted, builder, appendGArgs, false);
                typeString = builder.ToString();
            }
            return(typeString);
        }
Ejemplo n.º 29
0
 internal CILMethodImpl(CILReflectionContextImpl ctx, Int32 anID, CILType declaringType, String name, MethodAttributes attrs, CallingConventions callingConventions)
     : this(
         ctx,
         anID,
         new LazyWithLock <ListProxy <CILCustomAttribute> >(() => ctx.CollectionsFactory.NewListProxy <CILCustomAttribute>()),
         new SettableValueForEnums <CallingConventions>(callingConventions),
         new SettableValueForEnums <MethodAttributes>(attrs),
         () => declaringType,
         () => ctx.CollectionsFactory.NewListProxy <CILParameter>(),
         () => new MethodILImpl(declaringType.Module),
         new SettableLazy <MethodImplAttributes>(() => MethodImplAttributes.IL),
         null,
         new SettableValueForClasses <String>(name),
         () => ctx.Cache.NewBlankParameter(ctx.Cache.ResolveMethodBaseID(anID), E_CIL.RETURN_PARAMETER_POSITION, null, ParameterAttributes.None, declaringType.Module.AssociatedMSCorLibModule.GetTypeByName(Consts.VOID)),
         () => ctx.CollectionsFactory.NewListProxy <CILTypeBase>(),
         () => null,
         () => ctx.CollectionsFactory.NewListProxy <CILMethod>(),
         null,
         null,
         null,
         true)
 {
 }
Ejemplo n.º 30
0
 public string VisitCILType(CILType type, TypeQualifiers quals)
 {
     return(string.Empty);
 }
        public override bool VisitClassDecl(Class @class)
        {
            // FIXME: Add a better way to hook the event
            if (!isHooked)
            {
                Driver.Generator.OnUnitGenerated += OnUnitGenerated;
                isHooked = true;
            }

            if (!VisitDeclaration(@class))
                return false;

            // We can't handle value types yet
            // The generated code assumes that a NativePtr is available
            if (@class.IsValueType)
                return false;

            foreach (var method in @class.Methods)
            {
                if (!IsInsertionOperator(method))
                    continue;

                // Create the ToString method
                var stringType = GetType("std::string");
                if (stringType == null)
                    stringType = new CILType(typeof(string));
                var toStringMethod = new Method()
                {
                    Name = "ToString",
                    Namespace = @class,
                    ReturnType = new QualifiedType(stringType),
                    IsSynthetized = true,
                    IsOverride = true,
                    IsProxy = true
                };

                @class.Methods.Add(toStringMethod);

                Driver.Diagnostics.Debug("Function converted to ToString: {0}::{1}",
                    @class.Name, method.Name);

                break;
            }

            var methodEqualsParam = new Parameter
            {
                Name = "object",
                QualifiedType = new QualifiedType(new CILType(typeof(Object))),
            };

            var methodEquals = new Method
            {
                Name = "Equals",
                Namespace = @class,
                ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
                Parameters = new List<Parameter> { methodEqualsParam },
                IsSynthetized = true,
                IsOverride = true,
                IsProxy = true
            };
            @class.Methods.Add(methodEquals);

            var methodHashCode = new Method
            {
                Name = "GetHashCode",
                Namespace = @class,
                ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
                IsSynthetized = true,
                IsOverride = true,
                IsProxy = true
            };

            @class.Methods.Add(methodHashCode);
            return true;
        }