Exemplo n.º 1
0
 private void AddStruct(ITypeDefinition strct, StringBuilder key)
 {
     if (strct.Namespace == "")
     {
         lock (Structs)
         {
             foreach (var typeArg in strct.TypeParameters)
             {
                 foreach (var constraint in typeArg.DirectBaseTypes)
                 {
                     key.Append(constraint.Name);
                 }
             }
             if (Structs.ContainsKey(key.ToString()))
             {
                 return;
             }
             Structs.Add(key.ToString(), new StructProperties(strct));
         }
     }
     else
     {
         AddNamespace(key, strct);
     }
 }
Exemplo n.º 2
0
        public bool DefineStruct(StructElement data)
        {
            Structs.Add(data);


            return(true);
        }
Exemplo n.º 3
0
        public void AddStruct(Lexeme nameToken, StructDecl node, ErrorHandler errorHandler)
        {
            if (FindStructName(nameToken) != null)
            {
                errorHandler.AddMessage(Severity.Error, $"Duplicate declaration of struct '{nameToken.Value}'", nameToken);
                return;
            }

            Structs.Add(nameToken.Value, node);
        }
Exemplo n.º 4
0
 public void AddStruct(TSLStruct struct_)
 {
     Structs.Add(struct_);
     if (struct_.Depth < StructSettings.MaxDepth)
     {
         StructsBeforeMaxDepth.Add(struct_);
         if (!struct_.DynamicLengthed)
         {
             FixedLengthStructsBeforeMaxDepth.Add(struct_);
         }
     }
 }
Exemplo n.º 5
0
        public StructDef LookupOrCreateStruct(string name)
        {
            var def = Structs.Lookup(name);

            if (def == null)
            {
                def = new StructDef {
                    Name        = name,
                    Predecl     = true,
                    TypeBuilder = this,
                };
                Structs.Add(name, def);
            }
            return(def);
        }
Exemplo n.º 6
0
 public void SetStruct(Class c)
 {
     if (c.IsClass)
     {
         return;
     }
     foreach (var @struct in Structs)
     {
         if (@struct == c)
         {
             return;
         }
     }
     Structs.Add(c);
 }
Exemplo n.º 7
0
 //Добавляет структуры всех таблиц базы фомата Tbl_*_sub*
 public void AddDbStructs(DaoDb db) //База данных
 {
     db.ConnectDao();
     foreach (TableDef t in db.Database.TableDefs)
     {
         if (t.Name.StartsWith("Tbl_") && t.Name.Substring(t.Name.Length - 5, 4) == "_Sub")
         {
             int    level = t.Name.Substring(t.Name.Length - 1).ToInt();
             string code  = t.Name.Substring(4, t.Name.Length - 9);
             if (!Structs.ContainsKey(code))
             {
                 Structs.Add(code, new TablGroup(db.File, code));
             }
             Structs[code].AddTabl(db, t.Name, level);
         }
     }
 }
Exemplo n.º 8
0
 private void AddStruct(IType strct, StringBuilder key)
 {
     lock (Structs)
     {
         foreach (var typeArg in strct.TypeParameters)
         {
             foreach (var constraint in typeArg.Constraints)
             {
                 key.Append(constraint.Name);
             }
         }
         if (Structs.ContainsKey(key.ToString()))
         {
             return;
         }
         Structs.Add(key.ToString(), new StructProperties(strct));
     }
 }
Exemplo n.º 9
0
        void ProcessTagStructs(BlamLib.CheApe.ProjectState state, IO.XmlStream s)
        {
            foreach (XmlNode n in s.Cursor.ChildNodes)
            {
                if (n.Name != "Struct")
                {
                    continue;
                }

                s.SaveCursor(n);
                var block = new TagStruct(state, s);
                s.RestoreCursor();
                string name_str = block.ToString();

                try { Structs.Add(name_str, block); }
                catch (ArgumentException) { Debug.LogFile.WriteLine(CheApe.Import.kDuplicateErrorStr, "tag struct definition", name_str); }
            }
        }
        private void ConstuctInputDependencies()
        {
            var dependenciesRedi = new InputDependencies();
            var dependencies     = BackingData.AsKeyValueCollection().GetArray("m_InputDependencies");

            foreach (var dependency in dependencies)
            {
                var dependencyRedi = new InputDependencies.InputDependency
                {
                    ContentRelativeFilename = dependency.GetProperty <string>("m_RelativeFilename"),
                    ContentSearchPath       = dependency.GetProperty <string>("m_SearchPath"),
                    FileCRC = (uint)dependency.GetUnsignedIntegerProperty("m_nFileCRC"),
                };

                dependenciesRedi.List.Add(dependencyRedi);
            }

            Structs.Add(REDIStruct.InputDependencies, dependenciesRedi);
        }
        private void ConstructSpecialDependencies()
        {
            var specialDependenciesRedi = new SpecialDependencies();
            var specialDependencies     = BackingData.AsKeyValueCollection().GetArray("m_SpecialDependencies");

            foreach (var specialDependency in specialDependencies)
            {
                var specialDependencyRedi = new SpecialDependencies.SpecialDependency
                {
                    String             = specialDependency.GetProperty <string>("m_String"),
                    CompilerIdentifier = specialDependency.GetProperty <string>("m_CompilerIdentifier"),
                    Fingerprint        = specialDependency.GetIntegerProperty("m_nFingerprint"),
                    UserData           = specialDependency.GetIntegerProperty("m_nUserData"),
                };

                specialDependenciesRedi.List.Add(specialDependencyRedi);
            }

            Structs.Add(REDIStruct.SpecialDependencies, specialDependenciesRedi);
        }
