Example #1
0
 /// <summary>
 /// 更新设备类别
 /// </summary>
 /// <param name="obj"></param>
 protected void Update(TB_EquipmentType obj)
 {
     TypeInstance.Update(f => f.id == obj.id, act => {
         act.Code      = obj.Code;
         act.Name      = obj.Name;
         act.Image     = obj.Image;
         act.IsVehicle = obj.IsVehicle;
     });
 }
Example #2
0
        public void CreateInstanceWithArguments()
        {
            Dictionary <string, string> gg = new Dictionary <string, string>();

            gg.Add("test", "glx");

            ITestParameter fx = new TypeInstance().CreateInstance <ITestParameter>("Tests.Foo.TestParameter,c:\\Tests.Foo.dll", gg);

            Assert.True(fx != null);
            Assert.True(fx.FF != null);
            Assert.True(fx.FF.Keys.FirstOrDefault() == "test");
            fx.DoTheFoo();
        }
Example #3
0
 /// <summary>
 /// Recherche parmi un type saisi dans la fenetre de détail d'un port la liste des types
 /// qui doivent être insérés dans la couche modèle
 /// </summary>
 /// <param name="language">The language.</param>
 /// <param name="name">The name.</param>
 /// <returns></returns>
 public static IList <string> GetModelNamesFromClrType(Language language, string name)
 {
     if (ParseType.CanParse(language, name))
     {
         ParseType    parseType    = new ParseType(language, name);
         TypeInstance typeInstance = parseType.TypeInstance;
         if (typeInstance.TypeKind == TypeKind.Type)
         {
             return(GetModelsNameRecursive(language, typeInstance));
         }
     }
     return(null);
 }
Example #4
0
        private void ShowEdit()
        {
            var t = TypeInstance.Find(f => f.id == ParseInt(Utility.Decrypt(hidID.Value)));

            if (null != t)
            {
                txtCode.Value           = t.Code;
                txtName.Value           = t.Name;
                imgImage.Src            = t.Image;
                hidImage.Value          = t.Image;
                cbNormalVehicle.Checked = t.IsVehicle == true;
            }
            else
            {
                ShowNotification("./equipment_type.aspx", "Error: Cannot edit null object of <a>Equipment Type</a>.", false);
            }
        }
Example #5
0
        /// <summary>
        /// 更新设备状态码信息
        /// </summary>
        /// <param name="obj"></param>
        //protected void Update(TB_EquipmentStatusCode obj)
        //{
        //    CodeInstance.Update(f => f.id == obj.id, act => {
        //        act.Code = obj.Code;
        //        act.Name = obj.Name;
        //        act.Status = obj.Status;
        //    });
        //}
        /// <summary>
        /// 在下拉列表框里显示设备类别列表
        /// </summary>
        /// <param name="ddl"></param>
        protected void ShowEquipmentTypes(DropDownList ddl)
        {
            var types = TypeInstance.FindList(null).OrderBy(o => o.Name);

            ddl.Items.Clear();
            ddl.Items.Add(new ListItem()
            {
                Text = "Type:", Value = "", Selected = true
            });
            foreach (var type in types)
            {
                ddl.Items.Add(new ListItem()
                {
                    Text = type.Name, Value = type.id.ToString()
                });
            }
        }
