Compiler.cs 29 KB

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