Exemplo n.º 12
0
 public override void SetupParser()
 {
     Parser = (t) =>
     {
         switch (t.Class)
         {
         case TokenClass.Define:
             switch (t.Token)
             {
             case Token.Module:
                 Console.WriteLine("Parsing Define.");
                 Console.WriteLine("Module:" + PeekNext().Text);
                 var mod = new VSModule(TokStream);
                 Structs.Add(mod);
                 //  Console.WriteLine("Parsed module name:" + mod.ModuleName);
                 break;
             }
             break;
         }
     };
 }
Exemplo n.º 13
0
        public override void SetupParser()
        {
            PreParser = (t) =>
            {
                ModuleName = t.Text;
            };
            Parser = (t) =>
            {
                switch (t.Class)
                {
                case TokenClass.Type:

                    Console.WriteLine("Parsing Variable definitions.");
                    BackOne();
                    var vdef = new VSDefineVars(TokStream);
                    Structs.Add(vdef);

                    break;
                }
            };
        }
Exemplo n.º 14
0
        //Добавляет структуру одной группы таблиц
        public TablGroup AddStruct(DaoDb db,                                                                        //База данных
                                   string table0, string table1 = null, string table2 = null, string table3 = null) //Имена таблиц разной вложенности
        {
            db.ConnectDao();
            var s = new TablGroup(db.File, table0);

            Structs.Add(table0, s);
            s.AddTabl(db, table0, 0);
            if (!table1.IsEmpty())
            {
                s.AddTabl(db, table1, 1);
            }
            if (!table2.IsEmpty())
            {
                s.AddTabl(db, table2, 2);
            }
            if (!table3.IsEmpty())
            {
                s.AddTabl(db, table3, 3);
            }
            return(s);
        }
Exemplo n.º 15
0
        // Makes two shallow passes over the declarations inside a class to obtain
        // the names and types of all consts, methods and structs declared at the
        // top level; without this info, typechecking cannot begin.
        private void prePass(AST node)
        {
            addPredeclared();

            AST_kary decls = node as AST_kary;

            if (decls == null || decls.Tag != NodeType.DeclList)
            {
                throw new Exception("Bad argument passed to prePass");
            }
            // make one pass over the declarations just to enter the names of structs into
            // the Structs table
            int arity = decls.NumChildren;

            for (int i = 0; i < arity; i++)
            {
                AST ch = decls[i];
                if (ch.Tag != NodeType.Struct)
                {
                    continue; // it was not a struct declaration
                }
                string name = ((AST_leaf)(ch[0])).Sval;
                if (Structs.ContainsKey(name))
                {
                    ReportError(ch[0].LineNumber, "Duplicate declaration of struct {0}", name);
                }
                else
                {
                    Structs.Add(name, new CbStruct(name));
                }
            }
            // now make a second pass over the declarations to
            // 1. add const declarations to the Consts table
            // 2. add method declarations to the Methods table
            // 3. fill in the field details for each struct in the Structs table
            for (int i = 0; i < arity; i++)
            {
                AST    ch = decls[i];
                string name;
                CbType typ;
                int    argsize;

                switch (ch.Tag)
                {
                case NodeType.Struct:
                    CbStruct str;
                    name = ((AST_leaf)(ch[0])).Sval;

                    // find existing struct
                    Structs.TryGetValue(name, out str);     // do error checking

                    AST fldlst = ch[1];
                    AST fld;
                    AST idlst;

                    argsize = fldlst.NumChildren;
                    int idsize;
                    // iterate through the field list
                    for (int j = 0; j < argsize; j++)
                    {
                        // get field declaration
                        fld = fldlst[j];
                        // find declaration type
                        typ = lookUpType(fld[0]);
                        // get list of variables declared
                        idlst  = fld[1];
                        idsize = idlst.NumChildren;
                        // add all declared variables to the struct
                        for (int k = 0; k < idsize; k++)
                        {
                            str.AddField(((AST_leaf)(idlst[k])).Sval, typ);
                        }
                    }
                    break;

                case NodeType.Const:
                    // Add the name and type of this constant to the Consts table
                    name = ((AST_leaf)(ch[1])).Sval;

                    typ = lookUpType(ch[0]);
                    if (Consts.ContainsKey(name))
                    {
                        ReportError(ch[0].LineNumber, "Duplicate declaration of const {0}", name);
                    }
                    else
                    {
                        Consts.Add(name, typ);
                    }
                    break;

                case NodeType.Method:
                    name = ((AST_leaf)(ch[1])).Sval;
                    ch[2].Accept(this);
                    // check for duplicate method
                    CbMethod existing = getMethod(name, ch[2], false);
                    if (existing != null)
                    {
                        ReportError(ch[0].LineNumber, "Duplicate declaration of method {0}", name);
                        break;
                    }

                    CbType typm = CbType.Void;
                    // create new CbMethod
                    if (ch[0] != null)
                    {
                        typm = lookUpType(ch[0]);
                    }
                    CbMethod method = new CbMethod(name, typm);

                    // add argument list (full signature) to CbMethod
                    AST args = ch[2];
                    for (int j = 0; j < args.NumChildren; j++)
                    {
                        method.ArgType.Add(lookUpType(args[j][0]));
                    }
                    // get list of overloaded methods sharing same name
                    List <CbMethod> methods;
                    if (!Methods.TryGetValue(name, out methods)) // if none exist create new list
                    {
                        methods = new List <CbMethod>();
                    }
                    // add method to list
                    methods.Add(method);
                    // replace old list of methods with this name with new list
                    Methods[name] = methods;
                    break;

                default:
                    throw new Exception("Unexpected node type " + ch.Tag);
                }
            }
        }