Example #6
0
        public void Listen <H>(Int16 port,
                               Int32 RCV_BUFF      = 32 * 1024, Int32 SND_BUFF = 32 * 1024,
                               Int32 READ_TIME_OUT = 30, Int32 WRITE_TIME_OUT  = 30, Int32 RW_TIME_OUT = 30)
            where H : ByteToMessageDecoder, new()
        {
            var bootstrap = new ServerBootstrap();

            bootstrap
            .Group(threads)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, BackLog)
            .Option(ChannelOption.SoRcvbuf, RCV_BUFF)
            .Option(ChannelOption.SoSndbuf, SND_BUFF)
            .Option(ChannelOption.TcpNodelay, true)
            .Option(ChannelOption.SoReuseaddr, true)
            .Option(ChannelOption.SoKeepalive, true)
            .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default)

            .ChildAttribute(PLAYER_ID, new RefValue <Int64>(0))
            .ChildAttribute(IP_ADDR, new IPEndPoint(IPAddress.Any, 0))
            .ChildAttribute(OPEN_ID, "")
            .ChildAttribute(SERVER_ID, new RefValue <Int64>(0))
            .ChildAttribute(ACTIVE_TIME, new RefValue <Int64>(0))
            .ChildAttribute(SESSION_ID, new RefValue <Int64>(0))

            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                if (channel.RemoteAddress is IPEndPoint)
                {
                    channel.GetAttribute(IP_ADDR).Set(channel.RemoteAddress as IPEndPoint);
                }
                channel.GetAttribute(ACTIVE_TIME).Set(Platform.GetSeconds());
                Singleton <ConnManager> .Instance.AddNewConntion(channel);
                channel.GetAttribute(SESSION_ID).Get().Value = ConnectionSessionID++;

                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast("TimeOut", new IdleStateHandler(READ_TIME_OUT, WRITE_TIME_OUT, RW_TIME_OUT));
                pipeline.AddLast(TypeInstance <H> .New());

                LoggerProvider.Logger.Trace("NewSession SessionID:{0} IpAddr:{1}", channel.GetSessionID(), channel.GetIpAddr());
            }));

            Task.WaitAll(bootstrap.BindAsync(port));
            LoggerProvider.Logger.Trace("Listen Port:{0} Type:{1}", port);
            ports.Add(bootstrap);
        }
Example #7
0
        private void ShowTypes()
        {
            ddlType.Items.Clear();
            ddlType.Items.Add(new ListItem {
                Text = "Equipment Type:", Value = ""
            });
            var types = TypeInstance.FindList(f => f.Delete == false).OrderBy(o => o.Name);

            if (types.Count() > 0)
            {
                types = types.OrderBy(o => o.Name);
                foreach (var type in types)
                {
                    ddlType.Items.Add(new ListItem
                    {
                        Text  = type.Name,
                        Value = type.id.ToString()
                    });
                }
            }
        }
Example #8
0
        /// <summary>
        /// 显示设备类别列表
        /// </summary>
        private void ShowEquipmentTypes()
        {
            var totalRecords = 0;
            var pageIndex    = "" == hidPageIndex.Value ? 1 : int.Parse(hidPageIndex.Value);
            var list         = TypeInstance.FindPageList <TB_EquipmentType>(pageIndex, PageSize, out totalRecords,
                                                                            f => f.Delete == false, "Name");
            var totalPages = totalRecords / PageSize + (totalRecords % PageSize > 0 ? 1 : 0);

            string html = "";

            if (totalRecords < 1)
            {
                html = "<tr><td colspan=\"6\">No records, you can change condition and try again, or " +
                       " <a>Add</a> some new one.</td></tr>";
            }
            else
            {
                var cnt = (pageIndex - 1) * PageSize;
                foreach (var obj in list)
                {
                    cnt++;
                    var id = Utility.UrlEncode(Utility.Encrypt(obj.id.ToString()));
                    html += "<tr>" +
                            "<td style=\"width: 40px; text-align: center;\"><input type=\"checkbox\" id=\"cb_" + id + "\" /></td>" +
                            "<td style=\"width: 40px; text-align: center;\">" + cnt + "</td>" +
                            "<td><a href=\"./equipment_type.aspx?key=" + id + "\" >" + ("" == obj.Name ? "-" : obj.Name) + "</a></td>" +
                            "<td>" + obj.Code + "</td>" +
                            "<td>" + (obj.IsVehicle.Value ? "Yes" : "-") + "</td>" +
                            "<td><img alt=\"clipart\" style=\"width: 41px;\" class=\"img-rounded\" src=\"" + obj.Image + "\"/></td>" +
                            "<td></td>" +
                            "</tr>";
                }
            }
            tbodyBody.InnerHtml  = html;
            divPagging.InnerHtml = "";
            if (totalRecords > 0)
            {
                ShowPaggings(pageIndex, totalPages, totalRecords, "./equipment_type.aspx", divPagging);
            }
        }
