Example #1
0
 public void LoadRecord(string path)
 {
     if (File.Exists(path))
     {
         try {
             record    = LitJson.JsonMapper.ToObject <TIDMap>(File.ReadAllText(path));
             this.path = path;
         }
         catch (Exception ex)
         {
             GLog.LogError("Exception while reading {0} :\n{1}", path, ex);
         }
     }
     else
     {
         this.path    = path;
         record       = new TIDMap();
         record.idMap = new Dictionary <string, int>();
     }
 }
Example #2
0
        public static GType CreateFromDesc(TypeDesc desc)
        {
            GType ret = null;

            if (desc.Tt == TypeDesc.TT.Class)
            {
                ret = new GTypeClass();
            }
            else if (desc.Tt == TypeDesc.TT.Struct)
            {
                ret = new GTypeStruct();
            }
            else if (desc.Tt == TypeDesc.TT.Enum)
            {
                ret = new GTypeEnum();
            }
            else if (desc.Tt == TypeDesc.TT.BitField)
            {
                ret = new GTypeBitField();
            }
            else
            {
                GLog.LogError("Type must be declared as 'Class' or 'Struct' or 'Enum' or 'BitField'. \n" + desc.Tt);
                return(null);
            }

            ret.Name            = desc.Name;
            ret.Namespace       = desc.Namespace;
            ret.CompileTo       = desc.CompileTo;
            ret.Gen_Head        = desc.Gen_Head;
            ret.Gen_Serialize   = desc.Gen_Serialize;
            ret.Gen_Deserialize = desc.Gen_Deserialize;

            if (ret.Parse(desc))
            {
                return(ret);
            }

            return(null);
        }
Example #3
0
        /// <summary>
        /// Load Types from C# Assembly
        /// </summary>
        public bool LoadFromAssembly(string fileName, BatchInfo batch = null, string[] namespaceFilter = null)
        {
            Assembly asm = Assembly.Load(File.ReadAllBytes(fileName));

            foreach (var desc in GCSAssembly_Convertor.Convert(asm, namespaceFilter))
            {
                GType tp = GType.CreateFromDesc(desc);
                if (tp == null)
                {
                    return(false);
                }

                if (mTypeMap.ContainsKey(tp.Name))
                {
                    GLog.LogError("GTypeManager.Load: Multi definition of " + tp.Name);
                    return(false);
                }
                tp.batch = batch;
                mTypeMap.Add(tp.Name, tp);
                mTypeList.Add(tp);
            }
            return(true);
        }
Example #4
0
        public bool PreBuild()
        {
            if (prebuilded)
            {
                return(true);
            }
            prebuilded = true;

            if (!string.IsNullOrEmpty(Parent))
            {
                GLog.Log("Build:  " + this.ID);

                GObject parentObj = GDataManager.Instance.GetObj(Parent);
                if (parentObj == null)
                {
                    GLog.LogError("Parent '{0}' can't be found.{1}", Parent, debugInfo);
                    return(false);
                }

                // 0. parent prebuild
                parentObj.PreBuild();

                // 1. Inherite Array、Map ...
                var e = inst_object.GetEnumerator();
                while (e.MoveNext())
                {
                    if (e.Current.Value.inheritParent)
                    {
                        GLog.Log("inheriteParent true");
                        GData parentData = parentObj.GetField(e.Current.Key);
                        e.Current.Value.InheriteParent(parentData);
                    }
                }
            }

            return(true);
        }
Example #5
0
        public bool InheritParentFields()
        {
            if (inherited)
            {
                return(true);
            }

            if (this.Parent == null)
            {
                return(true);
            }

            // check
            GTypeClass parentType = (GTypeClass)GTypeManager.Instance.GetType(this.Parent);

            if (parentType == null || !parentType.IsClass())
            {
                GLog.LogError("'" + this.Parent + "' is not defined or is not a 'Class'");
                return(false);
            }

            parentType.InheritParentFields();

            // inherit category
            this.Category = parentType.Category;

            // inherit fiedls
            this.mInheritedFields = new GStructField[parentType.FieldCount];
            for (int i = 0; i < this.mInheritedFields.Length; ++i)
            {
                // TODO: copy or ref ? //
                this.mInheritedFields[i] = parentType.GetField(i);
            }
            inherited = true;
            return(true);
        }