Exemplo n.º 16
0
        public void ApplyFoo(XElement childElement, bool isValue)
        {
            var addressElements = childElement.Elements("address").ToList();

            if (addressElements.Count == 0)
            {
                var child = CreateChild(childElement, isValue);
                child.StartAddress = StartAddress + ChildOffset;
                child.FileAddress  = FileAddress + FileOffset;

                child.Parse();

                ChildOffset += child.Size;

                if (!IsExcludedFromFileOffset(child.ValuePath))
                {
                    FileOffset += child.FileSize;
                }

                if (isValue)
                {
                    Values.Add((RolandValue)child);
                }
                else
                {
                    Structs.Add((RolandStruct)child);
                }
            }
            else
            {
                var arrayIndex = 0;

                bool useArrayIndex = addressElements.Count > 1;

                foreach (var addressElement in addressElements)
                {
                    var childOffset = ParseAddress(addressElement.Value, 0);
                    var fileOffset  = isValue ? ParseAddress(addressElement.Value, 0) : FileOffset;


                    var typeElement = childElement.Element("type");
                    var childName   = "";

                    if (typeElement != null)
                    {
                        childName = childElement.Element("type").Value;
                    }
                    else
                    {
                        childName = "notset";
                    }
                    if (!isValue)
                    {
                        Debug.WriteLine(
                            $"ParseAddress for {childName} {addressElement.Value} with file offset {FileOffset:X} results in filestart {FileAddress:X} wih offset {fileOffset:X}. ChildOffset is {childOffset:X}");
                    }

                    var child = CreateChild(childElement, isValue);
                    child.StartAddress  = StartAddress + childOffset;
                    child.FileAddress   = FileAddress + fileOffset;
                    child.UseArrayIndex = useArrayIndex;
                    child.ArrayIndex    = arrayIndex;
                    child.Parse();


                    arrayIndex++;

                    if (childOffset + child.Size > ChildOffset)
                    {
                        ChildOffset = childOffset + child.Size;
                    }

                    if (!IsExcludedFromFileOffset(child.ValuePath))
                    {
                        if (IsAbsoluteAddress(addressElement.Value))
                        {
                            if (fileOffset + child.FileSize > FileOffset)
                            {
                                FileOffset = fileOffset + child.FileSize;
                            }
                        }
                        else
                        {
                            if (fileOffset + child.Size > FileOffset)
                            {
                                FileOffset = fileOffset + child.Size;
                            }
                        }
                    }


                    if (isValue)
                    {
                        Values.Add((RolandValue)child);
                    }
                    else
                    {
                        Structs.Add((RolandStruct)child);
                    }
                }
            }
        }