Example #9
0
        /// <summary>
        /// Called to load plugins
        /// </summary>
        /// <param name="bot"></param>
        public void Load(PalBot bot)
        {
            bot.On.GroupMessage   += (gm) => OnMessage(bot, gm.Clone());
            bot.On.PrivateMessage += (pm) => OnMessage(bot, pm.Clone());

            if (bot.Translations == null)
            {
                Plugins = typeof(IIPlugin)
                          .GetAllTypes()
                          .Where(t => Attribute.IsDefined(t, typeof(PluginCollection)))
                          .Select(t => new TypeInstance <PluginCollection>(t, t.GetCustomAttribute <PluginCollection>()))
                          .ToDictionary(t => t, t => PluginsFromCollection(bot, t));
                return;
            }

            var plugins = typeof(IIPlugin).GetAllTypes()
                          .Where(t => Attribute.IsDefined(t, typeof(PluginCollection)))
                          .Select(t => new TypeInstance <PluginCollection>(t, t.GetCustomAttribute <PluginCollection>()))
                          .ToArray();

            Plugins = plugins.Where(t => t.Value.TranslationKey == null)
                      .ToDictionary(t => t, t => PluginsFromCollection(bot, t));

            var other = plugins.Where(t => !Plugins.Keys.Contains(t)).ToArray();

            foreach (var collection in other)
            {
                var trans = bot.Translations[collection.Value.TranslationKey];

                foreach (var item in trans)
                {
                    var clone = new TypeInstance <PluginCollection>(collection.Type, collection.Value.Clone(item.Value));
                    clone.Language = item.Language;
                    Plugins.Add(clone, PluginsFromCollection(bot, clone, item.Language));
                }

                Plugins.Add(collection, PluginsFromCollection(bot, collection, null));
            }
        }
Example #10
0
        private void EditType()
        {
            var t = TypeInstance.Find(f => f.id == ParseInt(Utility.Decrypt(hidID.Value)));

            if (null != t)
            {
                BuildType(t);
                Update(t);

                // 保存历史记录
                SaveHistory(new TB_AccountHistory()
                {
                    ActionId = ActionInstance.Find(f => f.Name.Equals("EditEquipmentType")).id,
                    ObjectA  = "[id=" + t.id + "] " + t.Name + ", " + t.Code
                });

                ShowNotification("./equipment_type.aspx", "You changed the equipment type.");
            }
            else
            {
                ShowNotification("./equipment_type.aspx", "Error: paramenter error, cannot edit null object(equipment type).", false);
            }
        }
        /// <summary>
        /// Initial load of all questionnaire plugins
        /// </summary>
        /// <param name="bot"></param>
        public void Load(PalBot bot)
        {
            bot.On.GroupMessage   += (m) => OnMessage(bot, m);
            bot.On.PrivateMessage += (m) => OnMessage(bot, m);

            var ps = typeof(IIQuestionnaire).GetAllTypes()
                     .Where(t => Attribute.IsDefined(t, typeof(Questionnaire)))
                     .Select(t => new TypeInstance <Questionnaire>(t, t.GetCustomAttribute <Questionnaire>())).ToList();

            foreach (var plug in ps)
            {
                if (bot.Translations != null)
                {
                    foreach (var tr in bot.Translations[plug.Value.TranslationKey])
                    {
                        var c = new TypeInstance <Questionnaire>(plug.Type, plug.Value.Clone(tr.Value));
                        c.Language = tr.Language;
                        Plugs.Add(c);
                    }
                }

                Plugs.Add(plug);
            }
        }
