public static string Generate(SingleType members) { string mt = "MsgTypes.Unknown"; if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) { t = "std_msgs." + t; } mt = "MsgTypes." + t.Replace(".", "__"); if (mt.Contains("ColorRGBA")) { Console.WriteLine(mt); } } return(String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name, members.IsLiteral.ToString().ToLower(), ("typeof(" + members.Type + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt)); }
public static SingleType WhatItIs(MsgFile parent, string s, string extraindent) { string[] pieces = s.Split('/'); string package = null; // sometimes, a string can contain the char '/', such as the following line: // string CONTENT_JSON = "application/json" if (pieces.Length == 2) { if (s.ToLower().Contains("string") && !MsgFile.resolver.ContainsKey(pieces[0])) { goto ResolvingStep; } package = pieces[0]; s = pieces[1]; } ResolvingStep: SingleType st = new SingleType(package, s, extraindent); parent.resolve(st); WhatItIs(parent, st); return(st); }
private string GenerateEqualityCodeForOne(string type, string name, SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } if (type == "Time" || type == "Duration") { return(string.Format(@" {0}ret &= {1}.data.Equals(other.{1}.data);", leadingWhitespace, name)); } else if (type == "TimeData") { return(string.Format(@" {0}ret &= {1}.Equals(other.{1});", leadingWhitespace, name)); } else if (st.IsLiteral) { if (st.Const) { return(""); } return(string.Format(@" {0}ret &= {1} == other.{1};", leadingWhitespace, name)); } else { return(string.Format(@" {0}ret &= {1}.Equals(other.{1});", leadingWhitespace, name)); } // and that's it }
public string GenerateDeserializationCode(SingleType st) { //Console.WriteLine(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta); //if (!st.IsLiteral) // Console.WriteLine(st.Name); return(""); }
/// <summary> /// Returns the namespaced type name (if neccessary) /// </summary> /// <param name="st">This thing's SingleType</param> /// <param name="type">(optional) the type string</param> /// <returns>duh</returns> public static string GetNamespacedType(SingleType st, string type = null) { if (type == null) type = st.Type; if (st.Package != null && !KnownTypes.ContainsKey(st.rostype) && !type.Contains(st.Package)) return string.Format("Messages.{0}.{1}", st.Package, type); return type; }
public static void WhatItIs(MsgFile parent, SingleType t) { if (t.IsPrimitve) { t.rostype = t.Type; SingleType.Finalize(parent, t); return; } t.Finalize(parent, t.input.Split(spliter, StringSplitOptions.RemoveEmptyEntries), false); }
public static SingleType WhatItIs(MsgsFile parent, SingleType t) { foreach (KeyValuePair <string, string> test in KnownTypes) { if (t.Test(test)) { t.rostype = t.Type; return(t.Finalize(parent, test)); } } return(t.Finalize(parent, t.input.Split(spliter, StringSplitOptions.RemoveEmptyEntries), false)); }
public string GenerateSerializationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } if (st.Const) { return(""); } if (!st.IsArray) { return(GenerateSerializationForOne(st.Type, st.Name, st, extraTabs)); } int arraylength = -1; string ret = string.Format(@" {0}//{2} {0}hasmetacomponents |= {1};", leadingWhitespace, st.meta.ToString().ToLower(), st.Name); string completetype = KnownStuff.GetNamespacedType(st); ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[0];", leadingWhitespace, st.Name, completetype); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) { ret += string.Format(@" {0}pieces.Add(BitConverter.GetBytes({1}.Length));", leadingWhitespace, st.Name); } //special case arrays of bytes if (st.Type == "byte") { ret += string.Format(@" {0}pieces.Add(({2}[]){1});", leadingWhitespace, st.Name, st.Type); } else { if (!st.IsPrimitve || (st.Type == "string") || (st.Type == "bool")) { ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateSerializationForOne(st.Type, st.Name + "[i]", st, extraTabs + 1)); } else { ret += GenerateSerializationForOne(st.Type, st.Name + "[i]", st, extraTabs + 1, true); } } return(ret); }
public string GenerateRandomizationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" string pt = KnownStuff.GetNamespacedType(st); if (st.Const) { return(""); } else if (!st.IsArray) { return(GenerateRandomizationCodeForOne(st.Type, st.Name, st, extraTabs)); } string ret = string.Format(@" {0}//{1}", leadingWhitespace, st.Name); int arraylength = -1; string arraylengthstr = "arraylength"; //If the object is an array, send each object to be processed individually, then add them to the string //handle fixed length fields? if (!string.IsNullOrEmpty(st.length) && int.TryParse(st.length, out arraylength) && arraylength != -1) { arraylengthstr = "" + arraylength; } else { ret += string.Format(@" {0}arraylength = rand.Next(10);", leadingWhitespace); } ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[{3}]; {0}else {0} Array.Resize(ref {1}, {3});", leadingWhitespace, st.Name, pt, arraylengthstr); ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateRandomizationCodeForOne(pt, st.Name + "[i]", st, extraTabs + 1)); return(ret); }
public static SingleType WhatItIs(MsgFile parent, string s, string extraindent) { string[] pieces = s.Split('/'); string package = null; if (pieces.Length == 2) { package = pieces[0]; s = pieces[1]; } SingleType st = new SingleType(package, s, extraindent); parent.resolve(st); WhatItIs(parent, st); return st; }
public static void Finalize(MsgFile parent, SingleType thing) { string[] parts = thing.input.Split(' '); thing.rostype = parts[0]; if (!KnownStuff.KnownTypes.ContainsKey(thing.rostype)) { thing.meta = true; } else { parts[0] = KnownStuff.KnownTypes[thing.rostype]; } thing.Finalize(parent, parts, true); }
MsgsFile(string filename, bool isrequest, List <string> lines, string extraindent) { if (resolver == null) { resolver = new Dictionary <string, List <string> >(); } serviceMessageType = isrequest ? ServiceMessageType.Request : ServiceMessageType.Response; filename = filename.Replace(".srv", ".msg"); if (!filename.Contains(".msg")) { throw new Exception("" + filename + " IS NOT A VALID SRV FILE!"); } string[] sp = filename.Replace(Program.inputdir, "").Replace(".msg", "").Split('\\'); classname = sp[sp.Length - 1]; Namespace += "." + filename.Replace(Program.inputdir, "").Replace(".msg", ""); Namespace = Namespace.Replace("\\", ".").Replace("..", "."); string[] sp2 = Namespace.Split('.'); Namespace = ""; for (int i = 0; i < sp2.Length - 2; i++) { Namespace += sp2[i] + "."; } Namespace += sp2[sp2.Length - 2]; //THIS IS BAD! classname = classname.Replace("/", "."); Name = Namespace.Replace("Messages", "").TrimStart('.') + "." + classname; Name = Name.TrimStart('.'); classname = Name.Split('.').Length > 1 ? Name.Split('.')[1] : Name; classname += (isrequest ? "Request" : "Response"); Namespace = Namespace.Trim('.'); def = new List <string>(); for (int i = 0; i < lines.Count; i++) { if (lines[i].Trim().Length == 0) { continue; } def.Add(lines[i]); if (Name.ToLower() == "string") { lines[i].Replace("String", "string"); } SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent); if (test != null) { Stuff.Add(test); } } }
public static string Generate(SingleType members) { return(String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7})", members.Name, members.IsLiteral.ToString().ToLower(), ("typeof(" + members.Type + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower())); }
public static KeyValuePair <string, MsgFieldInfo> Instantiate(SingleType member) { string mt = "xamla/unknown"; if (member.meta) { string t = member.Type.Replace("Messages.", ""); if (!t.Contains('.')) { t = "std_msgs." + t; } mt = t.Replace(".", "/"); } return(new KeyValuePair <string, MsgFieldInfo>(member.Name, new MsgFieldInfo(member.Name, member.IsLiteral, member.Type, member.Static, member.StaticValue, member.IsArray, member.length, member.meta))); }
public void ParseAndResolveTypes() { def = new List <string>(); Stuff = new List <SingleType>(); foreach (var l in lines) { if (string.IsNullOrWhiteSpace(l)) { continue; } def.Add(l); SingleType test = KnownStuff.WhatItIs(this, l, extraindent); if (test != null) { Stuff.Add(test); } } }
public static string Generate(SingleType members) { string mt = "xamla/unknown"; string pt = KnownStuff.GetNamespacedType(members); if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) { if (members.Definer != null) { t = members.Definer.Package + "." + t; } else { t = null; } } if (t != null) { mt = t.Replace(".", "/"); } else { members.meta = false; } } return(String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name.Replace("@", ""), members.IsLiteral.ToString().ToLower(), ("typeof(" + pt + ")"), members.Static.ToString().ToLower(), members.StaticValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.StaticValue+")") : ("\""+members.StaticValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt)); }
public static void Resolve(MsgFile parent, SingleType st) { if (st.Type == null) { KnownStuff.WhatItIs(parent, st); } if (st.IsPrimitve) { return; } List <string> prefixes = new List <string>(new[] { "", "std_msgs", "geometry_msgs", "actionlib_msgs" }); if (st.Type.Contains("/")) { string[] pieces = st.Type.Split('/'); st.Package = pieces[0]; st.Type = pieces[1]; } prefixes[0] = !string.IsNullOrEmpty(st.Package) ? st.Package : parent.Package; foreach (string p in prefixes) { if (resolver.Keys.Contains(p)) { if (resolver[p].ContainsKey(st.Type)) { if (resolver[p][st.Type].Count == 1) { st.Package = p; st.Definer = resolver[p][st.Type][0].Definer; } else if (resolver[p][st.Type].Count > 1) { throw new ArgumentException($"Could not resolve: {st.Type}"); } } } } }
public string GenerateEqualityCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } if (st.IsArray) { return(string.Format(@" {0}if ({1}.Length != other.{1}.Length) {0} return false; {0}for (int __i__=0; __i__ < {1}.Length; __i__++) {0}{{{2} {0}}}", leadingWhitespace, st.Name, GenerateEqualityCodeForOne(st.Type, st.Name + "[__i__]", st, extraTabs + 1))); } else { return(GenerateEqualityCodeForOne(st.Type, st.Name, st, extraTabs)); } }
public string GetSrvHalf() { string wholename = classname.Replace("Request", ".Request").Replace("Response", ".Response"); classname = classname.Contains("Request") ? "Request" : "Response"; if (memoizedcontent == null) { memoizedcontent = ""; for (int i = 0; i < Stuff.Count; i++) { SingleType thisthing = Stuff[i]; if (thisthing.Type == "Header") { HasHeader = true; } else if (classname == "String") { thisthing.input = thisthing.input.Replace("String", "string"); thisthing.Type = thisthing.Type.Replace("String", "string"); thisthing.output = thisthing.output.Replace("String", "string"); } else if (classname == "Time") { thisthing.input = thisthing.input.Replace("Time", "TimeData"); thisthing.Type = thisthing.Type.Replace("Time", "TimeData"); thisthing.output = thisthing.output.Replace("Time", "TimeData"); } else if (classname == "Duration") { thisthing.input = thisthing.input.Replace("Duration", "TimeData"); thisthing.Type = thisthing.Type.Replace("Duration", "TimeData"); thisthing.output = thisthing.output.Replace("Duration", "TimeData"); } meta |= thisthing.meta; memoizedcontent += "\t" + thisthing.output + "\n"; } if (classname.ToLower() == "string") { memoizedcontent += "\n\n\t\t\t\t\tpublic String(string s){ data = s; }\n\t\t\t\t\tpublic String(){ data = \"\"; }\n\n"; } else if (classname == "Time") { memoizedcontent += "\n\n\t\t\t\t\tpublic Time(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Time(TimeData s){ data = s; }\n\t\t\t\t\tpublic Time() : this(0,0){}\n\n"; } else if (classname == "Duration") { memoizedcontent += "\n\n\t\t\t\t\tpublic Duration(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Duration(TimeData s){ data = s; }\n\t\t\t\t\tpublic Duration() : this(0,0){}\n\n"; } while (memoizedcontent.Contains("DataData")) { memoizedcontent = memoizedcontent.Replace("DataData", "Data"); } } string ns = Namespace.Replace("Messages.", ""); if (ns == "Messages") { ns = ""; } GeneratedDictHelper = ""; foreach (SingleType S in Stuff) { GeneratedDictHelper += MessageFieldHelper.Generate(S); } GUTS = fronthalf + memoizedcontent + "\n" + backhalf; return(GUTS); }
private string GenerateSerializationForOne(string type, string name, SingleType st) { if (type == "Time" || type == "Duration") { return string.Format(@"pieces.Add(BitConverter.GetBytes({0}.data.sec)); pieces.Add(BitConverter.GetBytes({0}.data.nsec));", name); } else if (type == "TimeData") return string.Format(@"pieces.Add(BitConverter.GetBytes({0}.sec)); pieces.Add(BitConverter.GetBytes({0}.nsec));", name); else if (type == "byte") { return string.Format("pieces.Add(new[] {{ (byte){0} }});", name); ; } else if (type == "string") { return string.Format(@" if ({0} == null) {0} = """"; scratch1 = Encoding.ASCII.GetBytes((string){0}); thischunk = new byte[scratch1.Length + 4]; scratch2 = BitConverter.GetBytes(scratch1.Length); Array.Copy(scratch1, 0, thischunk, 4, scratch1.Length); Array.Copy(scratch2, thischunk, 4); pieces.Add(thischunk);", name); } else if (type == "bool") { return string.Format(@" thischunk = new byte[1]; thischunk[0] = (byte) ((bool){0} ? 1 : 0 ); pieces.Add(thischunk);", name); } else if (st.IsLiteral) { string ret = string.Format(@" scratch1 = new byte[Marshal.SizeOf(typeof({1}))]; h = GCHandle.Alloc(scratch1, GCHandleType.Pinned); Marshal.StructureToPtr({0}, h.AddrOfPinnedObject(), false); h.Free(); pieces.Add(scratch1);", name, type); return ret; } else { return string.Format("pieces.Add({0}.Serialize(true));", name); } }
private string GenerateSerializationForOne(string type, string name, SingleType st, int extraTabs=0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; type = KnownStuff.GetNamespacedType(st, type); if (type == "Time" || type == "Duration") { return string.Format(@" {0}//{1} {0}pieces.Add(BitConverter.GetBytes({1}.data.sec)); {0}pieces.Add(BitConverter.GetBytes({1}.data.nsec));", leadingWhitespace, name); } else if (type == "TimeData") return string.Format(@" {0}//{1} {0}pieces.Add(BitConverter.GetBytes({1}.sec)); {0}pieces.Add(BitConverter.GetBytes({1}.nsec));", leadingWhitespace, name); else if (type == "byte") { return string.Format(@" {0}//{1} {0}pieces.Add(new[] {{ (byte){1} }});", leadingWhitespace, name); ; } else if (type == "string") { return string.Format(@" {0}//{1} {0}if ({1} == null) {0} {1} = """"; {0}scratch1 = Encoding.ASCII.GetBytes((string){1}); {0}thischunk = new byte[scratch1.Length + 4]; {0}scratch2 = BitConverter.GetBytes(scratch1.Length); {0}Array.Copy(scratch1, 0, thischunk, 4, scratch1.Length); {0}Array.Copy(scratch2, thischunk, 4); {0}pieces.Add(thischunk);", leadingWhitespace, name); } else if (type == "bool") { return string.Format(@" {0}//{1} {0}thischunk = new byte[1]; {0}thischunk[0] = (byte) ((bool){1} ? 1 : 0 ); {0}pieces.Add(thischunk);", leadingWhitespace, name); } else if (st.IsLiteral) { return string.Format(@" {0}//{1} {0}scratch1 = new byte[Marshal.SizeOf(typeof({2}))]; {0}h = GCHandle.Alloc(scratch1, GCHandleType.Pinned); {0}Marshal.StructureToPtr({1}, h.AddrOfPinnedObject(), false); {0}h.Free(); {0}pieces.Add(scratch1);", leadingWhitespace, name, type); } else { return string.Format(@" {0}//{1} {0}if ({1} == null) {0} {1} = new {2}(); {0}pieces.Add({1}.Serialize(true));", leadingWhitespace, name, type); } }
public string GenerateDeserializationCode(SingleType st) { // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" System.Diagnostics.Debug.WriteLine(string.Format(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta)); if (st.Const) { return ""; } else if (!st.IsArray) { return GenerateDeserializationForOne(st.Type, st.Name, st); } int arraylength = -1; //If the object is an array, send each object to be processed individually, then add them to the string string ret = string.Format(@"hasmetacomponents |= {0};" + @" ", st.meta.ToString().ToLower()); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) { ret += string.Format(@" arraylength = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0} = new {1}[arraylength]; ", st.Name, st.Type); } else { ret += string.Format(@" {0} = new {1}[{2}]; ", st.Name, st.Type, arraylength); } ret += string.Format(@"for (int i=0;i<{0}.Length; i++) {{ {1} }}" + @" ", st.Name, GenerateDeserializationForOne(st.Type, st.Name + "[i]", st)); return ret; }
private string GenerateDeserializationForOne(string type, string name, SingleType st) { if (type == "Time" || type == "Duration") { return string.Format(@" {0} = new {1}(new TimeData( BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex), BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex+Marshal.SizeOf(typeof(System.Int32))))); currentIndex += 2*Marshal.SizeOf(typeof(System.Int32));", name, st.Type); } else if (type == "TimeData") return string.Format(@" {0}.sec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0}.nsec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32));", name); else if (type == "byte") { return string.Format("{0}=SERIALIZEDSTUFF[currentIndex++];", name); ; } else if (type == "string") { return string.Format(@" {0} = """"; piecesize = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += 4; {0} = Encoding.ASCII.GetString(SERIALIZEDSTUFF, currentIndex, piecesize); currentIndex += piecesize;", name); } else if (type == "bool") { return string.Format(@" {0} = SERIALIZEDSTUFF[currentIndex++]==1; ", name); } else if (st.IsLiteral) { string ret = string.Format(@" piecesize = Marshal.SizeOf(typeof({0})); h = IntPtr.Zero; if (SERIALIZEDSTUFF.Length - currentIndex != 0) {{ h = Marshal.AllocHGlobal(piecesize); Marshal.Copy(SERIALIZEDSTUFF, currentIndex, h, piecesize); }} if (h == IntPtr.Zero) throw new Exception(""Alloc failed""); {1} = ({0})Marshal.PtrToStructure(h, typeof({0})); Marshal.FreeHGlobal(h); currentIndex+= piecesize; ", st.Type, name); return ret; } else { return string.Format("{0} = new {1}(SERIALIZEDSTUFF, ref currentIndex);", name, st.Type); } }
public string GenerateDeserializationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" string pt = KnownStuff.GetNamespacedType(st); if (st.Const) { return(""); } else if (!st.IsArray) { return(GenerateDeserializationForOne(st.Type, st.Name, st, extraTabs)); } string ret = string.Format(@" {0}//{2} {0}hasmetacomponents |= {1};", leadingWhitespace, st.meta.ToString().ToLower(), st.Name); int arraylength = -1; string arraylengthstr = "arraylength"; //If the object is an array, send each object to be processed individually, then add them to the string //handle fixed length fields? if (!string.IsNullOrEmpty(st.length) && int.TryParse(st.length, out arraylength) && arraylength != -1) { arraylengthstr = "" + arraylength; } else { ret += string.Format(@" {0}arraylength = BitConverter.ToInt32(serializedMessage, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace); } ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[{3}]; {0}else {0} Array.Resize(ref {1}, {3});", leadingWhitespace, st.Name, pt, arraylengthstr); //special case arrays of bytes if (st.Type == "byte") { ret += string.Format(@" {0}Array.Copy(serializedMessage, currentIndex, {1}, 0, {1}.Length); {0}currentIndex += {1}.Length;", leadingWhitespace, st.Name); } else { if (!st.IsPrimitve || (st.Type == "string") || (st.Type == "bool")) { ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateDeserializationForOne(pt, st.Name + "[i]", st, extraTabs + 1)); } else { ret += GenerateDeserializationForOne(pt, st.Name + "[i]", st, extraTabs + 1, true); } } return(ret); }
private string GenerateSerializationForOne(string type, string name, SingleType st, int extraTabs = 0, bool special = false) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } type = KnownStuff.GetNamespacedType(st, type); if (type == "Time" || type == "Duration") { return(string.Format(@" {0}//{1} {0}pieces.Add(BitConverter.GetBytes({1}.data.sec)); {0}pieces.Add(BitConverter.GetBytes({1}.data.nsec));", leadingWhitespace, name)); } else if (type == "TimeData") { return(string.Format(@" {0}//{1} {0}pieces.Add(BitConverter.GetBytes({1}.sec)); {0}pieces.Add(BitConverter.GetBytes({1}.nsec));", leadingWhitespace, name)); } else if (type == "byte") { return(string.Format(@" {0}//{1} {0}pieces.Add(new[] {{ (byte){1} }});", leadingWhitespace, name));; } else if (type == "string") { return(string.Format(@" {0}//{1} {0}if ({1} == null) {0} {1} = """"; {0}scratch1 = Encoding.ASCII.GetBytes((string){1}); {0}thischunk = new byte[scratch1.Length + 4]; {0}scratch2 = BitConverter.GetBytes(scratch1.Length); {0}Array.Copy(scratch1, 0, thischunk, 4, scratch1.Length); {0}Array.Copy(scratch2, thischunk, 4); {0}pieces.Add(thischunk);", leadingWhitespace, name)); } else if (type == "bool") { return(string.Format(@" {0}//{1} {0}thischunk = new byte[1]; {0}thischunk[0] = (byte) ((bool){1} ? 1 : 0 ); {0}pieces.Add(thischunk);", leadingWhitespace, name)); } else if (st.IsLiteral && !special) { return(string.Format(@" {0}//{1} {0}scratch1 = new byte[Marshal.SizeOf(typeof({2}))]; {0}h = GCHandle.Alloc(scratch1, GCHandleType.Pinned); {0}Marshal.StructureToPtr({1}, h.AddrOfPinnedObject(), false); {0}h.Free(); {0}pieces.Add(scratch1);", leadingWhitespace, name, type)); } else if (st.IsLiteral && special) { return(string.Format(@" // Start Xamla {0}//{1} {0}x__size = Marshal.SizeOf(typeof({2})) * {1}.Length; {0}scratch1 = new byte[x__size]; {0}Buffer.BlockCopy({1}, 0, scratch1, 0, x__size); {0}pieces.Add(scratch1); // End Xamla ", leadingWhitespace, name.Substring(0, name.Length - 3), type)); } else { return(string.Format(@" {0}//{1} {0}if ({1} == null) {0} {1} = new {2}(); {0}pieces.Add({1}.Serialize(true));", leadingWhitespace, name, type)); } }
public string GenerateDeserializationCode(SingleType st) { //Console.WriteLine(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta); //if (!st.IsLiteral) // Console.WriteLine(st.Name); return ""; }
public static bool IsPrimitiveType(SingleType st) { return(st.Package == null && KnownTypes.ContainsKey(st.rostype) && st.rostype != "duration" && st.rostype != "time"); }
public static void Finalize(MsgsFile parent, SingleType thing, KeyValuePair<string, string> csharptype) { string[] PARTS = thing.input.Split(' '); thing.rostype = PARTS[0]; if (!KnownStuff.KnownTypes.ContainsKey(thing.rostype)) thing.meta = true; PARTS[0] = csharptype.Value; thing.Finalize(parent, PARTS, true); }
public static string Generate(SingleType members) { string mt = "MsgTypes.Unknown"; string pt = KnownStuff.GetNamespacedType(members); if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) if (members.Definer != null) t = members.Definer.Package + "." + t; else { t = null; } if (t != null) mt = "MsgTypes." + t.Replace(".", "__"); else members.meta = false; } return String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name.Replace("@", ""), members.IsLiteral.ToString().ToLower(), ("typeof(" + pt + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt); }
private string GenerateRandomizationCodeForOne(string type, string name, SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; string pt = KnownStuff.GetNamespacedType(st); if (type == "Time" || type == "Duration") { return string.Format(@" {0}//{1} {0}{1} = new {2}(new TimeData( {0} Convert.ToUInt32(rand.Next()), {0} Convert.ToUInt32(rand.Next())));", leadingWhitespace, name, pt); } else if (type == "TimeData") return string.Format(@" {0}//{1} {0}{1}.sec = Convert.ToUInt32(rand.Next()); {0}{1}.nsec = Convert.ToUInt32(rand.Next());", leadingWhitespace, name); else if (type == "byte") { return string.Format(@" {0}//{1} {0}myByte = new byte[1]; {0}rand.NextBytes(myByte); {0}{1}= myByte[0];", leadingWhitespace, name); } else if (type == "string") { return string.Format(@" {0}//{1} {0}strlength = rand.Next(100) + 1; {0}strbuf = new byte[strlength]; {0}rand.NextBytes(strbuf); //fill the whole buffer with random bytes {0}for (int __x__ = 0; __x__ < strlength; __x__++) {0} if (strbuf[__x__] == 0) //replace null chars with non-null random ones {0} strbuf[__x__] = (byte)(rand.Next(254) + 1); {0}strbuf[strlength - 1] = 0; //null terminate {0}{1} = Encoding.ASCII.GetString(strbuf);", leadingWhitespace, name); } else if (type == "bool") { return string.Format(@" {0}//{1} {0}{1} = rand.Next(2) == 1;", leadingWhitespace, name); } else if (type == "int") { return string.Format(@" {0}//{1} {0}{1} = rand.Next();", leadingWhitespace, name); } else if (type == "uint") { return string.Format(@" {0}//{1} {0}{1} = (uint)rand.Next();", leadingWhitespace, name); } else if (type == "double") { return string.Format(@" {0}//{1} {0}{1} = (rand.Next() + rand.NextDouble());", leadingWhitespace, name); } else if (type == "float" || type == "Float64" || type == "Single") { return string.Format(@" {0}//{1} {0}{1} = (float)(rand.Next() + rand.NextDouble());", leadingWhitespace, name); } else if (type == "Int16" || type == "Short" || type == "short") { return string.Format(@" {0}//{1} {0}{1} = (System.Int16)rand.Next(System.Int16.MaxValue + 1);", leadingWhitespace, name); } else if (type == "UInt16" || type == "ushort" || type == "UShort") { return string.Format(@" {0}//{1} {0}{1} = (System.UInt16)rand.Next(System.UInt16.MaxValue + 1);", leadingWhitespace, name); } else if (type == "SByte" || type == "sbyte") { return string.Format(@" {0}//{1} {0}{1} = (SByte)(rand.Next(255) - 127);", leadingWhitespace, name); } else if (type == "UInt64" || type == "ULong" || type == "ulong") { return string.Format(@" {0}//{1} {0}{1} = (System.UInt64)((uint)(rand.Next() << 32)) | (uint)rand.Next();", leadingWhitespace, name); } else if (type == "Int64" || type == "Long" || type == "long") { return string.Format(@" {0}//{1} {0}{1} = (System.Int64)(rand.Next() << 32) | rand.Next();", leadingWhitespace, name); } else if (type == "char") { return string.Format(@" {0}//{1} {0}{1} = (char)(byte)(rand.Next(254) + 1);", leadingWhitespace, name); } else if (st.IsLiteral) { throw new Exception(st.Type + " needs to be handled SPECIFICALLY!"); } else { return string.Format(@" {0}//{1} {0}{1} = new {2}(); {0}{1}.Randomize();", leadingWhitespace, name, pt); } }
public string GenerateRandomizationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" string pt = KnownStuff.GetNamespacedType(st); if (st.Const) { return ""; } else if (!st.IsArray) { return GenerateRandomizationCodeForOne(st.Type, st.Name, st, extraTabs); } string ret = string.Format(@" {0}//{1}", leadingWhitespace, st.Name); int arraylength = -1; string arraylengthstr = "arraylength"; //If the object is an array, send each object to be processed individually, then add them to the string //handle fixed length fields? if (!string.IsNullOrEmpty(st.length) && int.TryParse(st.length, out arraylength) && arraylength != -1) { arraylengthstr = "" + arraylength; } else { ret += string.Format(@" {0}arraylength = rand.Next(10);", leadingWhitespace); } ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[{3}]; {0}else {0} Array.Resize(ref {1}, {3});", leadingWhitespace, st.Name, pt, arraylengthstr); ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateRandomizationCodeForOne(pt, st.Name + "[i]", st, extraTabs + 1)); return ret; }
private string GenerateDeserializationForOne(string type, string name, SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; string pt = KnownStuff.GetNamespacedType(st); if (type == "Time" || type == "Duration") { return string.Format(@" {0}//{1} {0}{1} = new {2}(new TimeData( {0} BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex), {0} BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex+Marshal.SizeOf(typeof(System.Int32))))); {0}currentIndex += 2*Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace, name, pt); } else if (type == "TimeData") return string.Format(@" {0}//{1} {0}{1}.sec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0}{1}.nsec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace, name); else if (type == "byte") { return string.Format(@" {0}//{1} {0}{1}=SERIALIZEDSTUFF[currentIndex++];", leadingWhitespace, name); } else if (type == "string") { return string.Format(@" {0}//{1} {0}{1} = """"; {0}piecesize = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); {0}currentIndex += 4; {0}{1} = Encoding.ASCII.GetString(SERIALIZEDSTUFF, currentIndex, piecesize); {0}currentIndex += piecesize;", leadingWhitespace, name); } else if (type == "bool") { return string.Format(@" {0}//{1} {0}{1} = SERIALIZEDSTUFF[currentIndex++]==1;", leadingWhitespace, name); } else if (st.IsLiteral) { string ret = string.Format(@" {0}//{2} {0}piecesize = Marshal.SizeOf(typeof({1})); {0}h = IntPtr.Zero; {0}if (SERIALIZEDSTUFF.Length - currentIndex != 0) {0}{{ {0} h = Marshal.AllocHGlobal(piecesize); {0} Marshal.Copy(SERIALIZEDSTUFF, currentIndex, h, piecesize); {0}}} {0}if (h == IntPtr.Zero) throw new Exception(""Alloc failed""); {0}{2} = ({1})Marshal.PtrToStructure(h, typeof({1})); {0}Marshal.FreeHGlobal(h); {0}currentIndex+= piecesize;", leadingWhitespace, pt, name); return ret; } else { return string.Format(@" {0}//{1} {0}{1} = new {2}(SERIALIZEDSTUFF, ref currentIndex);", leadingWhitespace, name, pt); } }
public override string ToString() { if (fronthalf == null) { fronthalf = ""; backhalf = ""; string[] lines = Templates.MsgPlaceHolder.Split('\n'); bool hitvariablehole = false; for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("$$DOLLADOLLABILLS")) { hitvariablehole = true; continue; } if (lines[i].Contains("namespace")) { fronthalf += "using Messages.std_msgs;\nusing String=System.String;\n\n" ; fronthalf += "namespace " + Namespace + "\n"; continue; } if (!hitvariablehole) { fronthalf += lines[i] + "\n"; } else { backhalf += lines[i] + "\n"; } } } string GeneratedDeserializationCode = "", GeneratedSerializationCode = "", GeneratedRandomizationCode = "", GeneratedEqualityCode = ""; if (memoizedcontent == null) { memoizedcontent = ""; for (int i = 0; i < Stuff.Count; i++) { SingleType thisthing = Stuff[i]; if (thisthing.Type == "Header") { HasHeader = true; } else if (classname == "Time") { thisthing.input = thisthing.input.Replace("Time", "TimeData"); thisthing.Type = thisthing.Type.Replace("Time", "TimeData"); thisthing.output = thisthing.output.Replace("Time", "TimeData"); } else if (classname == "Duration") { thisthing.input = thisthing.input.Replace("Duration", "TimeData"); thisthing.Type = thisthing.Type.Replace("Duration", "TimeData"); thisthing.output = thisthing.output.Replace("Duration", "TimeData"); } thisthing.input = thisthing.input.Replace("String", "string"); thisthing.Type = thisthing.Type.Replace("String", "string"); thisthing.output = thisthing.output.Replace("String", "string"); meta |= thisthing.meta; memoizedcontent += "\t" + thisthing.output + "\n"; } string ns = Namespace.Replace("Messages.", ""); if (ns == "Messages") { ns = ""; } while (memoizedcontent.Contains("DataData")) { memoizedcontent = memoizedcontent.Replace("DataData", "Data"); } //if (GeneratedDictHelper == null) // GeneratedDictHelper = TypeInfo.Generate(classname, ns, HasHeader, meta, def, Stuff); GeneratedDictHelper = GenFields(); StringBuilder DEF = new StringBuilder(); foreach (string s in def) { DEF.AppendLine(s); } } GUTS = (serviceMessageType != ServiceMessageType.Response ? fronthalf : "") + "\n" + memoizedcontent + "\n" + (serviceMessageType != ServiceMessageType.Request ? backhalf : ""); if (classname.ToLower() == "string") { GUTS = GUTS.Replace("$NULLCONSTBODY", "if (data == null)\n\t\t\tdata = \"\";\n"); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(string d)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } else if (classname == "Time" || classname == "Duration") { GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(TimeData d)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } GUTS = GUTS.Replace("$WHATAMI", classname); GUTS = GUTS.Replace("$MYISMETA", meta.ToString().ToLower()); GUTS = GUTS.Replace("$MYMSGTYPE", Namespace.Replace("Messages.", "") + "/" + classname); for (int i = 0; i < def.Count; i++) { while (def[i].Contains("\t")) { def[i] = def[i].Replace("\t", " "); } while (def[i].Contains("\n\n")) { def[i] = def[i].Replace("\n\n", "\n"); } def[i] = def[i].Replace('\t', ' '); while (def[i].Contains(" ")) { def[i] = def[i].Replace(" ", " "); } def[i] = def[i].Replace(" = ", "="); } GUTS = GUTS.Replace("$MYMESSAGEDEFINITION", "@\"" + def.Aggregate("", (current, d) => current + (d + "\n")).Trim('\n').Replace("\"", "\"\"") + "\""); GUTS = GUTS.Replace("$MYHASHEADER", HasHeader.ToString().ToLower()); GUTS = GUTS.Replace("$MYFIELDS", GeneratedDictHelper.Length > 5 ? "{{" + GeneratedDictHelper + "}}" : "()"); GUTS = GUTS.Replace("$NULLCONSTBODY", ""); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", ""); string md5 = MD5.Sum(this); if (md5 == null) { return(null); } GeneratedEqualityCode += string.Format(@"var other = ____other as Messages.{0}; if (other == null) return false;", Name); for (int i = 0; i < Stuff.Count; i++) { GeneratedDeserializationCode += this.GenerateDeserializationCode(Stuff[i]); GeneratedSerializationCode += this.GenerateSerializationCode(Stuff[i]); GeneratedRandomizationCode += this.GenerateRandomizationCode(Stuff[i]); GeneratedEqualityCode += this.GenerateEqualityCode(Stuff[i]); } GUTS = GUTS.Replace("$SERIALIZATIONCODE", GeneratedSerializationCode); GUTS = GUTS.Replace("$DESERIALIZATIONCODE", GeneratedDeserializationCode); GUTS = GUTS.Replace("$RANDOMIZATIONCODE", GeneratedRandomizationCode); GUTS = GUTS.Replace("$EQUALITYCODE", GeneratedEqualityCode); GUTS = GUTS.Replace("$MYMD5SUM", md5); return(GUTS); }
public static SingleType WhatItIs(MsgsFile parent, string s, string extraindent) { string[] pieces = s.Split('/'); string package = parent.Package; if (pieces.Length == 2) { package = pieces[0]; s = pieces[1]; } SingleType st = new SingleType(package, s, extraindent); parent.resolve(parent, st); WhatItIs(parent, st); return st; }
public string GenerateEqualityCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; if (st.IsArray) { return string.Format(@" {0}if ({1}.Length != other.{1}.Length) {0} return false; {0}for (int __i__=0; __i__ < {1}.Length; __i__++) {0}{{{2} {0}}}", leadingWhitespace, st.Name, GenerateEqualityCodeForOne(st.Type, st.Name + "[__i__]", st, extraTabs + 1)); } else return GenerateEqualityCodeForOne(st.Type, st.Name, st, extraTabs); }
public static string Generate(SingleType members) { string mt = "MsgTypes.Unknown"; if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) t = "std_msgs." + t; mt = "MsgTypes." + t.Replace(".", "__"); if (mt.Contains("ColorRGBA")) Console.WriteLine(mt); } return String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name, members.IsLiteral.ToString().ToLower(), ("typeof(" + members.Type + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt); }
private string GenerateDeserializationForOne(string type, string name, SingleType st, int extraTabs = 0, bool special = false) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } string pt = KnownStuff.GetNamespacedType(st); if (type == "Time" || type == "Duration") { return(string.Format(@" {0}//{1} {0}{1} = new {2}(new TimeData( {0} BitConverter.ToUInt32(serializedMessage, currentIndex), {0} BitConverter.ToUInt32(serializedMessage, currentIndex+Marshal.SizeOf(typeof(System.Int32))))); {0}currentIndex += 2*Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace, name, pt)); } else if (type == "TimeData") { return(string.Format(@" {0}//{1} {0}{1}.sec = BitConverter.ToUInt32(serializedMessage, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0}{1}.nsec = BitConverter.ToUInt32(serializedMessage, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace, name)); } else if (type == "byte") { return(string.Format(@" {0}//{1} {0}{1}=serializedMessage[currentIndex++];", leadingWhitespace, name)); } else if (type == "string") { return(string.Format(@" {0}//{1} {0}{1} = """"; {0}piecesize = BitConverter.ToInt32(serializedMessage, currentIndex); {0}currentIndex += 4; {0}{1} = Encoding.ASCII.GetString(serializedMessage, currentIndex, piecesize); {0}currentIndex += piecesize;", leadingWhitespace, name)); } else if (type == "bool") { return(string.Format(@" {0}//{1} {0}{1} = serializedMessage[currentIndex++]==1;", leadingWhitespace, name)); } else if (st.IsLiteral && !special) { string ret = string.Format(@" {0}//{2} {0}piecesize = Marshal.SizeOf(typeof({1})); {0}h = IntPtr.Zero; {0}if (serializedMessage.Length - currentIndex != 0) {0}{{ {0} h = Marshal.AllocHGlobal(piecesize); {0} Marshal.Copy(serializedMessage, currentIndex, h, piecesize); {0}}} {0}if (h == IntPtr.Zero) throw new Exception(""Memory allocation failed""); {0}{2} = ({1})Marshal.PtrToStructure(h, typeof({1})); {0}Marshal.FreeHGlobal(h); {0}currentIndex+= piecesize;", leadingWhitespace, pt, name); return(ret); } else if (st.IsLiteral && special) { string ret = string.Format(@" // Start Xamla {0}//{2} {0}piecesize = Marshal.SizeOf(typeof({1})) * {2}.Length; {0}if (currentIndex + piecesize > serializedMessage.Length) {{ {0} throw new Exception(""Memory allocation failed: Ran out of bytes to read.""); {0}}} {0}Buffer.BlockCopy(serializedMessage, currentIndex, {2}, 0, piecesize); {0}currentIndex += piecesize; // End Xamla ", leadingWhitespace, pt, name.Substring(0, name.Length - 3)); return(ret); } else { return(string.Format(@" {0}//{1} {0}{1} = new {2}(serializedMessage, ref currentIndex);", leadingWhitespace, name, pt)); } }
/// <summary> /// Returns the namespaced type name (if neccessary) /// </summary> /// <param name="st">This thing's SingleType</param> /// <param name="type">(optional) the type string</param> /// <returns>duh</returns> public static string GetNamespacedType(SingleType st, string type = null) { if (type == null) type = st.Type; if (!KnownTypes.ContainsKey(st.rostype) && !type.Contains(st.Package) && !STATIC_NAMESPACE_STRING.Contains("Messages." + st.Package)) return string.Format("Messages.{0}.{1}", st.Package, type); return type; }
private string GenerateRandomizationCodeForOne(string type, string name, SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) { leadingWhitespace += " "; } string pt = KnownStuff.GetNamespacedType(st); if (type == "Time" || type == "Duration") { return(string.Format(@" {0}//{1} {0}{1} = new {2}(new TimeData( {0} Convert.ToUInt32(rand.Next()), {0} Convert.ToUInt32(rand.Next())));", leadingWhitespace, name, pt)); } else if (type == "TimeData") { return(string.Format(@" {0}//{1} {0}{1}.sec = Convert.ToUInt32(rand.Next()); {0}{1}.nsec = Convert.ToUInt32(rand.Next());", leadingWhitespace, name)); } else if (type == "byte") { return(string.Format(@" {0}//{1} {0}myByte = new byte[1]; {0}rand.NextBytes(myByte); {0}{1}= myByte[0];", leadingWhitespace, name)); } else if (type == "string") { return(string.Format(@" {0}//{1} {0}strlength = rand.Next(100) + 1; {0}strbuf = new byte[strlength]; {0}rand.NextBytes(strbuf); //fill the whole buffer with random bytes {0}for (int __x__ = 0; __x__ < strlength; __x__++) {0} if (strbuf[__x__] == 0) //replace null chars with non-null random ones {0} strbuf[__x__] = (byte)(rand.Next(254) + 1); {0}strbuf[strlength - 1] = 0; //null terminate {0}{1} = Encoding.ASCII.GetString(strbuf);", leadingWhitespace, name)); } else if (type == "bool") { return(string.Format(@" {0}//{1} {0}{1} = rand.Next(2) == 1;", leadingWhitespace, name)); } else if (type == "int") { return(string.Format(@" {0}//{1} {0}{1} = rand.Next();", leadingWhitespace, name)); } else if (type == "uint") { return(string.Format(@" {0}//{1} {0}{1} = (uint)rand.Next();", leadingWhitespace, name)); } else if (type == "double") { return(string.Format(@" {0}//{1} {0}{1} = (rand.Next() + rand.NextDouble());", leadingWhitespace, name)); } else if (type == "float" || type == "Float64" || type == "Single") { return(string.Format(@" {0}//{1} {0}{1} = (float)(rand.Next() + rand.NextDouble());", leadingWhitespace, name)); } else if (type == "Int16" || type == "Short" || type == "short") { return(string.Format(@" {0}//{1} {0}{1} = (System.Int16)rand.Next(System.Int16.MaxValue + 1);", leadingWhitespace, name)); } else if (type == "UInt16" || type == "ushort" || type == "UShort") { return(string.Format(@" {0}//{1} {0}{1} = (System.UInt16)rand.Next(System.UInt16.MaxValue + 1);", leadingWhitespace, name)); } else if (type == "SByte" || type == "sbyte") { return(string.Format(@" {0}//{1} {0}{1} = (SByte)(rand.Next(255) - 127);", leadingWhitespace, name)); } else if (type == "UInt64" || type == "ULong" || type == "ulong") { return(string.Format(@" {0}//{1} {0}{1} = (System.UInt64)((uint)(rand.Next() << 32)) | (uint)rand.Next();", leadingWhitespace, name)); } else if (type == "Int64" || type == "Long" || type == "long") { return(string.Format(@" {0}//{1} {0}{1} = (System.Int64)(rand.Next() << 32) | rand.Next();", leadingWhitespace, name)); } else if (type == "char") { return(string.Format(@" {0}//{1} {0}{1} = (char)(byte)(rand.Next(254) + 1);", leadingWhitespace, name)); } else if (st.IsLiteral) { throw new ArgumentException($"{st.Type} is not supported"); } else { return(string.Format(@" {0}//{1} {0}{1} = new {2}(); {0}{1}.Randomize();", leadingWhitespace, name, pt)); } }
private string GenerateEqualityCodeForOne(string type, string name, SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; if (type == "Time" || type == "Duration") return string.Format(@" {0}ret &= {1}.data.Equals(other.{1}.data);", leadingWhitespace, name); else if (type == "TimeData") return string.Format(@" {0}ret &= {1}.Equals(other.{1});", leadingWhitespace, name); else if (st.IsLiteral) { if (st.Const) return ""; return string.Format(@" {0}ret &= {1} == other.{1};", leadingWhitespace, name); } else return string.Format(@" {0}ret &= {1}.Equals(other.{1});", leadingWhitespace, name); // and that's it }
public string GenerateSerializationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; if (st.Const) return ""; if (!st.IsArray) { return GenerateSerializationForOne(st.Type, st.Name, st, extraTabs); } int arraylength = -1; string ret = string.Format(@" {0}//{2} {0}hasmetacomponents |= {1};", leadingWhitespace, st.meta.ToString().ToLower(), st.Name); string completetype = KnownStuff.GetNamespacedType(st); ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[0];", leadingWhitespace, st.Name, completetype); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) { ret += string.Format(@" {0}pieces.Add(BitConverter.GetBytes({1}.Length));", leadingWhitespace, st.Name); } //special case arrays of bytes if (st.Type == "byte") { ret += string.Format(@" {0}pieces.Add(({2}[]){1});", leadingWhitespace, st.Name, st.Type); } else { ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateSerializationForOne(st.Type, st.Name + "[i]", st, extraTabs + 1)); } return ret; }
public static string Generate(SingleType members) { string mt = "MsgTypes.Unknown"; string pt = members.Type; if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) t = members.Definer.Package + "." + t; mt = "MsgTypes." + t.Replace(".", "__"); } if (!KnownStuff.KnownTypes.ContainsKey(members.rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages." + members.Package)) { pt = "Messages." + members.Package + "." + pt; } return String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name, members.IsLiteral.ToString().ToLower(), ("typeof(" + pt + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt); }
public string GenerateSerializationCode(SingleType st) { System.Diagnostics.Debug.WriteLine(string.Format(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta)); if (st.Const) return ""; if (!st.IsArray) { return GenerateSerializationForOne(st.Type, st.Name, st); } int arraylength = -1; //TODO: if orientation_covariance does not send successfully, skip prepending length when array length is coded in .msg string ret = string.Format(@"hasmetacomponents |= {0};" + @" ", st.meta.ToString().ToLower()); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) ret += "pieces.Add( BitConverter.GetBytes(" + st.Name + ".Length));" + @" "; ret += string.Format(@"for (int i=0;i<{0}.Length; i++) {{ {1} }}" + @" ", st.Name, GenerateSerializationForOne(st.Type, st.Name + "[i]", st)); return ret; }
public void resolve(MsgsFile parent, SingleType st) { if (st.Type == null) { KnownStuff.WhatItIs(parent, st); } List<string> prefixes = new List<string>(new[] { "", "std_msgs", "geometry_msgs", "actionlib_msgs"}); if (st.Type.Contains("/")) { string[] pieces = st.Type.Split('/'); st.Package = pieces[0]; st.Type = pieces[1]; } if (!string.IsNullOrEmpty(st.Package)) prefixes[0] = st.Package; foreach (string p in prefixes) { if (resolver.Keys.Contains(p)) { if (resolver[p].ContainsKey(st.Type)) { if (resolver[p][st.Type].Count == 1) { st.Package = p; st.Definer = resolver[p][st.Type][0].Definer; } else if (resolver[p][st.Type].Count>1) throw new Exception("Could not resolve " + st.Type); } } } }
public MsgsFile(string filename, string extraindent) { if (resolver == null) { resolver = new Dictionary <string, List <string> >(); } if (!filename.Contains(".msg")) { throw new Exception("" + filename + " IS NOT A VALID MSG FILE!"); } string[] sp = filename.Replace(Program.inputdir, "").Replace(".msg", "").Split('\\'); classname = sp[sp.Length - 1]; Namespace += "." + filename.Replace(Program.inputdir, "").Replace(".msg", ""); Namespace = Namespace.Replace("\\", ".").Replace("..", "."); string[] sp2 = Namespace.Split('.'); Namespace = ""; for (int i = 0; i < sp2.Length - 2; i++) { Namespace += sp2[i] + "."; } Namespace += sp2[sp2.Length - 2]; //THIS IS BAD! classname = classname.Replace("/", "."); Name = Namespace.Replace("Messages", "").TrimStart('.') + "." + classname; Name = Name.TrimStart('.'); classname = Name.Split('.').Length > 1 ? Name.Split('.')[1] : Name; Namespace = Namespace.Trim('.'); if (!resolver.Keys.Contains(classname) && Namespace != "Messages.std_msgs") { resolver.Add(classname, new List <string> { Namespace + "." + classname }); } else if (Namespace != "Messages.std_msgs") { resolver[classname].Add(Namespace + "." + classname); } List <string> lines = new List <string>(File.ReadAllLines(filename)); lines = lines.Where(st => (!st.Contains('#') || st.Split('#')[0].Length != 0)).ToList(); for (int i = 0; i < lines.Count; i++) { lines[i] = lines[i].Split('#')[0].Trim(); } //lines = lines.Where((st) => (st.Length > 0)).ToList(); lines.ForEach(s => { if (s.Contains('#') && s.Split('#')[0].Length != 0) { s = s.Split('#')[0]; } if (s.Contains('#')) { s = ""; } }); lines = lines.Where(st => (st.Length > 0)).ToList(); def = new List <string>(); for (int i = 0; i < lines.Count; i++) { def.Add(lines[i]); if (Name.ToLower() == "string") { lines[i].Replace("String", "string"); } SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent); if (test != null) { Stuff.Add(test); } } }
public void resolve(SingleType st) { Resolve(this, st); }
public override string ToString() { bool wasnull = false; if (fronthalf == null) { wasnull = true; fronthalf = ""; backhalf = ""; string[] lines = File.ReadAllLines("TemplateProject\\PlaceHolder._cs"); bool hitvariablehole = false; for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("$$DOLLADOLLABILLS")) { hitvariablehole = true; continue; } if (lines[i].Contains("namespace")) { fronthalf += "using Messages.std_msgs;using String=Messages.std_msgs.String;\n\n"; //\nusing Messages.roscsharp; fronthalf += "namespace " + Namespace + "\n"; continue; } if (!hitvariablehole) { fronthalf += lines[i] + "\n"; } else { backhalf += lines[i] + "\n"; } } } if (memoizedcontent == null) { memoizedcontent = ""; for (int i = 0; i < Stuff.Count; i++) { SingleType thisthing = Stuff[i]; if (thisthing.Type == "Header") { HasHeader = true; } else if (classname == "String") { thisthing.input = thisthing.input.Replace("String", "string"); thisthing.Type = thisthing.Type.Replace("String", "string"); thisthing.output = thisthing.output.Replace("String", "string"); } else if (classname == "Time") { thisthing.input = thisthing.input.Replace("Time", "TimeData"); thisthing.Type = thisthing.Type.Replace("Time", "TimeData"); thisthing.output = thisthing.output.Replace("Time", "TimeData"); } else if (classname == "Duration") { thisthing.input = thisthing.input.Replace("Duration", "TimeData"); thisthing.Type = thisthing.Type.Replace("Duration", "TimeData"); thisthing.output = thisthing.output.Replace("Duration", "TimeData"); } meta |= thisthing.meta; memoizedcontent += "\t" + thisthing.output + "\n"; } string ns = Namespace.Replace("Messages.", ""); if (ns == "Messages") { ns = ""; } while (memoizedcontent.Contains("DataData")) { memoizedcontent = memoizedcontent.Replace("DataData", "Data"); } //if (GeneratedDictHelper == null) // GeneratedDictHelper = TypeInfo.Generate(classname, ns, HasHeader, meta, def, Stuff); GeneratedDictHelper = GenFields(); string GeneratedDeserializationCode = ""; bool literal = false; StringBuilder DEF = new StringBuilder(); foreach (string s in def) { DEF.AppendLine(s); } if (!meta && Stuff.Count == 1 && Stuff[0].Name == "data") { Console.WriteLine(DEF); } for (int i = 0; i < Stuff.Count; i++) { GeneratedDeserializationCode += GenerateDeserializationCode(Stuff[i]); } } GUTS = (serviceMessageType != ServiceMessageType.Response ? fronthalf : "") + "\n" + memoizedcontent + "\n" + (serviceMessageType != ServiceMessageType.Request ? backhalf : ""); if (classname.ToLower() == "string") { GUTS = GUTS.Replace("$NULLCONSTBODY", "if (data == null)\n\t\t\tdata = \"\";\n"); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(string d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } else if (classname == "Time" || classname == "Duration") { GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(TimeData d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } GUTS = GUTS.Replace("$WHATAMI", classname); GUTS = GUTS.Replace("$MYISMETA", meta.ToString().ToLower()); GUTS = GUTS.Replace("$MYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname); for (int i = 0; i < def.Count; i++) { while (def[i].Contains("\t")) { def[i] = def[i].Replace("\t", " "); } while (def[i].Contains("\n\n")) { def[i] = def[i].Replace("\n\n", "\n"); } def[i] = def[i].Replace('\t', ' '); while (def[i].Contains(" ")) { def[i] = def[i].Replace(" ", " "); } def[i] = def[i].Replace(" = ", "="); } GUTS = GUTS.Replace("$MYMESSAGEDEFINITION", "@\"" + def.Aggregate("", (current, d) => current + (d + "\n")).Trim('\n') + "\""); GUTS = GUTS.Replace("$MYHASHEADER", HasHeader.ToString().ToLower()); GUTS = GUTS.Replace("$MYFIELDS", GeneratedDictHelper.Length > 5 ? "{{" + GeneratedDictHelper + "}}" : "()"); GUTS = GUTS.Replace("$NULLCONSTBODY", ""); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", ""); return(GUTS); }
public string GenerateDeserializationCode(SingleType st, int extraTabs = 0) { string leadingWhitespace = ""; for (int i = 0; i < LEADING_WHITESPACE + extraTabs; i++) leadingWhitespace += " "; // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" string pt = KnownStuff.GetNamespacedType(st); if(st.Const) { return ""; } else if(!st.IsArray) { return GenerateDeserializationForOne(st.Type, st.Name, st, extraTabs); } string ret = string.Format(@" {0}//{2} {0}hasmetacomponents |= {1};", leadingWhitespace, st.meta.ToString().ToLower(), st.Name); int arraylength = -1; string arraylengthstr = "arraylength"; //If the object is an array, send each object to be processed individually, then add them to the string //handle fixed length fields? if (!string.IsNullOrEmpty(st.length) && int.TryParse(st.length, out arraylength) && arraylength != -1) { arraylengthstr = "" + arraylength; } else { ret += string.Format(@" {0}arraylength = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); {0}currentIndex += Marshal.SizeOf(typeof(System.Int32));", leadingWhitespace); } ret += string.Format(@" {0}if ({1} == null) {0} {1} = new {2}[{3}]; {0}else {0} Array.Resize(ref {1}, {3});", leadingWhitespace, st.Name, pt, arraylengthstr); //special case arrays of bytes if (st.Type == "byte") { ret += string.Format(@" {0}Array.Copy(SERIALIZEDSTUFF, currentIndex, {1}, 0, {1}.Length); {0}currentIndex += {1}.Length;", leadingWhitespace, st.Name); } else { ret += string.Format(@" {0}for (int i=0;i<{1}.Length; i++) {{{2} {0}}}", leadingWhitespace, st.Name, GenerateDeserializationForOne(pt, st.Name + "[i]", st, extraTabs + 1)); } return ret; }
public static SingleType WhatItIs(MsgsFile parent, SingleType t) { foreach (KeyValuePair<string, string> test in KnownTypes) { if (t.Test(test)) { t.rostype = t.Type; return t.Finalize(parent, test); } } return t.Finalize(parent, t.input.Split(spliter, StringSplitOptions.RemoveEmptyEntries), false); }
public static KeyValuePair<string, MsgFieldInfo> Instantiate(SingleType member) { string mt = "MsgTypes.Unknown"; if (member.meta) { string t = member.Type.Replace("Messages.", ""); if (!t.Contains('.')) t = "std_msgs." + t; mt = "MsgType." + t.Replace(".", "__"); } return new KeyValuePair<string, MsgFieldInfo>(member.Name, new MsgFieldInfo(member.Name, member.IsLiteral, member.Type, member.Const, member.ConstValue, member.IsArray, member.length, member.meta)); }