LSL2CSConverter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Text.RegularExpressions;
  31. namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
  32. {
  33. public class LSL2CSConverter
  34. {
  35. // Uses regex to convert LSL code to C# code.
  36. //private Regex rnw = new Regex(@"[a-zA-Z0-9_\-]", RegexOptions.Compiled);
  37. private Dictionary<string, string> dataTypes = new Dictionary<string, string>();
  38. private Dictionary<string, string> quotes = new Dictionary<string, string>();
  39. // c Style
  40. private Regex cstylecomments = new Regex(@"/\*(.|[\r\n])*?\*/", RegexOptions.Compiled | RegexOptions.Multiline);
  41. // c# one liners
  42. private Regex nonCommentFwsl = new Regex("\"[a-zA-Z0-9.,:/\\n ]+//[^\"+]+([\\\\\\\"+]+)?(\\s+)?[\"+](\\s+)?(;)?", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  43. private Regex conelinecomments = new Regex(@"[^:].?([\/]{2}[^\n]*)|([\n]{1,}[\/]{2}[^\n]*)", RegexOptions.Compiled | RegexOptions.Multiline);
  44. // ([^\"])((?:[a-zA-Z])\.[a-zA-Z].?)([^\"])
  45. // value we're looking for: (?:[a-zA-Z])\.[a-zA-Z]
  46. public LSL2CSConverter()
  47. {
  48. // Only the types we need to convert
  49. dataTypes.Add("void", "void");
  50. dataTypes.Add("integer", "LSL_Types.LSLInteger");
  51. dataTypes.Add("float", "LSL_Types.LSLFloat");
  52. dataTypes.Add("string", "LSL_Types.LSLString");
  53. dataTypes.Add("key", "LSL_Types.LSLString");
  54. dataTypes.Add("vector", "LSL_Types.Vector3");
  55. dataTypes.Add("rotation", "LSL_Types.Quaternion");
  56. dataTypes.Add("list", "LSL_Types.list");
  57. dataTypes.Add("null", "null");
  58. }
  59. public string Convert(string Script)
  60. {
  61. quotes.Clear();
  62. string Return = String.Empty;
  63. Script = " \r\n" + Script;
  64. //
  65. // Prepare script for processing
  66. //
  67. // Clean up linebreaks
  68. Script = Regex.Replace(Script, @"\r\n", "\n");
  69. Script = Regex.Replace(Script, @"\n", "\r\n");
  70. // QUOTE REPLACEMENT
  71. // temporarily replace quotes so we can work our magic on the script without
  72. // always considering if we are inside our outside quotes's
  73. // TODO: Does this work on half-quotes in strings? ;)
  74. string _Script = String.Empty;
  75. string C;
  76. bool in_quote = false;
  77. bool quote_replaced = false;
  78. string quote_replacement_string = "Q_U_O_T_E_REPLACEMENT_";
  79. string quote = String.Empty;
  80. bool last_was_escape = false;
  81. int quote_replaced_count = 0;
  82. string removefwnoncomments = nonCommentFwsl.Replace(Script, "\"\";");
  83. string removecomments = conelinecomments.Replace(removefwnoncomments, "");
  84. removecomments = cstylecomments.Replace(removecomments, "");
  85. string[] localscript = removecomments.Split('"');
  86. string checkscript = String.Empty;
  87. bool flip = true;
  88. for (int p = 0; p < localscript.Length; p++)
  89. {
  90. //if (localscript[p].Length >= 1)
  91. //{
  92. if (!localscript[p].EndsWith(@"\"))
  93. {
  94. flip = !flip;
  95. //System.Console.WriteLine("Flip:" + flip.ToString() + " - " + localscript[p] + " ! " + localscript[p].EndsWith(@"\").ToString());
  96. }
  97. //}
  98. //else
  99. //{
  100. // flip = !flip;
  101. // System.Console.WriteLine("Flip:" + flip.ToString() + " - " + localscript[p]);
  102. //}
  103. if (!flip)
  104. checkscript += localscript[p];
  105. }
  106. //System.Console.WriteLine("SCRIPT:" + checkscript);
  107. // checks for alpha.alpha way of referring to objects in C#
  108. // ignores alpha.x alpha.y, alpha.z for refering to vector components
  109. Match SecurityM;
  110. // BROKEN: this check is very wrong. It block's any url in strings.
  111. SecurityM = Regex.Match(checkscript, @"(?:[a-zA-Z])\.(?:[a-wA-Z]|[a-zA-Z][a-zA-Z])", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  112. if (SecurityM.Success)
  113. throw new Exception("CS0103: 'The . symbol cannot be used in LSL except in float values or vector components'. Detected around: " + SecurityM.Captures[0].Value);
  114. SecurityM = Regex.Match(checkscript, @"typeof\s", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  115. if (SecurityM.Success)
  116. throw new Exception("CS0103: 'The object.typeof method isn't allowed in LSL'");
  117. SecurityM = Regex.Match(checkscript, @"GetType\(", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  118. if (SecurityM.Success)
  119. throw new Exception("CS0103: 'The object.GetType method isn't allowed in LSL'");
  120. for (int p = 0; p < Script.Length; p++)
  121. {
  122. C = Script.Substring(p, 1);
  123. while (true)
  124. {
  125. // found " and last was not \ so this is not an escaped \"
  126. if (C == "\"" && last_was_escape == false)
  127. {
  128. // Toggle inside/outside quote
  129. in_quote = !in_quote;
  130. if (in_quote)
  131. {
  132. quote_replaced_count++;
  133. }
  134. else
  135. {
  136. if (quote == String.Empty)
  137. {
  138. // We didn't replace quote, probably because of empty string?
  139. _Script += quote_replacement_string +
  140. quote_replaced_count.ToString().PadLeft(5, "0".ToCharArray()[0]);
  141. }
  142. // We just left a quote
  143. quotes.Add(
  144. quote_replacement_string +
  145. quote_replaced_count.ToString().PadLeft(5, "0".ToCharArray()[0]), quote);
  146. quote = String.Empty;
  147. }
  148. break;
  149. }
  150. if (!in_quote)
  151. {
  152. // We are not inside a quote
  153. quote_replaced = false;
  154. }
  155. else
  156. {
  157. // We are inside a quote
  158. if (!quote_replaced)
  159. {
  160. // Replace quote
  161. _Script += quote_replacement_string +
  162. quote_replaced_count.ToString().PadLeft(5, "0".ToCharArray()[0]);
  163. quote_replaced = true;
  164. }
  165. quote += C;
  166. break;
  167. }
  168. _Script += C;
  169. break;
  170. }
  171. last_was_escape = false;
  172. if (C == @"\")
  173. {
  174. last_was_escape = true;
  175. }
  176. }
  177. Script = _Script;
  178. //
  179. // END OF QUOTE REPLACEMENT
  180. //
  181. //
  182. // PROCESS STATES
  183. // Remove state definitions and add state names to start of each event within state
  184. //
  185. int ilevel = 0;
  186. int lastlevel = 0;
  187. string ret = String.Empty;
  188. string cache = String.Empty;
  189. bool in_state = false;
  190. string current_statename = String.Empty;
  191. for (int p = 0; p < Script.Length; p++)
  192. {
  193. C = Script.Substring(p, 1);
  194. while (true)
  195. {
  196. // inc / dec level
  197. if (C == @"{")
  198. ilevel++;
  199. if (C == @"}")
  200. ilevel--;
  201. if (ilevel < 0)
  202. ilevel = 0;
  203. cache += C;
  204. // if level == 0, add to return
  205. if (ilevel == 1 && lastlevel == 0)
  206. {
  207. // 0 => 1: Get last
  208. Match m =
  209. //Regex.Match(cache, @"(?![a-zA-Z_]+)\s*([a-zA-Z_]+)[^a-zA-Z_\(\)]*{",
  210. Regex.Match(cache, @"(?![a-zA-Z_]+)\s*(state\s+)?(?<statename>[a-zA-Z_][a-zA-Z_0-9]*)[^a-zA-Z_0-9\(\)]*{",
  211. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  212. in_state = false;
  213. if (m.Success)
  214. {
  215. // Go back to level 0, this is not a state
  216. in_state = true;
  217. current_statename = m.Groups["statename"].Captures[0].Value;
  218. //Console.WriteLine("Current statename: " + current_statename);
  219. cache =
  220. //@"(?<s1>(?![a-zA-Z_]+)\s*)" + @"([a-zA-Z_]+)(?<s2>[^a-zA-Z_\(\)]*){",
  221. Regex.Replace(cache,
  222. @"(?<s1>(?![a-zA-Z_]+)\s*)" + @"(state\s+)?([a-zA-Z_][a-zA-Z_0-9]*)(?<s2>[^a-zA-Z_0-9\(\)]*){",
  223. "${s1}${s2}",
  224. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  225. }
  226. ret += cache;
  227. cache = String.Empty;
  228. }
  229. if (ilevel == 0 && lastlevel == 1)
  230. {
  231. // 1 => 0: Remove last }
  232. if (in_state == true)
  233. {
  234. cache = cache.Remove(cache.Length - 1, 1);
  235. //cache = Regex.Replace(cache, "}$", String.Empty, RegexOptions.Multiline | RegexOptions.Singleline);
  236. //Replace function names
  237. // void dataserver(key query_id, string data) {
  238. //cache = Regex.Replace(cache, @"([^a-zA-Z_]\s*)((?!if|switch|for)[a-zA-Z_]+\s*\([^\)]*\)[^{]*{)", "$1" + "<STATE>" + "$2", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  239. //Console.WriteLine("Replacing using statename: " + current_statename);
  240. cache =
  241. Regex.Replace(cache,
  242. @"^(\s*)((?!(if|switch|for|while)[^a-zA-Z0-9_])[a-zA-Z0-9_]*\s*\([^\)]*\)[^;]*\{)",
  243. @"$1public " + current_statename + "_event_$2",
  244. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  245. }
  246. ret += cache;
  247. cache = String.Empty;
  248. in_state = true;
  249. current_statename = String.Empty;
  250. }
  251. break;
  252. }
  253. lastlevel = ilevel;
  254. }
  255. ret += cache;
  256. cache = String.Empty;
  257. Script = ret;
  258. ret = String.Empty;
  259. foreach (string key in dataTypes.Keys)
  260. {
  261. string val;
  262. dataTypes.TryGetValue(key, out val);
  263. // Replace CAST - (integer) with (int)
  264. Script =
  265. Regex.Replace(Script, @"\(" + key + @"\)", @"(" + val + ")",
  266. RegexOptions.Compiled | RegexOptions.Multiline);
  267. // Replace return types and function variables - integer a() and f(integer a, integer a)
  268. Script =
  269. Regex.Replace(Script, @"(^|;|}|[\(,])(\s*)" + key + @"(\s+)", @"$1$2" + val + "$3",
  270. RegexOptions.Compiled | RegexOptions.Multiline);
  271. Script =
  272. Regex.Replace(Script, @"(^|;|}|[\(,])(\s*)" + key + @"(\s*)[,]", @"$1$2" + val + "$3,",
  273. RegexOptions.Compiled | RegexOptions.Multiline);
  274. }
  275. // Change jumps into goto's and prefix its label
  276. Script =
  277. Regex.Replace(Script,
  278. @"(\W)jump\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*;",
  279. @"$1goto label_$2;", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  280. // and prefix labels so the do not clash with C#'s reserved words
  281. Script =
  282. Regex.Replace(Script,
  283. @"@([a-zA-Z_][a-zA-Z_0-9]*)\s*;",
  284. @"label_$1: ;", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  285. // Add "void" in front of functions that needs it
  286. Script =
  287. Regex.Replace(Script,
  288. @"^(\s*public\s+)?((?!(if|switch|for)[^a-zA-Z0-9_])[a-zA-Z0-9_]*\s*\([^\)]*\)[^;]*\{)",
  289. @"$1void $2", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  290. // Replace <x,y,z> and <x,y,z,r>
  291. Script =
  292. Regex.Replace(Script, @"<([^,>;]*,[^,>;]*,[^,>;]*,[^,>;]*)>", @"new LSL_Types.Quaternion($1)",
  293. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  294. Script =
  295. Regex.Replace(Script, @"<([^,>;)]*,[^,>;]*,[^,>;]*)>", @"new LSL_Types.Vector3($1)",
  296. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  297. // Replace List []'s
  298. Script =
  299. Regex.Replace(Script, @"\[([^\]]*)\]", @"new LSL_Types.list($1)",
  300. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  301. // Replace (string) to .ToString() //
  302. Script =
  303. Regex.Replace(Script, @"\(string\)\s*([a-zA-Z0-9_.]+(\s*\([^\)]*\))?)", @"$1.ToString()",
  304. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  305. Script =
  306. Regex.Replace(Script, @"\((float|int)\)\s*([a-zA-Z0-9_.]+(\s*\([^\)]*\))?)", @"$1.Parse($2)",
  307. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline);
  308. // Replace "state STATENAME" with "state("statename")"
  309. Script =
  310. Regex.Replace(Script, @"(state)\s+([^;\n\r]+)(;[\r\n\s])", "$1(\"$2\")$3",
  311. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  312. // REPLACE BACK QUOTES
  313. foreach (string key in quotes.Keys)
  314. {
  315. string val;
  316. quotes.TryGetValue(key, out val);
  317. Script = Script.Replace(key, "\"" + val + "\"");
  318. }
  319. //System.Console.WriteLine(Script);
  320. Return = String.Empty;// +
  321. //"using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;";
  322. //Return += String.Empty +
  323. // "namespace SecondLife { ";
  324. //Return += String.Empty +
  325. // //"[Serializable] " +
  326. // "public class Script : OpenSim.Region.ScriptEngine.Shared.LSL_BaseClass { ";
  327. //Return += @"public Script() { } ";
  328. Return += Script;
  329. //Return += "} }\r\n";
  330. quotes.Clear();
  331. return Return;
  332. }
  333. }
  334. }