Example #12
0
        /// <summary>
        /// Gets the type instance for the specified symbol.
        /// </summary>
        /// <param name="parentType">The user type from which this symbol comes from (examples: field type, template type...).</param>
        /// <param name="symbol">The original type.</param>
        /// <param name="bitLength">Number of bits used for this symbol.</param>
        internal virtual TypeInstance GetSymbolTypeInstance(UserType parentType, Symbol symbol, int bitLength = 0)
        {
            switch (symbol.Tag)
            {
            case CodeTypeTag.BuiltinType:
                if (bitLength == 1)
                {
                    return(new BasicTypeInstance(CodeNaming, typeof(bool)));
                }
                switch (symbol.BasicType)
                {
                case BasicType.Bit:
                case BasicType.Bool:
                    return(new BasicTypeInstance(CodeNaming, typeof(bool)));

                case BasicType.Char:
                case BasicType.WChar:
                case BasicType.Char16:
                case BasicType.Char32:
                    return(new BasicTypeInstance(CodeNaming, typeof(char)));

                case BasicType.BSTR:
                    return(new BasicTypeInstance(CodeNaming, typeof(string)));

                case BasicType.Void:
                case BasicType.NoType:
                    return(new BasicTypeInstance(CodeNaming, typeof(VoidType)));

                case BasicType.Float:
                    return(new BasicTypeInstance(CodeNaming, symbol.Size <= 4 ? typeof(float) : typeof(double)));

                case BasicType.Int:
                case BasicType.Long:
                    switch (symbol.Size)
                    {
                    case 0:
                        return(new BasicTypeInstance(CodeNaming, typeof(VoidType)));

                    case 1:
                        return(new BasicTypeInstance(CodeNaming, typeof(sbyte)));

                    case 2:
                        return(new BasicTypeInstance(CodeNaming, typeof(short)));

                    case 4:
                        return(new BasicTypeInstance(CodeNaming, typeof(int)));

                    case 8:
                        return(new BasicTypeInstance(CodeNaming, typeof(long)));

                    default:
                        throw new Exception($"Unexpected type length {symbol.Size}");
                    }

                case BasicType.UInt:
                case BasicType.ULong:
                    switch (symbol.Size)
                    {
                    case 0:
                        return(new BasicTypeInstance(CodeNaming, typeof(VoidType)));

                    case 1:
                        return(new BasicTypeInstance(CodeNaming, typeof(byte)));

                    case 2:
                        return(new BasicTypeInstance(CodeNaming, typeof(ushort)));

                    case 4:
                        return(new BasicTypeInstance(CodeNaming, typeof(uint)));

                    case 8:
                        return(new BasicTypeInstance(CodeNaming, typeof(ulong)));

                    default:
                        throw new Exception($"Unexpected type length {symbol.Size}");
                    }

                case BasicType.Hresult:
                    return(new BasicTypeInstance(CodeNaming, typeof(uint)));        // TODO: Create Hresult type

                default:
                    throw new Exception($"Unexpected basic type {symbol.BasicType}");
                }

            case CodeTypeTag.Pointer:
            {
                Symbol   pointerType = symbol.ElementType;
                UserType pointerUserType;

                // When exporting pointer from Global Modules, always export types as code pointer.
                if (parentType is GlobalsUserType && GetUserType(pointerType, out pointerUserType))
                {
                    return(new PointerTypeInstance(UserTypeInstance.Create(pointerUserType, this)));
                }

                TypeInstance innerType = GetSymbolTypeInstance(parentType, pointerType);

                if (innerType is TemplateArgumentTypeInstance)
                {
                    return(new PointerTypeInstance(innerType));
                }
                switch (pointerType.Tag)
                {
                case CodeTypeTag.BuiltinType:
                case CodeTypeTag.Enum:
                {
                    if ((innerType as BasicTypeInstance)?.BasicType == typeof(VoidType))
                    {
                        return(new BasicTypeInstance(CodeNaming, typeof(NakedPointer)));
                    }
                    return(new PointerTypeInstance(innerType));
                }

                case CodeTypeTag.Class:
                case CodeTypeTag.Structure:
                case CodeTypeTag.Union:
                    return(innerType);

                default:
                    return(new PointerTypeInstance(innerType));
                }
            }

            case CodeTypeTag.Enum:
            case CodeTypeTag.Class:
            case CodeTypeTag.Structure:
            case CodeTypeTag.Union:
            case CodeTypeTag.TemplateArgumentConstant:
            {
                // Try to apply transformation on the type
                UserTypeTransformation transformation = FindTransformation(symbol, parentType);

                if (transformation != null)
                {
                    return(new TransformationTypeInstance(CodeNaming, transformation));
                }

                // Try to find user type that represents current type
                UserType userType;

                if (GetUserType(symbol, out userType))
                {
                    TypeInstance         type         = UserTypeInstance.Create(userType, this);
                    TemplateTypeInstance genericsTree = type as TemplateTypeInstance;

                    if (genericsTree != null && !genericsTree.CanInstantiate)
                    {
                        return(new VariableTypeInstance(CodeNaming));
                    }
                    return(type);
                }

                // We were unable to find user type. If it is enum, use its basic type
                if (symbol.Tag == CodeTypeTag.Enum)
                {
                    return(new BasicTypeInstance(CodeNaming, EnumUserType.GetEnumBasicType(symbol)));
                }

                // Is it template argument constant?
                if (symbol.Tag == CodeTypeTag.TemplateArgumentConstant && symbol.UserType is TemplateArgumentConstantUserType constantArgument)
                {
                    return(new TemplateArgumentConstantTypeInstance(constantArgument));
                }

                // Fall-back to Variable
                return(new VariableTypeInstance(CodeNaming));
            }

            case CodeTypeTag.Array:
                return(new ArrayTypeInstance(GetSymbolTypeInstance(parentType, symbol.ElementType)));

            case CodeTypeTag.Function:
                return(new FunctionTypeInstance(CodeNaming));

            case CodeTypeTag.BaseClass:
            {
                symbol = symbol.Module.GetSymbol(symbol.Name);
                return(GetSymbolTypeInstance(parentType, symbol, bitLength));
            }

            default:
                throw new Exception("Unexpected type tag " + symbol.Tag);
            }
        }
