Compiler.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. using System;
  28. using System.CodeDom.Compiler;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using Microsoft.CSharp;
  33. using Microsoft.JScript;
  34. using Microsoft.VisualBasic;
  35. using OpenSim.Region.Environment.Interfaces;
  36. using OpenSim.Region.ScriptEngine.Interfaces;
  37. namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
  38. {
  39. public class Compiler : ICompiler
  40. {
  41. // private static readonly log4net.ILog m_log
  42. // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  43. // * Uses "LSL2Converter" to convert LSL to C# if necessary.
  44. // * Compiles C#-code into an assembly
  45. // * Returns assembly name ready for AppDomain load.
  46. //
  47. // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
  48. //
  49. internal enum enumCompileType
  50. {
  51. lsl = 0,
  52. cs = 1,
  53. vb = 2,
  54. js = 3,
  55. yp = 4
  56. }
  57. /// <summary>
  58. /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
  59. /// </summary>
  60. public int LinesToRemoveOnError = 3;
  61. private enumCompileType DefaultCompileLanguage;
  62. private bool WriteScriptSourceToDebugFile;
  63. private bool CompileWithDebugInformation;
  64. private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  65. private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  66. private string FilePrefix;
  67. private string ScriptEnginesPath = "ScriptEngines";
  68. private static ICodeConverter LSL_Converter;
  69. private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap; // mapping between LSL and C# line/column numbers
  70. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  71. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  72. private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
  73. private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp
  74. private static YP2CSConverter YP_Converter = new YP2CSConverter();
  75. // private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  76. private static UInt64 scriptCompileCounter = 0; // And a counter
  77. public IScriptEngine m_scriptEngine;
  78. public Compiler(IScriptEngine scriptEngine)
  79. {
  80. m_scriptEngine = scriptEngine;
  81. ReadConfig();
  82. }
  83. public bool in_startup = true;
  84. public void ReadConfig()
  85. {
  86. // Get some config
  87. WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", true);
  88. CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
  89. // Get file prefix from scriptengine name and make it file system safe:
  90. FilePrefix = "CommonCompiler";
  91. foreach (char c in Path.GetInvalidFileNameChars())
  92. {
  93. FilePrefix = FilePrefix.Replace(c, '_');
  94. }
  95. // First time we start? Delete old files
  96. if (in_startup)
  97. {
  98. in_startup = false;
  99. DeleteOldFiles();
  100. }
  101. // Map name and enum type of our supported languages
  102. LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
  103. LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
  104. LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
  105. LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
  106. LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp);
  107. // Allowed compilers
  108. string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
  109. AllowedCompilers.Clear();
  110. #if DEBUG
  111. m_scriptEngine.Log.Debug("[Compiler]: Allowed languages: " + allowComp);
  112. #endif
  113. foreach (string strl in allowComp.Split(','))
  114. {
  115. string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
  116. if (!LanguageMapping.ContainsKey(strlan))
  117. {
  118. m_scriptEngine.Log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  119. }
  120. else
  121. {
  122. #if DEBUG
  123. //m_scriptEngine.Log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  124. #endif
  125. }
  126. AllowedCompilers.Add(strlan, true);
  127. }
  128. if (AllowedCompilers.Count == 0)
  129. m_scriptEngine.Log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
  130. // Default language
  131. string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
  132. // Is this language recognized at all?
  133. if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
  134. {
  135. m_scriptEngine.Log.Error("[Compiler]: " +
  136. "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
  137. defaultCompileLanguage = "lsl";
  138. }
  139. // Is this language in allow-list?
  140. if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
  141. {
  142. m_scriptEngine.Log.Error("[Compiler]: " +
  143. "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
  144. }
  145. else
  146. {
  147. #if DEBUG
  148. // m_scriptEngine.Log.Debug("[Compiler]: " +
  149. // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
  150. #endif
  151. // LANGUAGE IS IN ALLOW-LIST
  152. DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
  153. }
  154. // We now have an allow-list, a mapping list, and a default language
  155. }
  156. /// <summary>
  157. /// Delete old script files
  158. /// </summary>
  159. private void DeleteOldFiles()
  160. {
  161. // CREATE FOLDER IF IT DOESNT EXIST
  162. if (!Directory.Exists(ScriptEnginesPath))
  163. {
  164. try
  165. {
  166. Directory.CreateDirectory(ScriptEnginesPath);
  167. }
  168. catch (Exception ex)
  169. {
  170. m_scriptEngine.Log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
  171. }
  172. }
  173. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  174. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  175. {
  176. try
  177. {
  178. Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
  179. m_scriptEngine.World.RegionInfo.RegionID.ToString()));
  180. }
  181. catch (Exception ex)
  182. {
  183. m_scriptEngine.Log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
  184. m_scriptEngine.World.RegionInfo.RegionID.ToString())+ "\": " + ex.ToString());
  185. }
  186. }
  187. foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
  188. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  189. {
  190. //m_scriptEngine.Log.Error("[Compiler]: FILE FOUND: " + file);
  191. if (file.ToLower().StartsWith(FilePrefix + "_compiled_") ||
  192. file.ToLower().StartsWith(FilePrefix + "_source_"))
  193. {
  194. try
  195. {
  196. File.Delete(file);
  197. }
  198. catch (Exception ex)
  199. {
  200. m_scriptEngine.Log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  201. }
  202. }
  203. }
  204. }
  205. ////private ICodeCompiler icc = codeProvider.CreateCompiler();
  206. //public string CompileFromFile(string LSOFileName)
  207. //{
  208. // switch (Path.GetExtension(LSOFileName).ToLower())
  209. // {
  210. // case ".txt":
  211. // case ".lsl":
  212. // Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
  213. // return CompileFromLSLText(File.ReadAllText(LSOFileName));
  214. // case ".cs":
  215. // Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
  216. // return CompileFromCSText(File.ReadAllText(LSOFileName));
  217. // default:
  218. // throw new Exception("Unknown script type.");
  219. // }
  220. //}
  221. /// <summary>
  222. /// Converts script from LSL to CS and calls CompileFromCSText
  223. /// </summary>
  224. /// <param name="Script">LSL script</param>
  225. /// <returns>Filename to .dll assembly</returns>
  226. public string PerformScriptCompile(string Script, string asset)
  227. {
  228. m_positionMap = null;
  229. string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
  230. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  231. FilePrefix + "_compiled_" + asset + ".dll"));
  232. // string OutFile = Path.Combine(ScriptEnginesPath,
  233. // FilePrefix + "_compiled_" + asset + ".dll");
  234. if (!Directory.Exists(ScriptEnginesPath))
  235. {
  236. try
  237. {
  238. Directory.CreateDirectory(ScriptEnginesPath);
  239. }
  240. catch (Exception)
  241. {
  242. }
  243. }
  244. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  245. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  246. {
  247. try
  248. {
  249. Directory.CreateDirectory(ScriptEnginesPath);
  250. }
  251. catch (Exception)
  252. {
  253. }
  254. }
  255. if (Script == String.Empty)
  256. {
  257. if (File.Exists(OutFile))
  258. {
  259. // m_scriptEngine.Log.DebugFormat("[Compiler] Returning existing assembly for {0}", asset);
  260. return OutFile;
  261. }
  262. throw new Exception("Cannot find script assembly and no script text present");
  263. }
  264. enumCompileType l = DefaultCompileLanguage;
  265. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  266. l = enumCompileType.cs;
  267. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  268. {
  269. l = enumCompileType.vb;
  270. // We need to remove //vb, it won't compile with that
  271. Script = Script.Substring(4, Script.Length - 4);
  272. }
  273. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  274. l = enumCompileType.lsl;
  275. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  276. l = enumCompileType.js;
  277. if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
  278. l = enumCompileType.yp;
  279. if (!AllowedCompilers.ContainsKey(l.ToString()))
  280. {
  281. // Not allowed to compile to this language!
  282. string errtext = String.Empty;
  283. errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  284. throw new Exception(errtext);
  285. }
  286. string compileScript = Script;
  287. if (l == enumCompileType.lsl)
  288. {
  289. // Its LSL, convert it to C#
  290. LSL_Converter = (ICodeConverter)new CSCodeGenerator();
  291. compileScript = LSL_Converter.Convert(Script);
  292. m_positionMap = ((CSCodeGenerator) LSL_Converter).PositionMap;
  293. }
  294. // Check this late so the map is generated on sim start
  295. //
  296. if (File.Exists(OutFile))
  297. {
  298. // m_scriptEngine.Log.DebugFormat("[Compiler] Returning existing assembly for {0}", asset);
  299. return OutFile;
  300. }
  301. if (l == enumCompileType.yp)
  302. {
  303. // Its YP, convert it to C#
  304. compileScript = YP_Converter.Convert(Script);
  305. }
  306. switch (l)
  307. {
  308. case enumCompileType.cs:
  309. case enumCompileType.lsl:
  310. compileScript = CreateCSCompilerScript(compileScript);
  311. break;
  312. case enumCompileType.vb:
  313. compileScript = CreateVBCompilerScript(compileScript);
  314. break;
  315. case enumCompileType.js:
  316. compileScript = CreateJSCompilerScript(compileScript);
  317. break;
  318. case enumCompileType.yp:
  319. compileScript = CreateYPCompilerScript(compileScript);
  320. break;
  321. }
  322. return CompileFromDotNetText(compileScript, l, asset);
  323. }
  324. private static string CreateJSCompilerScript(string compileScript)
  325. {
  326. compileScript = String.Empty +
  327. "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
  328. "package SecondLife {\r\n" +
  329. "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  330. compileScript +
  331. "} }\r\n";
  332. return compileScript;
  333. }
  334. private static string CreateCSCompilerScript(string compileScript)
  335. {
  336. compileScript = String.Empty +
  337. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  338. String.Empty + "namespace SecondLife { " +
  339. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  340. @"public Script() { } " +
  341. compileScript +
  342. "} }\r\n";
  343. return compileScript;
  344. }
  345. private static string CreateYPCompilerScript(string compileScript)
  346. {
  347. compileScript = String.Empty +
  348. "using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " +
  349. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  350. String.Empty + "namespace SecondLife { " +
  351. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  352. //@"public Script() { } " +
  353. @"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " +
  354. @"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " +
  355. compileScript +
  356. "} }\r\n";
  357. return compileScript;
  358. }
  359. private static string CreateVBCompilerScript(string compileScript)
  360. {
  361. compileScript = String.Empty +
  362. "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
  363. String.Empty + "NameSpace SecondLife:" +
  364. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " +
  365. "\r\nPublic Sub New()\r\nEnd Sub: " +
  366. compileScript +
  367. ":End Class :End Namespace\r\n";
  368. return compileScript;
  369. }
  370. /// <summary>
  371. /// Compile .NET script to .Net assembly (.dll)
  372. /// </summary>
  373. /// <param name="Script">CS script</param>
  374. /// <returns>Filename to .dll assembly</returns>
  375. internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset)
  376. {
  377. string ext = "." + lang.ToString();
  378. // Output assembly name
  379. scriptCompileCounter++;
  380. string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
  381. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  382. FilePrefix + "_compiled_" + asset + ".dll"));
  383. try
  384. {
  385. File.Delete(OutFile);
  386. }
  387. catch (Exception e) // NOTLEGIT - Should be just FileIOException
  388. {
  389. throw new Exception("Unable to delete old existing "+
  390. "script-file before writing new. Compile aborted: " +
  391. e.ToString());
  392. }
  393. // DEBUG - write source to disk
  394. if (WriteScriptSourceToDebugFile)
  395. {
  396. string srcFileName = FilePrefix + "_source_" +
  397. Path.GetFileNameWithoutExtension(OutFile) + ext;
  398. try
  399. {
  400. File.WriteAllText(Path.Combine(Path.Combine(
  401. ScriptEnginesPath,
  402. m_scriptEngine.World.RegionInfo.RegionID.ToString()),
  403. srcFileName), Script);
  404. }
  405. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  406. {
  407. m_scriptEngine.Log.Error("[Compiler]: Exception while "+
  408. "trying to write script source to file \"" +
  409. srcFileName + "\": " + ex.ToString());
  410. }
  411. }
  412. // Do actual compile
  413. CompilerParameters parameters = new CompilerParameters();
  414. parameters.IncludeDebugInformation = true;
  415. string rootPath =
  416. Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  417. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  418. "OpenSim.Region.ScriptEngine.Shared.dll"));
  419. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  420. "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
  421. if (lang == enumCompileType.yp)
  422. {
  423. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  424. "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
  425. }
  426. parameters.GenerateExecutable = false;
  427. parameters.OutputAssembly = OutFile;
  428. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  429. //parameters.WarningLevel = 1; // Should be 4?
  430. parameters.TreatWarningsAsErrors = false;
  431. CompilerResults results;
  432. switch (lang)
  433. {
  434. case enumCompileType.vb:
  435. results = VBcodeProvider.CompileAssemblyFromSource(
  436. parameters, Script);
  437. break;
  438. case enumCompileType.cs:
  439. case enumCompileType.lsl:
  440. results = CScodeProvider.CompileAssemblyFromSource(
  441. parameters, Script);
  442. break;
  443. case enumCompileType.js:
  444. results = JScodeProvider.CompileAssemblyFromSource(
  445. parameters, Script);
  446. break;
  447. case enumCompileType.yp:
  448. results = YPcodeProvider.CompileAssemblyFromSource(
  449. parameters, Script);
  450. break;
  451. default:
  452. throw new Exception("Compiler is not able to recongnize "+
  453. "language type \"" + lang.ToString() + "\"");
  454. }
  455. // Check result
  456. // Go through errors
  457. //
  458. // WARNINGS AND ERRORS
  459. //
  460. int display = 5;
  461. if (results.Errors.Count > 0)
  462. {
  463. string errtext = String.Empty;
  464. foreach (CompilerError CompErr in results.Errors)
  465. {
  466. // Show 5 errors max
  467. //
  468. if (display <= 0)
  469. break;
  470. display--;
  471. string severity = "Error";
  472. if ( CompErr.IsWarning )
  473. {
  474. severity = "Warning";
  475. }
  476. KeyValuePair<int, int> lslPos;
  477. lslPos = FindErrorPosition(CompErr.Line, CompErr.Column);
  478. string text = CompErr.ErrorText;
  479. // Use LSL type names
  480. if (lang == enumCompileType.lsl)
  481. text = ReplaceTypes(CompErr.ErrorText);
  482. // The Second Life viewer's script editor begins
  483. // countingn lines and columns at 0, so we subtract 1.
  484. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  485. lslPos.Key - 1, lslPos.Value - 1,
  486. CompErr.ErrorNumber, text, severity);
  487. }
  488. if (!File.Exists(OutFile))
  489. {
  490. throw new Exception(errtext);
  491. }
  492. }
  493. //
  494. // NO ERRORS, BUT NO COMPILED FILE
  495. //
  496. if (!File.Exists(OutFile))
  497. {
  498. string errtext = String.Empty;
  499. errtext += "No compile error. But not able to locate compiled file.";
  500. throw new Exception(errtext);
  501. }
  502. // m_scriptEngine.Log.DebugFormat("[Compiler] Compiled new assembly "+
  503. // "for {0}", asset);
  504. return OutFile;
  505. }
  506. public KeyValuePair<int, int> FindErrorPosition(int line, int col)
  507. {
  508. return FindErrorPosition(line, col, m_positionMap);
  509. }
  510. private class kvpSorter : IComparer<KeyValuePair<int,int>>
  511. {
  512. public int Compare(KeyValuePair<int,int> a,
  513. KeyValuePair<int,int> b)
  514. {
  515. return a.Key.CompareTo(b.Key);
  516. }
  517. }
  518. public static KeyValuePair<int, int> FindErrorPosition(int line,
  519. int col, Dictionary<KeyValuePair<int, int>,
  520. KeyValuePair<int, int>> positionMap)
  521. {
  522. if (positionMap == null || positionMap.Count == 0)
  523. return new KeyValuePair<int, int>(line, col);
  524. KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
  525. if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
  526. out ret))
  527. return ret;
  528. List<KeyValuePair<int,int>> sorted =
  529. new List<KeyValuePair<int,int>>(positionMap.Keys);
  530. sorted.Sort(new kvpSorter());
  531. int l = 1;
  532. int c = 1;
  533. foreach (KeyValuePair<int, int> cspos in sorted)
  534. {
  535. if (cspos.Key >= line)
  536. {
  537. if (cspos.Key > line)
  538. return new KeyValuePair<int, int>(l, c);
  539. if (cspos.Value > col)
  540. return new KeyValuePair<int, int>(l, c);
  541. c = cspos.Value;
  542. if (c == 0)
  543. c++;
  544. }
  545. else
  546. {
  547. l = cspos.Key;
  548. }
  549. }
  550. return new KeyValuePair<int, int>(l, c);
  551. }
  552. string ReplaceTypes(string message)
  553. {
  554. message = message.Replace(
  555. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
  556. "string");
  557. message = message.Replace(
  558. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
  559. "integer");
  560. message = message.Replace(
  561. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
  562. "float");
  563. message = message.Replace(
  564. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
  565. "list");
  566. return message;
  567. }
  568. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
  569. LineMap()
  570. {
  571. if (m_positionMap == null)
  572. return null;
  573. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ret =
  574. new Dictionary<KeyValuePair<int,int>, KeyValuePair<int, int>>();
  575. foreach (KeyValuePair<int, int> kvp in m_positionMap.Keys)
  576. ret.Add(kvp, m_positionMap[kvp]);
  577. return ret;
  578. }
  579. }
  580. }