Exemplo n.º 17
0
/*		static readonly List<uint> _fieldids = new List<uint>();
 *              /// <summary>
 *              ///
 *              /// </summary>
 *              internal static List<uint> FieldIds
 *              { get { return _fieldids; } } */
        #endregion Properties (static)


        #region Methods (static)
        /// <summary>
        /// Reads a GFF-file and parses out its data to a GFFData object.
        /// @note Sections will be extracted in a non-arbitrary sequence because
        /// the data in a specific section could rely on the data in a different
        /// section. The order I have chosen is:
        /// 1. Header data (ofc)
        /// 2. FieldIndices
        /// 3. Structs - relies on FieldIndices
        /// 4. Labels
        /// 5. Fields - relies on Structs and Labels and extracts FieldData and ListIndices
        /// </summary>
        /// <param name="pfe">path-file-extension - ensure file exists before call</param>
        internal static GffData ReadGFFfile(string pfe)
        {
            Structs.Clear();             // Structs and Fields will be cleared after load completes
            Fields.Clear();              // but do it here (before load starts) also - jic.

            byte[] bytes = FileService.ReadFile(pfe);
            if (bytes != null)
            {
                if (bytes.Length != 0)
                {
                    uint pos = 0;
                    uint b;

                    var buffer = new byte[8];
                    for (b = 0; b != 8; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    string ver = Encoding.ASCII.GetString(buffer, 0, buffer.Length);

                    if (ver.Substring(3) != Globals.SupportedVersion)
                    {
                        FileService.error("That is not a version 3.2 GFF file.");
                        return(null);
                    }


                    bool le = BitConverter.IsLittleEndian;                     // hardware architecture

                    var data = new GffData(pfe);

                    data.TypeVer = ver;
                    data.Type    = GffData.GetGffType(ver.Substring(0, 3));

                    data.Latest            = File.GetLastWriteTime(pfe);
                    FileWatchDialog.Bypass = false;


// HEADER METADATA ->
                    pos    = head_StructOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint StructOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("StructOffset= " + StructOffset);

                    // The Struct-section will always start at 56-bytes (0x38)
                    if (StructOffset != Globals.Length_HEADER)
                    {
                        FileService.error("That does not appear to be a GFF file.");
                        return(null);
                    }

                    pos    = head_StructCount;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint StructCount = BitConverter.ToUInt32(buffer, 0);                     // count of elements
                    //logfile.Log("StructCount= " + StructCount);


                    pos    = head_FieldOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("FieldOffset= " + FieldOffset);


                    pos    = head_FieldCount;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldCount = BitConverter.ToUInt32(buffer, 0);                     // count of elements
                    //logfile.Log("FieldCount= " + FieldCount);


                    pos    = head_LabelOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint LabelOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("LabelOffset= " + LabelOffset);


                    pos    = head_LabelCount;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint LabelCount = BitConverter.ToUInt32(buffer, 0);                     // count of elements
                    //logfile.Log("LabelCount= " + LabelCount);


                    pos    = head_FieldDataOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldDataOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("FieldDataOffset= " + FieldDataOffset);


                    pos    = head_FieldDataLength;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldDataCount = BitConverter.ToUInt32(buffer, 0);                     // count of bytes (not used.)
                    //logfile.Log("FieldDataCount= " + FieldDataCount);


                    pos    = head_FieldIndicesOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldIndicesOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("FieldIndicesOffset= " + FieldIndicesOffset);


                    pos    = head_FieldIndicesLength;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint FieldIndicesCount = BitConverter.ToUInt32(buffer, 0);                     // count of bytes
                    //logfile.Log("FieldIndicesCount= " + FieldIndicesCount);


                    pos    = head_ListIndicesOffset;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint ListIndicesOffset = BitConverter.ToUInt32(buffer, 0);
                    //logfile.Log("ListIndicesOffset= " + ListIndicesOffset);


                    pos    = head_ListIndicesLength;
                    buffer = new byte[4];
                    for (b = 0; b != 4; ++b)
                    {
                        buffer[b] = bytes[pos++];
                    }

                    if (!le)
                    {
                        Array.Reverse(buffer);
                    }
                    uint ListIndicesCount = BitConverter.ToUInt32(buffer, 0);                     // count of bytes (not used.)
                    //logfile.Log("ListIndicesCount= " + ListIndicesCount);


                    //logfile.Log("");

// FIELDID DATA -> contains the FieldIds of Structs that contain > 1 field (is req'd for parsing Structs)
// - a list of DWORD ids into the Fields section
                    //logfile.Log("FIELDIDS");
                    //int fid = 0; // log

                    var fieldids = new List <uint>();

                    pos = FieldIndicesOffset;
                    while (pos != FieldIndicesOffset + FieldIndicesCount)
                    {
                        //logfile.Log(". start= " + FieldIndicesOffset + " stop= " + (FieldIndicesOffset + FieldIndicesCount));
                        //logfile.Log(". fid #" + fid++);

                        buffer = new byte[4];                         // 4-byte DWORD - field id
                        for (b = 0; b != 4; ++b)
                        {
                            //logfile.Log(". . pos= " + pos);
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        fieldids.Add(BitConverter.ToUInt32(buffer, 0));                         // WARNING: There is no safety on the count below.
                    }


// STRUCT DATA ->
// - DWORD type-id
// - DWORD dataordataoffset
// - DWORD fieldcount
                    uint fields, idoroffset, i, j;

                    pos = StructOffset;
                    for (i = 0; i != StructCount; ++i)
                    {
                        //logfile.Log("Struct #" + i);
                        var st = new Struct();

                        buffer = new byte[4];                         // type-id ->
                        for (b = 0; b != 4; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        st.typeid = BitConverter.ToUInt32(buffer, 0);
                        //logfile.Log(". typid= " + st.typeid);

                        buffer = new byte[4];                         // dataordataoffset ->
                        for (b = 0; b != 4; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        idoroffset = BitConverter.ToUInt32(buffer, 0);                          // if fields=1 -> id into the FieldArray
                        // if fields>1 -> offset into FieldIndices -> list of ids into the FieldArray

                        buffer = new byte[4];                         // fieldcount ->
                        for (b = 0; b != 4; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        fields = BitConverter.ToUInt32(buffer, 0);
                        //logfile.Log(". fields= " + fields);

                        st.fieldids = new List <uint>();
                        if (fields == 1)                                        // get the FieldId directly w/ the Struct's 'idoroffset' id ->
                        {
                            //logfile.Log(". . idoroffset/id= " + idoroffset);
                            //logfile.Log(". . data._fields.Count= " + data._fields.Count);
                            st.fieldids.Add(idoroffset);
                        }
                        else if (fields > 1)                            // get the FieldIds out of the FieldIndices w/ the 'idoroffset' offset ->
                        {
                            uint fieldid;
                            for (j = 0; j != fields; ++j)
                            {
                                //logfile.Log(". . [" + j + "] idoroffset/offset= " + idoroffset + " -> fieldids id= " + (idoroffset / 4 + j));
                                //logfile.Log(". . data._fieldids Length= " + (data._fieldids.Count * 4));
                                //logfile.Log(". . data._fields.Count= " + data._fields.Count);

                                fieldid = fieldids[(int)(idoroffset / Globals.Length_DWORD + j)];                                       // 4 bytes in each DWORD (ie. convert offset to id id)
                                //logfile.Log(". . fieldid= " + fieldid);
                                st.fieldids.Add(fieldid);                                                                               // isn't the GFF format wonderful ... at least it works
                            }                                                                                                           // the Bioware documentation could be better.
                        }                                                                                                               // Ps. it contains inaccurate and unspecific info

                        Structs.Add(st);
                    }


// LABEL DATA -> contains Labels for the Fields (is req'd for parsing Fields)
// - each label shall be unique across the entire GFF data
// - 16-CHAR
                    var    labels = new List <string>();
                    string label;

                    pos = LabelOffset;
                    for (i = 0; i != LabelCount; ++i)
                    {
                        buffer = new byte[Globals.Length_LABEL];                         // 16-byte CHAR(s) - label length
                        for (b = 0; b != Globals.Length_LABEL; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        label = Encoding.ASCII.GetString(buffer, 0, buffer.Length).TrimEnd('\0');
                        labels.Add(label);
                    }


// FIELD DATA ->
// - the doc contradicts itself by saying that the TopLevelStruct is the 1st
//   entry in the Fields section but that the Fields section does not contain
//   the TopLevelStruct ... the latter appears to be correct: the first Field in
//   a toolset-written FieldsArray is "Description" eg.
// - DWORD datatype
// - DWORD label-id
// - DWORD dataordataoffset
//   - if BYTE,CHAR,WORD,SHORT,DWORD,INT,FLOAT -> dataordataoffset is a value.
//   - if DWORD64,INT64,DOUBLE,CExoString,CResRef,CExoLocString -> dataordataoffset
//     is an offset from the start of the FieldDataBlock section to complex data:
//     - DWORD64       8-bytes
//     - INT64         8-bytes
//     - DOUBLE        8-bytes
//     - CExoString    DWORD (length) + chars
//     - CExoLocString DWORD (total length) + DWORD (strref) + DWORD (stringcount) + [INT (id) + INT (length) + chars]
//     - CResRef       1-byte (length) + chars (lowercase)
//     - VOID          arbitrary
//   - if Struct -> dataordataoffset is an id into the Struct section.
//   - if List -> dataordataoffset is an offset from the start of the ListIndices
//     section to an array of DWORDs, the first of which is the count of DWORDS
//     that follow, which are ids into the Struct section.

                    uint offset, length, count;

                    pos = FieldOffset;
                    for (i = 0; i != FieldCount; ++i)
                    {
                        var field = new GffData.Field();


                        buffer = new byte[4];                         // 4-byte DWORD - field type
                        for (b = 0; b != 4; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        field.type = (FieldTypes)BitConverter.ToUInt32(buffer, 0);


                        buffer = new byte[4];                         // 4-byte DWORD - field label id
                        for (b = 0; b != 4; ++b)
                        {
                            buffer[b] = bytes[pos++];
                        }

                        if (!le)
                        {
                            Array.Reverse(buffer);
                        }
                        field.label = labels[(int)BitConverter.ToUInt32(buffer, 0)];
                        //logfile.Log("label= " + field.label);


                        buffer = new byte[4];                                   // 4-byte DWORD - field data (val, is not a DWORD per se) or data
                        for (b = 0; b != 4; ++b)                                // offset into (a) DataBlock or (b) ListIds or id into (c) Structs
                        {
                            buffer[b] = bytes[pos++];
                        }


                        switch (field.type)
                        {
                        // WARNING: non-Complex types whose size is less than or
                        // equal to 4-bytes are (according to the doc) contained
                        // in the first byte(s) of the dataordataoffset 'DWORD'.

                        case FieldTypes.BYTE:
                            field.BYTE = buffer[0];
                            break;

                        case FieldTypes.CHAR:
                        {
                            var a = (sbyte[])(object)new[] { buffer[0] };
                            field.CHAR = a[0];
                            break;
                        }

                        case FieldTypes.WORD:
                        {
                            var a = new byte[2];
                            if (le)
                            {
                                a[0] = buffer[0];
                                a[1] = buffer[1];
                            }
                            else
                            {
                                a[0] = buffer[1];
                                a[1] = buffer[0];
                            }

                            field.WORD = BitConverter.ToUInt16(a, 0);
                            break;
                        }

                        case FieldTypes.SHORT:
                        {
                            var a = new byte[2];
                            if (le)
                            {
                                a[0] = buffer[0];
                                a[1] = buffer[1];
                            }
                            else
                            {
                                a[0] = buffer[1];
                                a[1] = buffer[0];
                            }

                            field.SHORT = BitConverter.ToInt16(a, 0);
                            break;
                        }

                        case FieldTypes.DWORD:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.DWORD = BitConverter.ToUInt32(buffer, 0);
                            break;

                        case FieldTypes.INT:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.INT = BitConverter.ToInt32(buffer, 0);
                            break;

                        case FieldTypes.DWORD64:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);
                            buffer = new byte[8];
                            for (b = 0; b != 8; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.DWORD64 = BitConverter.ToUInt64(buffer, 0);
                            break;

                        case FieldTypes.INT64:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);
                            buffer = new byte[8];
                            for (b = 0; b != 8; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.INT64 = BitConverter.ToInt64(buffer, 0);
                            break;

                        case FieldTypes.FLOAT:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.FLOAT = BitConverter.ToSingle(buffer, 0);
                            break;

                        case FieldTypes.DOUBLE:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);
                            buffer = new byte[8];
                            for (b = 0; b != 8; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.DOUBLE = BitConverter.ToDouble(buffer, 0);
                            break;

                        case FieldTypes.CResRef:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);
                            length = bytes[offset];                                     // 1-byte size

                            ++offset;
                            buffer = new byte[(int)length];
                            for (b = 0; b != length; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            field.CResRef = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
                            break;

                        case FieldTypes.CExoString:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);

                            buffer = new byte[4];
                            for (b = 0; b != 4; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            length = BitConverter.ToUInt32(buffer, 0);                                     // 4-byte size

                            buffer = new byte[(int)length];
                            for (b = 0; b != length; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            field.CExoString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                            field.CExoString = field.CExoString.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
                            break;

                        case FieldTypes.CExoLocString:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);

                            buffer = new byte[4];                                                                                       // total length (not incl/ these 4 bytes) ->
                            for (b = 0; b != 4; ++b)                                                                                    // aka Pointless. just advance the offset val
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            length = BitConverter.ToUInt32(buffer, 0);                                     // 4-byte size

                            buffer = new byte[4];                                                          // strref (-1 no strref)
                            for (b = 0; b != 4; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.CExoLocStrref = BitConverter.ToUInt32(buffer, 0);                                     // 4-byte size

                            buffer = new byte[4];                                                                       // substring count
                            for (b = 0; b != 4; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            count = BitConverter.ToUInt32(buffer, 0);                                     // 4-byte size

                            if (count != 0)
                            {
                                field.Locales = new List <GffData.Locale>();

                                //logfile.Log("label= " + field.label);
                                for (j = 0; j != count; ++j)
                                {
                                    var locale = new GffData.Locale();

                                    buffer = new byte[4];                                             // langid
                                    for (b = 0; b != 4; ++b)
                                    {
                                        buffer[b] = bytes[offset++];
                                    }

                                    if (!le)
                                    {
                                        Array.Reverse(buffer);
                                    }
                                    locale.SetLocaleLanguage(BitConverter.ToUInt32(buffer, 0));

                                    buffer = new byte[4];                                             // stringlength
                                    for (b = 0; b != 4; ++b)
                                    {
                                        buffer[b] = bytes[offset++];
                                    }

                                    if (!le)
                                    {
                                        Array.Reverse(buffer);
                                    }
                                    length = BitConverter.ToUInt32(buffer, 0);
                                    //logfile.Log("length= " + length);

                                    buffer = new byte[(int)length];
                                    for (b = 0; b != length; ++b)
                                    {
                                        buffer[b] = bytes[offset++];
                                    }

                                    locale.local = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                                    locale.local = locale.local.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
                                    //logfile.Log("local= " + locale.local);

                                    field.Locales.Add(locale);
                                }
                            }
                            break;

                        case FieldTypes.VOID:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = FieldDataOffset + BitConverter.ToUInt32(buffer, 0);
                            buffer = new byte[4];
                            for (b = 0; b != 4; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            length = BitConverter.ToUInt32(buffer, 0);

                            field.VOID = new byte[(int)length];

                            for (j = 0; j != length; ++j)
                            {
                                field.VOID[j] = bytes[offset++];
                            }

                            break;

                        case FieldTypes.List:                                 // a list-type Field is an offset into the FieldIndices; the later contains a list of StructIds.
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            offset = ListIndicesOffset + BitConverter.ToUInt32(buffer, 0); // offset into the (not)FieldIndices(not) -> try ListIndices

                            buffer = new byte[4];                                          // 4-byte DWORD - count of structids
                            for (b = 0; b != 4; ++b)
                            {
                                buffer[b] = bytes[offset++];
                            }

                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            count = BitConverter.ToUInt32(buffer, 0);

                            var list = new List <uint>();
                            for (j = 0; j != count; ++j)
                            {
                                buffer = new byte[4];                                         // 4-byte DWORD - structid
                                for (b = 0; b != 4; ++b)
                                {
                                    buffer[b] = bytes[offset++];
                                }

                                if (!le)
                                {
                                    Array.Reverse(buffer);
                                }
                                list.Add(BitConverter.ToUInt32(buffer, 0));
                            }
                            field.List = list;
                            break;

                        case FieldTypes.Struct:
                            if (!le)
                            {
                                Array.Reverse(buffer);
                            }
                            field.Struct = Structs[(int)BitConverter.ToUInt32(buffer, 0)];                                     // NOTE: That is an id into the Structs not an offset.
                            break;
                        }

                        Fields.Add(field);
                    }
                    return(data);
                }

                FileService.error("That file has no data.");
            }
            return(null);
        }
Exemplo n.º 18
0
            public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
            {
                if (context.Node is not StructDeclarationSyntax sds)
                {
                    return;
                }
                var methods = sds.ChildNodes().OfType <MethodDeclarationSyntax>().Where(m =>
                {
                    var sm = (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(m);
                    return(sm != null && sm.GetAttributes()
                           .Any(a => a.AttributeClass?.Name == "MemberFunctionAttribute" || a.AttributeClass?.Name == "VirtualFunctionAttribute"));
                }).ToList();

                if (methods.Count > 0)
                {
                    if (context.SemanticModel.GetDeclaredSymbol(sds) is not INamedTypeSymbol structType)
                    {
                        return;
                    }
                    var structObj = new Struct
                    {
                        Name             = structType.Name,
                        Namespace        = structType.ContainingNamespace.ToDisplayString(),
                        MemberFunctions  = new List <Function>(),
                        VirtualFunctions = new List <Function>()
                    };

                    foreach (var m in methods)
                    {
                        if (context.SemanticModel.GetDeclaredSymbol(m) is not IMethodSymbol ms)
                        {
                            continue;
                        }
                        var format = new SymbolDisplayFormat(
                            typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                            miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
                        var functionObj = new Function
                        {
                            Name       = ms.Name,
                            ReturnType = ms.ReturnType.ToDisplayString(format),
                            HasReturn  = ms.ReturnType.ToDisplayString() != "void",
                            HasParams  = ms.Parameters.Any(),
                            ParamList  = string.Join(",",
                                                     ms.Parameters.Select(p => $"{p.Type.ToDisplayString(format)} {p.Name}")),
                            ParamTypeList = string.Join(",", ms.Parameters.Select(p => p.Type.ToDisplayString(format))),
                            ParamNameList = string.Join(",", ms.Parameters.Select(p => p.Name))
                        };
                        if (ms.GetAttributes().FirstOrDefault(a => a.AttributeClass?.Name == "MemberFunctionAttribute") is { } memberFuncAttr)
                        {
                            functionObj.Signature = (string)memberFuncAttr.ConstructorArguments[0].Value;
                            functionObj.IsStatic  = memberFuncAttr.NamedArguments.Any() ? (bool)memberFuncAttr.NamedArguments[0].Value.Value : false;
                            structObj.MemberFunctions.Add(functionObj);
                        }
                        if (ms.GetAttributes().FirstOrDefault(a => a.AttributeClass?.Name == "VirtualFunctionAttribute") is { } virtualFuncAttr)
                        {
                            functionObj.VirtualOffset = (int)virtualFuncAttr.ConstructorArguments[0].Value;
                            structObj.VirtualFunctions.Add(functionObj);
                        }
                    }

                    Structs.Add(structObj);
                }
            }
Exemplo n.º 19
0
        public void Process()
        {
            Content = System.IO.File.ReadAllText(File);
            Content = Content.Trim();

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < Content.Length; i++)
            {
                char c = Content[i];
                // 字符解析获取语法
                string sSymbol = string.Empty;
                if (c == '#')
                {
                    isComment = true;
                }
                if (c == '\n')
                {
                    isComment = false;
                }
                if (isComment)
                {
                    sb.Append(c);
                }
                else
                {
                    if (c == '\n')
                    {
                        sSymbol = sb.ToString();
                    }
                    else if (c == ' ')
                    {
                        sSymbol = sb.ToString();
                    }
                    else if (c == '\t')
                    {
                        sSymbol = sb.ToString();
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                // 确保当完成所有字符读取后可以生成字符表
                if (i == Content.Length - 1)
                {
                    sSymbol = sb.ToString();
                }

                if (!string.IsNullOrEmpty(sSymbol))
                {
                    Symbols.Add(sSymbol);
                    sb.Clear();
                }

                if (c == '\n' || c == '\t')
                {
                    Symbols.Add(c.ToString());
                }
            }

            for (Index = 0; Index < Symbols.Count; Index++)
            {
                string symbol = Symbols[Index];

                if (symbol == "\n")
                {
                    Row = Row + 1;
                }

                if (symbol == "\n")
                {
                    indentation = 0;
                }

                // 计算首行缩进
                while (symbol == "\n")
                {
                    Index = Index + 1;
                    if (Index == Symbols.Count - 1)
                    {
                        break;
                    }
                    string indent = Symbols[Index];
                    if (indent == "\t")
                    {
                        indentation++;
                    }
                    else
                    {
                        break;
                    }
                }
                symbol = Symbols[Index];

                if (indentation == 0)
                {
                    if (symbol == "struct")
                    {
                        define = Define.Struct;
                        Structs.Add(new TStruct());
                        Structs.Last().Name    = GetSName();
                        Structs.Last().Comment = GetComment();
                    }
                }

                if (indentation == 1)
                {
                    if (!string.IsNullOrEmpty(symbol))
                    {
                        // 首行缩进为1如果有不为空的字符则代表不处于内部结构中
                        if (define == Define.InStruct)
                        {
                            define = Define.Struct;
                        }
                    }

                    // 跳过直接换行
                    if (symbol == "\r")
                    {
                        continue;
                    }
                    if (symbol == "\n")
                    {
                        continue;
                    }

                    if (symbol == "struct")
                    {
                        if (Structs.Last() != null)
                        {
                            define = Define.InStruct;
                            Structs.Last().CStructs.Add(new TStruct());
                            Structs.Last().CStructs.Last().Name = GetSName();
                            Structs.Last().CStructs.Last().Comment = GetComment();
                        }
                        else
                        {
                            throw new Exception(ErrorMessage("首行缩进为1的语法定义为内部嵌套结构, 子结构需要定义在父结构内!"));
                        }
                    }
                    else
                    {
                        int    cIndex = Index;
                        TField tField = new TField()
                        {
                            Type = GetSType(), Name = GetSName(), Comment = GetComment()
                        };
                        Structs.Last().Fields.Add(tField);
                    }
                }

                if (indentation == 2)
                {
                    // 跳过直接换行
                    if (symbol == "\r")
                    {
                        continue;
                    }
                    if (symbol == "\n")
                    {
                        continue;
                    }

                    if (define == Define.InStruct)
                    {
                        if (symbol == "struct")
                        {
                            throw new Exception(ErrorMessage("内部结构不能在套内部结构!"));
                        }
                        TField tField = new TField()
                        {
                            Type = GetSType(), Name = GetSName(), Comment = GetComment()
                        };
                        Structs.Last().CStructs.Last().Fields.Add(tField);
                    }
                    else
                    {
                        throw new Exception(ErrorMessage("首行缩进为2的语法定义要求包含在内部结构中!"));
                    }
                }
            }
        }
Exemplo n.º 20
0
        void LoadTypes(XmlNode root)
        {
            foreach (XmlNode node in root.ChildNodes)
            {
                if (node is XmlComment)
                {
                    continue;
                }
                if (node.Attributes["requires"] != null && node.ChildNodes.Count == 0)
                {
                }
                if (node.Attributes["category"] != null)
                {
                    string cat = node.Attributes["category"].Value;
                    if (cat == "union" || cat == "struct")
                    {
                        string       name   = node.Attributes["name"].Value;
                        bool         union  = cat == "union";
                        List <Field> fields = new List <Field>();

                        foreach (XmlNode fNode in node.ChildNodes)
                        {
                            if (fNode is XmlComment)
                            {
                                continue;
                            }
                            if (fNode.Name == "comment")
                            {
                                continue;
                            }
                            if (fNode.Name == "validity")
                            {
                                continue;
                            }
                            LoadField(fNode, fields);
                        }

                        var s = new Struct(name, fields, union);
                        Structs.Add(s);
                        StructMap.Add(name, s);
                    }
                    else if (cat == "handle")
                    {
                        if (node.Attributes["alias"] != null)
                        {
                            continue;
                        }
                        string       name   = node["name"].InnerText;
                        List <Field> fields = new List <Field>();
                        var          s      = new Struct(name, fields, false);
                        s.Handle = true;

                        if (node["type"].InnerText == "VK_DEFINE_HANDLE")
                        {
                            fields.Add(new Field("native", "IntPtr", false, null));
                        }
                        else
                        {
                            fields.Add(new Field("native", "ulong", false, null));
                        }

                        Structs.Add(s);
                        StructMap.Add(name, s);
                    }
                    else if (cat == "enum")
                    {
                        if (node.Attributes["alias"] != null)
                        {
                            continue;
                        }
                        var eName = node.Attributes["name"].Value;
                        if (!EnumMap.ContainsKey(eName))
                        {
                            var e = new Enum(eName, false);
                            EnumMap.Add(eName, e);
                            Enums.Add(e);
                            AllEnums.Add(eName);
                        }
                    }
                    else if (cat == "bitmask")
                    {
                        if (node.Attributes["alias"] != null)
                        {
                            continue;
                        }
                        var eName = node["name"].InnerText;
                        if (!EnumMap.ContainsKey(eName))
                        {
                            var e = new Enum(eName, true);
                            EnumMap.Add(eName, e);
                            Enums.Add(e);
                            AllEnums.Add(eName);
                        }
                    }
                }
            }
        }