Example #13
0
        /// <summary>
        /// Try to generate fields based on the Hungarian notation used in class fields.
        /// </summary>
        /// <param name="fixName">Function that generated unique field names with desire to keep existing name.</param>
        protected virtual IEnumerable <HungarianArrayUserTypeMember> GenerateHungarianNotationFields(Func <string, string> fixName)
        {
            // TODO: Add comments to this function and expand XML documentation comment
            const string CounterPrefix = "m_c";
            const string PointerPrefix = "m_p";
            const string ArrayPrefix   = "m_rg";

            SymbolField[]                         fields          = Symbol.Fields;
            IEnumerable <SymbolField>             counterFields   = fields.Where(r => r.Name.StartsWith(CounterPrefix));
            Dictionary <SymbolField, SymbolField> userTypesArrays = new Dictionary <SymbolField, SymbolField>();

            foreach (SymbolField counterField in counterFields)
            {
                if (counterField.Type.BasicType != BasicType.UInt &&
                    counterField.Type.BasicType != BasicType.Int &&
                    counterField.Type.BasicType != BasicType.Long &&
                    counterField.Type.BasicType != BasicType.ULong)
                {
                    continue;
                }

                if (counterField.Type.Tag == CodeTypeTag.Enum)
                {
                    continue;
                }

                string counterNameSurfix = counterField.Name.Substring(CounterPrefix.Length);

                if (string.IsNullOrEmpty(counterNameSurfix))
                {
                    continue;
                }

                foreach (SymbolField pointerField in fields.Where(r => (r.Name.StartsWith(PointerPrefix) || r.Name.StartsWith(ArrayPrefix)) && r.Name.EndsWith(counterNameSurfix)))
                {
                    if ((counterField.IsStatic) != (pointerField.IsStatic))
                    {
                        continue;
                    }

                    if (pointerField.Type.Tag != CodeTypeTag.Pointer)
                    {
                        continue;
                    }

                    if (userTypesArrays.ContainsKey(pointerField))
                    {
                        if (userTypesArrays[pointerField].Name.Length > counterField.Name.Length)
                        {
                            continue;
                        }
                    }

                    userTypesArrays[pointerField] = counterField;
                }
            }

            foreach (var userTypeArray in userTypesArrays)
            {
                SymbolField  pointerField = userTypeArray.Key;
                SymbolField  counterField = userTypeArray.Value;
                TypeInstance fieldType    = Factory.GetSymbolTypeInstance(this, pointerField.Type);

                if (fieldType is ArrayTypeInstance)
                {
                    continue;
                }

                if (fieldType is PointerTypeInstance fieldTypeCodePointer)
                {
                    fieldType = fieldTypeCodePointer.ElementType;
                }

                yield return(new HungarianArrayUserTypeMember()
                {
                    AccessLevel = AccessLevel.Public,
                    Name = fixName(CodeNaming.FixUserNaming(pointerField.Name + "Array")),
                    Type = new ArrayTypeInstance(fieldType),
                    UserType = this,
                    PointerFieldName = pointerField.Name,
                    CounterFieldName = counterField.Name,
                });
            }
        }