Example #6
0
 public override bool WriteJson(ref JsonData jsonData, GData data)
 {
     GLog.LogError("GTypeMap WriteJson is not implemented.");
     return(false);
 }
Example #7
0
        // string cache
        // List<string> mStrings = new List<string>();


        public bool LoadJson(string jsonStr, string dir, string fileName, string patchName)
        {
            GLog.Log("Load json: " + Path.Combine(dir, fileName));
            LitJson.JsonData jsonData;
            try {
                jsonData = LitJson.JsonMapper.ToObject(jsonStr);
            }
            catch (LitJson.JsonException ex) {
                GLog.LogError("Exception catched while parsing : " + Path.Combine(dir, fileName) + "\n" + ex.Message);
                return(false);
            }

            for (int i = 0; i < jsonData.Count; ++i)
            {
                if (!jsonData[i].Keys.Contains("Type"))
                {
                    GLog.LogError("GDataManager.LoadJson: " + jsonData.ToJson() + " does not contain 'Type' definition");
                    return(false);
                }
                string type = (string)jsonData[i]["Type"];

                // check is class
                GTypeClass tp = GTypeManager.Instance.GetType(type) as GTypeClass;
                if (tp == null)
                {
                    GLog.LogError("LoadJson. '" + type + "' is not defined or is not class\n");
                    return(false);
                }

                DataDebugInfo info = new DataDebugInfo();
                info.fileName = Path.Combine(dir, fileName);
                GObject obj = tp.ReadData(jsonData[i], false, null, info) as GObject;
                if (obj == null)
                {
                    continue;
                }

                obj.DirPath  = dir;
                obj.FileName = Path.GetFileNameWithoutExtension(fileName);
                obj.patch    = patchName;


                GObject oldObj;
                if (mIDMap.TryGetValue(obj.ID, out oldObj))
                {
                    if (oldObj.patch.Equals((obj.patch)))
                    {
                        GLog.LogError("GDataManager.LoadJson: Multi definition of " + oldObj.ID);
                        return(false);
                    }
                    else
                    {
                        mIDMap[obj.ID] = obj;
                        List <GObject> typeObjs;
                        if (!mTypeMap.TryGetValue(type, out typeObjs))
                        {
                            typeObjs = new List <GObject>();
                            mTypeMap.Add(type, typeObjs);
                        }
                        typeObjs.Remove(oldObj);
                        typeObjs.Add(obj);
                    }
                }
                else
                {
                    mIDMap[obj.ID] = obj;

                    List <GObject> typeObjs;
                    if (!mTypeMap.TryGetValue(type, out typeObjs))
                    {
                        typeObjs = new List <GObject>();
                        mTypeMap.Add(type, typeObjs);
                    }
                    typeObjs.Add(obj);
                }
            }

            return(true);
        }
Example #8
0
 public virtual bool GenCode_FlatBuffer(CodeGenerator gen)
 {
     GLog.LogError("Basic GType!");
     return(false);
 }
Example #9
0
 public virtual bool GenCode_CS_Impl(CodeGenerator gen)
 {
     GLog.LogError("Basic GType!");
     return(false);
 }
Example #10
0
        public override GData ReadData(JsonData jsonData, bool inherit, GStructField field, DataDebugInfo ownerDebugInfo)
        {
            GData data = new GData(GType.Array);

            data.inheritParent = inherit;
            data.debugInfo     = ownerDebugInfo;

            data.fieldInfo = field;
            data.Array     = new List <GData>();

            GType itemType = GTypeManager.Instance.GetType(field.SubTypes[0]);

            // 完整数组 //
            if (jsonData.IsArray)
            {
                for (int iSub = 0; iSub < jsonData.Count; ++iSub)
                {
                    GData arrayItem = itemType.ReadData(jsonData[iSub], false, field, data.debugInfo);
                    if (arrayItem == null)
                    {
                        return(null);
                    }
                    data.Array.Add(arrayItem);
                }
                return(data);
            }
            // 指定index的数组 //
            else if (jsonData.IsObject)
            {
                data.isKVArray = true;

                var keys      = jsonData.Keys;
                int lastIndex = -1;
                var e         = keys.GetEnumerator();
                while (e.MoveNext())
                {
                    int index = 0;
                    if (!int.TryParse(e.Current, out index))
                    {
                        GLog.LogError("Array index must be integer. '{0}' {1}", e.Current, data.debugInfo);
                        return(null);
                    }

                    if (index <= lastIndex)
                    {
                        GLog.LogError("Array index must be incremental. '{0}' {1}", e.Current, data.debugInfo);
                        return(null);
                    }

                    while (lastIndex++ < index - 1)
                    {
                        data.Array.Add(null);
                    }

                    GData arrayItem = itemType.ReadData(jsonData[e.Current], false, field, data.debugInfo);
                    if (arrayItem == null)
                    {
                        return(null);
                    }
                    data.Array.Add(arrayItem);
                }

                return(data);
            }
            else
            {
                GLog.LogError("Field '{0}' expect array data.{1}", field.Name, data.debugInfo);
                return(null);
            }
        }