Example #14
0
        /// <summary>
        /// Function that should evaluate <see cref="BaseClass"/> and <see cref="BaseClassOffset"/> properties.
        /// </summary>
        protected virtual Tuple <TypeInstance, int> GetBaseClass(Symbol symbol)
        {
            Symbol[]     baseClasses     = symbol.BaseClasses;
            TypeInstance baseClass       = null;
            int          baseClassOffset = 0;

            // Check if we are exporting only static fields
            if (ExportOnlyStaticFields)
            {
                baseClass = new StaticClassTypeInstance(CodeNaming);
                return(Tuple.Create(baseClass, baseClassOffset));
            }

            // Check if it is inheriting one of its own template arguments
            foreach (Symbol baseClassSymbol in baseClasses)
            {
                TypeInstance typeInstance = Factory.GetSymbolTypeInstance(this, baseClassSymbol);

                if (typeInstance is TemplateArgumentTypeInstance)
                {
                    baseClass = new MultiClassInheritanceTypeInstance(CodeNaming);
                    return(Tuple.Create(baseClass, baseClassOffset));
                }
            }

            // Check if it is recursively inheriting itself
            foreach (Symbol baseClassSymbol in baseClasses)
            {
                UserType userType;

                if (Factory.GetUserType(baseClassSymbol, out userType))
                {
                    if (userType != this && userType is SpecializedTemplateUserType specialization)
                    {
                        userType = specialization.TemplateType;
                    }
                    if (userType == this || (this is SpecializedTemplateUserType specThis && specThis.TemplateType == userType))
                    {
                        baseClass = new MultiClassInheritanceTypeInstance(CodeNaming);
                        return(Tuple.Create(baseClass, baseClassOffset));
                    }
                }
            }

            // Check if it is multi class inheritance
            if (baseClasses.Length > 1)
            {
                int emptyTypes = baseClasses.Count(t => t.IsEmpty);

                if (emptyTypes == baseClasses.Length - 1)
                {
                    UserType userType;
                    Symbol   baseClassSymbol = baseClasses.First(t => !t.IsEmpty);

                    if (!baseClassSymbol.IsVirtualInheritance && Factory.GetUserType(baseClassSymbol, out userType) && !(Factory.GetSymbolTypeInstance(this, baseClassSymbol) is TemplateArgumentTypeInstance))
                    {
                        baseClassOffset = baseClassSymbol.Offset;
                        baseClass       = new SingleClassInheritanceWithInterfacesTypeInstance(userType, Factory);
                        return(Tuple.Create(baseClass, baseClassOffset));
                    }
                }

                baseClass = new MultiClassInheritanceTypeInstance(CodeNaming);
                return(Tuple.Create(baseClass, baseClassOffset));
            }

            // Single class inheritance
            if (baseClasses.Length == 1)
            {
                // Check if base class type is virtual inheritance
                Symbol baseClassType = baseClasses[0];

                if (baseClassType.IsVirtualInheritance)
                {
                    baseClass = new MultiClassInheritanceTypeInstance(CodeNaming);
                    return(Tuple.Create(baseClass, baseClassOffset));
                }

                // Check if base class type should be transformed
                UserTypeTransformation transformation = Factory.FindTransformation(baseClassType, this);

                if (transformation != null)
                {
                    baseClass = new TransformationTypeInstance(CodeNaming, transformation);
                    return(Tuple.Create(baseClass, baseClassOffset));
                }

                // Try to find base class user type
                UserType baseUserType;

                if (Factory.GetUserType(baseClassType, out baseUserType))
                {
                    baseClass = UserTypeInstance.Create(baseUserType, Factory);
                    TemplateTypeInstance genericsInstance = baseClass as TemplateTypeInstance;

                    if (genericsInstance != null && !genericsInstance.CanInstantiate)
                    {
                        // We cannot instantiate the base class, so we must use UserType as the base class.
                        baseClass = new VariableTypeInstance(CodeNaming, false);
                        return(Tuple.Create(baseClass, baseClassOffset));
                    }

                    baseClassOffset = baseClassType.Offset;
                    return(Tuple.Create(baseClass, baseClassOffset));
                }

                // We weren't able to find base class user type. Continue the search.
                return(GetBaseClass(baseClassType));
            }

            // Class doesn't inherit any type
            baseClass = new VariableTypeInstance(CodeNaming, false);
            return(Tuple.Create(baseClass, baseClassOffset));
        }