Example #11
0
        public virtual GData ReadData(string strData, GStructField field, DataDebugInfo ownerDebugInfo)
        {
            GData data = new GData(Name);

            data.debugInfo = ownerDebugInfo;

            if (Name.Equals(GType.Bool))
            {
                bool ret;
                if (bool.TryParse(strData, out ret))
                {
                    data.Bool = bool.Parse(strData);
                }
                else
                {
                    GLog.LogError("Parse Bool failed: {0}", strData);
                    return(null);
                }
            }
            else if (Name.Equals(GType.Byte) ||
                     Name.Equals(GType.Short) ||
                     Name.Equals(GType.Int))
            {
                int intVal = 0;
                int ret;
                if (int.TryParse(strData, out ret))
                {
                    intVal = ret;
                }
                else
                {
                    string[] splits = strData.Split('.');
                    if (splits.Length >= 2)
                    {
                        GType tp = GTypeManager.Instance.GetType(splits[0]);
                        if (tp.IsEnum())
                        {
                            GTypeEnum enumTp = tp as GTypeEnum;
                            int       val    = (int)enumTp.GetVal(splits[1]);
                            if (val != -1)
                            {
                                intVal = val;
                            }
                            else
                            {
                                GLog.LogError("Can't parse {0} while assigning to int field {1}{2}", strData, field.Name, data.debugInfo);
                            }
                        }
                        else
                        {
                            GLog.LogError("Can't parse {0} while assigning to int field {1}{2}", strData, field.Name, data.debugInfo);
                        }
                    }
                    else
                    {
                        GLog.LogError("Can't parse {0} while assigning to int field {1}{2}", strData, field.Name, data.debugInfo);
                    }
                }

                if (Name.Equals(GType.Int))
                {
                    data.Int = intVal;
                }
                else if (Name.Equals(GType.Short))
                {
                    data.Short = (short)intVal;
                    if (data.Short != intVal)
                    {
                        GLog.LogError("{0} is cast to short {1}", intVal, data.Short);
                    }
                }
                else if (Name.Equals(GType.Byte))
                {
                    data.Byte = (byte)intVal;
                    if (data.Byte != intVal)
                    {
                        GLog.LogError("{0} is cast to byte {1}", intVal, data.Byte);
                    }
                }
            }
            else if (Name.Equals(GType.Float))
            {
                float ret;
                if (float.TryParse(strData, out ret))
                {
                    data.Float = ret;
                }
                else
                {
                    GLog.LogError("(" + strData + ") is not a number" + data.debugInfo);
                    return(null);
                }
            }
            else if (Name.Equals(GType.String))
            {
                data.String = strData;
            }
            else if (Name.Equals(GType.TID))
            {
                if (string.IsNullOrEmpty(field.Category))
                {
                    data.TID = strData;
                }
                else
                {
                    data.TID = field.Category + "." + strData;
                }
            }

            return(data);
        }
Example #12
0
        public virtual GData ReadData(JsonData jsonData, bool inherit, GStructField field, DataDebugInfo ownerDebugInfo)
        {
            GData data = new GData(Name);

            data.inheritParent = inherit;
            data.debugInfo     = ownerDebugInfo;

            if (Name.Equals(GType.Bool))
            {
                data.Bool = (bool)jsonData;
            }
            else if (Name.Equals(GType.Byte) ||
                     Name.Equals(GType.Short) ||
                     Name.Equals(GType.Int))
            {
                int intVal = 0;
                if (jsonData.IsInt)
                {
                    intVal = (int)jsonData;
                }
                else if (jsonData.IsDouble)
                {
                    float tmp = (float)jsonData;
                    intVal = (int)tmp;
                    if (tmp > intVal)
                    {
                        GLog.LogError(jsonData + " is converted to int!" + data.debugInfo);
                    }
                }
                else if (jsonData.IsString)
                {
                    string[] splits = ((string)jsonData).Split('.');
                    if (splits.Length >= 2)
                    {
                        GType tp = GTypeManager.Instance.GetType(splits[0]);
                        if (tp.IsEnum())
                        {
                            GTypeEnum enumTp = tp as GTypeEnum;
                            int       val    = (int)enumTp.GetVal(splits[1]);
                            if (val != -1)
                            {
                                intVal = val;
                            }
                            else
                            {
                                GLog.LogError("Can't parse {0} while assigning to int field {1}{2}", (string)jsonData, field.Name, data.debugInfo);
                            }
                        }
                        else
                        {
                            GLog.LogError("Can't parse {0} while assigning to int field {1}{2}", (string)jsonData, field.Name, data.debugInfo);
                        }
                    }
                    else
                    {
                        GLog.LogError("Can't parse string \"{0}\" to enum while assigning to int field {1}{2}", (string)jsonData, field.Name, data.debugInfo);
                    }
                }
                else
                {
                    GLog.LogError("(" + jsonData.GetJsonType() + ") is not int" + data.debugInfo);
                }

                if (Name.Equals(GType.Int))
                {
                    data.Int = intVal;
                }
                else if (Name.Equals(GType.Short))
                {
                    data.Short = (short)intVal;
                    if (data.Short != intVal)
                    {
                        GLog.LogError("{0} is cast to short {1}", intVal, data.Short);
                    }
                }
                else if (Name.Equals(GType.Byte))
                {
                    data.Byte = (byte)intVal;
                    if (data.Byte != intVal)
                    {
                        GLog.LogError("{0} is cast to byte {1}", intVal, data.Byte);
                    }
                }
            }
            else if (Name.Equals(GType.Float))
            {
                if (jsonData.IsInt)
                {
                    data.Float = (int)jsonData;
                }
                else if (jsonData.IsDouble)
                {
                    data.Float = (float)jsonData;
                }
                else
                {
                    GLog.LogError("(" + jsonData.GetJsonType() + ") is not a number" + data.debugInfo);
                }
            }
            else if (Name.Equals(GType.String))
            {
                data.String = (string)jsonData;
            }
            else if (Name.Equals(GType.TID))
            {
                if (string.IsNullOrEmpty(field.Category))
                {
                    data.TID = (string)jsonData;
                }
                else
                {
                    // todo: ����Ƿ��Ѿ�����Ϊ Catagory.Name ��ʽ
                    data.TID = field.Category + "." + (string)jsonData;
                }
            }

            return(data);
        }
Example #13
0
        public override GData ReadData(JsonData jsonData, bool inherit, GStructField field, DataDebugInfo ownerDebugInfo)
        {
            GObject obj = new GObject(Name);

            obj.inheritParent = inherit;
            obj.debugInfo     = ownerDebugInfo;

            // TODO: check errors
            // todo: 检查是否已经定义为 Category.Name 格式
            if (string.IsNullOrEmpty(this.Category))
            {
                obj.ID = (string)jsonData["ID"];
            }
            else
            {
                obj.ID = this.Category + "." + (string)jsonData["ID"];
            }

            obj.debugInfo.ownerTID = obj.ID;

            if (jsonData.Keys.Contains("RuntimeLink"))
            {
                obj.isRuntimeLink = (bool)jsonData["RuntimeLink"];
            }

            // todo: 检查是否已经定义为 Category.Name 格式
            if (jsonData.Keys.Contains("Parent"))
            {
                if (string.IsNullOrEmpty(this.Category))
                {
                    obj.Parent = (string)jsonData["Parent"];
                }
                else
                {
                    obj.Parent = this.Category + "." + (string)jsonData["Parent"];
                }
            }

            if (jsonData.Keys.Contains("Singleton"))
            {
                try {
                    obj.singletonType = (GObject.SingletonType)Enum.Parse(typeof(GObject.SingletonType), (string)jsonData["Singleton"]);
                }
                catch (Exception ex) {
                    GLog.LogError("Unrecognized SingletonType '{0}' {1}", (string)jsonData["Singleton"], obj.debugInfo);
                }
            }

            if (jsonData.Keys.Contains("CrcMask"))
            {
                obj.CrcMask = (uint)(int)jsonData["CrcMask"];
            }

            obj.crc = Crc32.Calc(obj.ID, obj.CrcMask);

            if (!ReadData_Impl(obj, jsonData, field))
            {
                return(null);
            }
            return(obj);
        }