Example #15
0
        /// <summary>
        /// Function that should evaluate <see cref="Members"/> property.
        /// </summary>
        protected virtual IEnumerable <UserTypeMember> GetMembers()
        {
            // Prepare naming "deduplication" and error fixing
            HashSet <string>      usedNames = new HashSet <string>();
            Func <string, string> fixName   = (string nameBase) =>
            {
                string name = nameBase;

                for (int i = 0; usedNames.Contains(name); i++)
                {
                    if (i > 0)
                    {
                        name = $"{nameBase}_{i}";
                    }
                    else
                    {
                        name = $"{nameBase}_";
                    }
                }
                usedNames.Add(name);
                return(name);
            };

            usedNames.Add(ConstructorName);
            foreach (UserType innerType in InnerTypes)
            {
                usedNames.Add(innerType.ConstructorName);
            }

            // Add constants and data fields
            foreach (var field in Symbol.Fields)
            {
                if (field.IsStatic && !field.IsValidStatic)
                {
                    continue;
                }

                if (field.IsStatic && DontExportStaticFields)
                {
                    continue;
                }

                if (!field.IsStatic && ExportOnlyStaticFields)
                {
                    continue;
                }

                string fieldName = fixName(CodeNaming.FixUserNaming(field.Name));

                if (field.LocationType == LocationType.Constant)
                {
                    yield return new ConstantUserTypeMember()
                           {
                               AccessLevel = AccessLevel.Public,
                               Name        = fieldName,
                               Type        = Factory.GetSymbolTypeInstance(this, field.Type, field.BitSize),
                               Symbol      = field,
                               UserType    = this,
                           }
                }
                ;
                else
                {
                    yield return new DataFieldUserTypeMember()
                           {
                               AccessLevel = AccessLevel.Public,
                               Name        = fieldName,
                               Type        = Factory.GetSymbolTypeInstance(this, field.Type, field.BitSize),
                               Symbol      = field,
                               UserType    = this,
                           }
                };
            }

            // Hungarian notation fields
            if (!ExportOnlyStaticFields)
            {
                foreach (UserTypeMember member in GenerateHungarianNotationFields(fixName))
                {
                    yield return(member);
                }
            }

            // Base class properties
            if (!ExportOnlyStaticFields && (BaseClass is MultiClassInheritanceTypeInstance || BaseClass is SingleClassInheritanceWithInterfacesTypeInstance))
            {
                Symbol[] baseClasses = Symbol.BaseClasses;
                Symbol[] baseClassesForProperties = BaseClass is SingleClassInheritanceWithInterfacesTypeInstance?baseClasses.Where(b => b.IsEmpty).ToArray() : baseClasses;

                List <Symbol> baseClassesSorted = baseClasses.OrderBy(s => s.Offset).ThenBy(s => s.Name).ToList();

                foreach (Symbol baseClass in baseClassesForProperties)
                {
                    // Generate simplified base class name
                    TypeInstance  type          = Factory.GetSymbolTypeInstance(this, baseClass);
                    string        baseClassName = CodeNaming.FixUserNaming(type.GetTypeString(truncateNamespace: true));
                    StringBuilder sb            = new StringBuilder();
                    int           i             = baseClassName[0] == '@' ? 1 : 0;

                    for (; i < baseClassName.Length; i++)
                    {
                        switch (baseClassName[i])
                        {
                        case '_':
                        case '.':
                            if (i > 0 && baseClassName[i - 1] != '_')
                            {
                                sb.Append('_');
                            }
                            break;

                        default:
                            sb.Append(baseClassName[i]);
                            break;
                        }
                    }
                    while (sb.Length > 0 && sb[sb.Length - 1] == '_')
                    {
                        sb.Length--;
                    }
                    baseClassName = sb.ToString();

                    // Create property
                    string propertyName = fixName(baseClassesForProperties.Length > 1 ? $"BaseClass_{baseClassName}" : "BaseClass");

                    yield return(new BaseClassPropertyUserTypeMember()
                    {
                        AccessLevel = AccessLevel.Public,
                        Name = propertyName,
                        Type = type,
                        Symbol = baseClass,
                        UserType = this,
                        Index = baseClassesSorted.IndexOf(baseClass),
                    });
                }
            }
        }