Example #14
0
        public override bool ParseJson(JsonData data)
        {
            this.isTemplateClass = true;
            this.Gen_Head        = true;
            this.Gen_Serialize   = false;
            this.Gen_Deserialize = true;

            JsonData classHeader;
            JsonData classData = data["Class"];

            if (classData.IsObject)
            {
                classHeader = classData;
                // name
                if (!classHeader.Keys.Contains("Name"))
                {
                    GLog.LogError(data.ToJson() + "\n 'Name' is required'");
                    return(false);
                }
                this.Name = (string)classHeader["Name"];
            }
            else
            {
                classHeader = data;
                this.Name   = (string)classData;
            }


            // parent
            if (classHeader.Keys.Contains("Parent"))
            {
                this.Parent = (string)classHeader["Parent"];
            }
            else
            {
                this.builtinParent = "BaseTemplate";
            }

            // Category
            if (classHeader.Keys.Contains("Category"))
            {
                if (!string.IsNullOrEmpty(this.Parent))
                {
                    GLog.LogError("Category can be declared only in root class. Error in " + this.Name + "\nGType.Parse: \n" + data.ToJson());
                }
                else
                {
                    this.Category = (string)classHeader["Category"];
                }
            }

            // Binding class
            if (classHeader.Keys.Contains("BindingClass"))
            {
                this.BindingClass = (string)classHeader["BindingClass"];
            }
            // Binding class macro
            if (classHeader.Keys.Contains("BindingClassMacro"))
            {
                this.BindingClassMacro = (string)classHeader["BindingClassMacro"];
            }

            // Multiton

/*            if (classHeader.Keys.Contains("Multiton"))
 *              this.Multiton = (bool)classHeader["Multiton"];
 *          else
 *              this.Multiton = false;*/

            // type id
            // disable CrcMask
            // if (classHeader.Keys.Contains("CrcMask"))
            //    this.CrcMask = (uint)(int)classHeader["CrcMask"];
            this.crc = Crc32.Calc(this.Name, this.CrcMask);

            // TODO: check repeated typeid, in a Mgr.CheckErrors() method

            return(ParseJsonFields(data));
        }
Example #15
0
        /// <summary>
        /// Replaces the macro.
        /// </summary>
        /// <returns>new string</returns>
        public string ReplaceMacro(string str, DataDebugInfo debugInfo)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            int    index      = 0;
            int    numOfMacro = 0;
            string newStr     = "";

            while (index < str.Length)
            {
                int leftIndex = str.IndexOf("##", index, StringComparison.Ordinal);
                if (leftIndex < 0)
                {
                    if (index > 0)
                    {
                        newStr += str.Substring(index);
                    }
                    break;
                }

                int rightIndex = str.IndexOf("##", leftIndex + 2, StringComparison.Ordinal);
                if (rightIndex < 0)
                {
                    GLog.LogError("Can't parse macro in string : " + str + debugInfo);
                    return(str);
                }

                numOfMacro += 1;
                newStr     += str.Substring(index, leftIndex - index);

                string macroName = str.Substring(leftIndex + 2, rightIndex - leftIndex - 2);
                // todo: 目前仅支持ID宏 其他的后续看情况添加 //
                if (macroName.Equals("ID"))
                {
                    if (this.ID.IndexOf('.') < 0)
                    {
                        newStr += this.ID;
                    }
                    else
                    {
                        string[] splits = this.ID.Split('.');
                        newStr += splits[1];
                    }
                }
                else
                {
                    GLog.LogError("Unknown macro '{0}' in string '{1}'{2}", macroName, str, debugInfo);
                    return(str);
                }

                index = rightIndex + 2;
            }

            if (numOfMacro > 0)
            {
                GLog.Log("ReplaceMacro '{0}' to '{1}' {2}", str, newStr, debugInfo);
            }
            else
            {
                newStr = str;
            }
            return(newStr);
        }
Example #16
0
 public virtual bool WriteDefault(BinaryWriter writer, JsonData defaultVal = null)
 {
     if (Name.Equals(GType.Bool))
     {
         if (defaultVal == null)
         {
             writer.Write(false);
         }
         else if (defaultVal.IsBoolean)
         {
             writer.Write((bool)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.Byte))
     {
         if (defaultVal == null)
         {
             writer.Write((byte)0);
         }
         else if (defaultVal.IsInt)
         {
             writer.Write((byte)defaultVal);
         }
         else if (defaultVal.IsDouble)
         {
             writer.Write((byte)(float)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.Short))
     {
         if (defaultVal == null)
         {
             writer.Write((short)0);
         }
         else if (defaultVal.IsInt)
         {
             writer.Write((short)defaultVal);
         }
         else if (defaultVal.IsDouble)
         {
             writer.Write((short)(float)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.Int))
     {
         if (defaultVal == null)
         {
             writer.Write(0);
         }
         else if (defaultVal.IsInt)
         {
             writer.Write((int)defaultVal);
         }
         else if (defaultVal.IsDouble)
         {
             writer.Write((int)(float)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.Float))
     {
         if (defaultVal == null)
         {
             writer.Write(0.0f);
         }
         else if (defaultVal.IsInt)
         {
             writer.Write((float)defaultVal);
         }
         else if (defaultVal.IsDouble)
         {
             writer.Write((float)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.String))
     {
         if (defaultVal == null)
         {
             writer.Write(0);
         }
         else if (defaultVal.IsString)
         {
             SerializeUtil.WriteString(writer, (string)defaultVal);
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     else if (Name.Equals(GType.TID))
     {
         if (defaultVal == null)
         {
             writer.Write(0);
         }
         else if (defaultVal.IsString)
         {
             writer.Write(GTIDGenerator.Instance.GetID((string)defaultVal));
         }
         else
         {
             GLog.LogError("Default value is invalid. Skipped. Type: " + this.Name + "  default: " + defaultVal);
         }
         return(true);
     }
     return(false);
 }
Example #17
0
        public bool Parse(JsonData jsonData)
        {
            foreach (var key in jsonData.Keys)
            {
                // 兼容旧版本 //
                if (key.Equals("Field"))
                {
                    this.Name = (string)jsonData["Field"];
                }
                else if (key.Equals("Array"))
                {
                    this.Name = (string)jsonData["Array"];
                    this.Type = GType.Array;
                }
                // 兼容旧版本 //
                else if (key.Equals("Type"))
                {
                    if (jsonData["Type"].IsString)
                    {
                        if (this.Type == null)
                        {
                            this.Type = (string)jsonData["Type"];
                        }
                        else
                        {
                            this.SubTypes    = new string[1];
                            this.SubTypes[0] = (string)jsonData["Type"];
                        }
                    }
                    else
                    {
                        GLog.LogError("'Type' must be string. " + jsonData["Type"]);
                        return(false);
                    }
                }
                else if (key.Equals("Category"))
                {
                    this.Category = (string)jsonData["Category"];
                }
                else if (key.Equals("Default"))
                {
                    this.Default = jsonData["Default"];
                }
                else if (key.Equals("Tags"))
                {
                    this.Tags = ((string)jsonData["Tags"]).Split(';');
                }
                else if (key.Equals("Limit"))
                {
                    this.Limit = (string)jsonData["Limit"];
                }
                else if (key.Equals("Desc"))
                {
                    // todo:   desc
                }
                else
                {
                    // new way to define type-name
                    if (key.StartsWith("Array<") && key.EndsWith(">"))
                    {
                        this.Type = GType.Array;
                        int    preLength = 6; // "Array<".Length
                        string innerStr  = key.Substring(preLength, key.Length - preLength - 1);
                        this.SubTypes    = new string[1];
                        this.SubTypes[0] = innerStr.Trim();
                    }
                    else if (key.Contains("Map<") && key.Contains(">"))
                    {
                        this.Type = GType.Map;
                        int      preLength = 4; // "Map<".Length
                        string   innerStr  = key.Substring(preLength, key.Length - preLength - 1);
                        string[] splits    = innerStr.Split(',');
                        if (splits.Length != 2)
                        {
                            GLog.LogError("Parse Type {0} failed!", key);
                            return(false);
                        }
                        this.SubTypes    = new string[2];
                        this.SubTypes[0] = splits[0].Trim();
                        this.SubTypes[1] = splits[1].Trim();
                    }
                    else
                    {
                        this.Type = key;
                    }

                    this.Name = (string)jsonData[key];
                }
            }

            // TODO: check type is correct

            // check errors
            if (string.IsNullOrEmpty(this.Name))
            {
                GLog.LogError("GType.Field.Parse: 'Name' is required");
                return(false);
            }

            if (string.IsNullOrEmpty(this.Type))
            {
                GLog.LogError("GType.Field.Parse: 'Type' is required");
                return(false);
            }

            return(true);
        }
Example #18
0
        public override bool ParseJson(JsonData data)
        {
            this.Gen_Head = true;
            this.Name     = (string)data["Enum"];

            if (data.Keys.Contains("EnumGroup"))
            {
                this.EnumGroup = (string)data["EnumGroup"];
            }

            if (data.Keys.Contains("BitSize"))
            {
                this.bitSize = int.Parse((string)data["BitSize"]);
                if (bitSize != 8 &&
                    bitSize != 16 &&
                    bitSize != 32 &&
                    bitSize != 64)
                {
                    GLog.LogError("Enum BitSize must be 8 or 16 or 32 or 64: " + this.Name + "  bit size:" + bitSize);
                    bitSize = 16;
                }
            }
            else
            {
                this.bitSize = 16;
            }

            if (data.Keys.Contains("Fields"))
            {
                JsonData fieldsJson = data["Fields"];

                if (!fieldsJson.IsArray)
                {
                    GLog.LogError("'Fields' must be array.\n" + data.ToJson());
                    return(false);
                }

                this.Fields      = new string[fieldsJson.Count];
                this.FieldsValue = new long[fieldsJson.Count];
                for (int i = 0; i < fieldsJson.Count; ++i)
                {
                    string jsonDesc = (string)fieldsJson[i];
                    if (jsonDesc.IndexOf('=') >= 0)
                    {
                        if (!string.IsNullOrEmpty(EnumGroup))
                        {
                            GLog.LogError("Enum {0}'s value can't be specified because it's in EnumGroup.", this.Name);
                        }

                        string[] splits = jsonDesc.Split('=');
                        if (splits.Length != 2)
                        {
                            GLog.LogError("Invalid Enum Item: " + jsonDesc);
                            return(false);
                        }

                        this.Fields[i] = splits[0].Trim();
                        long newVal = long.Parse(splits[1].Trim());
                        if (i > 0 && newVal <= this.FieldsValue[i - 1])
                        {
                            GLog.LogError("Enum item value must be bigger than previous item. Invalid Item: " + jsonDesc);
                        }

                        switch (bitSize)
                        {
                        case 8:
                            this.FieldsValue[i] = (sbyte)newVal;
                            break;

                        case 16:
                            this.FieldsValue[i] = (short)newVal;
                            break;

                        case 32:
                            this.FieldsValue[i] = (int)newVal;
                            break;

                        case 64:
                            this.FieldsValue[i] = (long)newVal;
                            break;
                        }
                        if (this.FieldsValue[i] != newVal)
                        {
                            GLog.LogError("Enum {0}.{1} value cast from {2} to {3}", this.Name, this.Fields[i], newVal, this.FieldsValue[i]);
                        }
                    }
                    else
                    {
                        this.Fields[i] = jsonDesc;
                        if (i == 0)
                        {
                            if (!string.IsNullOrEmpty(EnumGroup))
                            {
                                this.FieldsValue[i] = GTypeManager.Instance.GetValueOfEnumGroup(EnumGroup);
                            }
                            else
                            {
                                this.FieldsValue[i] = 0;
                            }
                        }
                        else
                        {
                            this.FieldsValue[i] = this.FieldsValue[i - 1] + 1;
                        }
                    }

                    if (isReservedWord(this.Fields[i]))
                    {
                        GLog.LogError(Fields[i] + " is reserved word.");
                        return(false);
                    }
                }

                if (!string.IsNullOrEmpty(EnumGroup))
                {
                    GTypeManager.Instance.SetValueOfEnumGroup(EnumGroup, this.FieldsValue[this.FieldsValue.Length - 1]);
                }

                return(true);
            }
            else
            {
                this.Fields = new string[0];
                return(true);
            }
        }