aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
diff options
context:
space:
mode:
authorlbsa712008-06-24 21:09:49 +0000
committerlbsa712008-06-24 21:09:49 +0000
commit6b7930104bdb845d3b9c085dc04f52b6446f23b1 (patch)
tree05ee45781a455817fa400bb99f30f4d19d4eb1f8 /OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
parentbased on positive feedback on performance of making keys fixed length (diff)
downloadopensim-SC-6b7930104bdb845d3b9c085dc04f52b6446f23b1.zip
opensim-SC-6b7930104bdb845d3b9c085dc04f52b6446f23b1.tar.gz
opensim-SC-6b7930104bdb845d3b9c085dc04f52b6446f23b1.tar.bz2
opensim-SC-6b7930104bdb845d3b9c085dc04f52b6446f23b1.tar.xz
* Applied patch from Melanie, mantis issue #1581 - "Refactor LSL language, api and compiler out of XEngine"
"First stage in a major Script Engine refactor, that will result in the LSL implementaions ebing reconverged. Not there yet, but one major part is done." Thank you, Melanie!
Diffstat (limited to 'OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs')
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs515
1 files changed, 515 insertions, 0 deletions
diff --git a/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
new file mode 100644
index 0000000..2edcee0
--- /dev/null
+++ b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
@@ -0,0 +1,515 @@
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
28using System;
29using System.CodeDom.Compiler;
30using System.Collections.Generic;
31using System.Globalization;
32using System.IO;
33using Microsoft.CSharp;
34using Microsoft.JScript;
35using Microsoft.VisualBasic;
36using OpenSim.Region.Environment.Interfaces;
37using OpenSim.Region.ScriptEngine.Interfaces;
38
39namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
40{
41 public class Compiler
42 {
43 private static readonly log4net.ILog m_log
44 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
45
46 // * Uses "LSL2Converter" to convert LSL to C# if necessary.
47 // * Compiles C#-code into an assembly
48 // * Returns assembly name ready for AppDomain load.
49 //
50 // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
51 //
52
53 internal enum enumCompileType
54 {
55 lsl = 0,
56 cs = 1,
57 vb = 2,
58 js = 3
59 }
60
61 /// <summary>
62 /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
63 /// </summary>
64 public int LinesToRemoveOnError = 3;
65 private enumCompileType DefaultCompileLanguage;
66 private bool WriteScriptSourceToDebugFile;
67 private bool CompileWithDebugInformation;
68 private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
69 private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
70
71 private string FilePrefix;
72 private string ScriptEnginesPath = "ScriptEngines";
73
74 private static LSL2CSConverter LSL_Converter = new LSL2CSConverter();
75 private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
76 private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
77 private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
78
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
82 public IScriptEngine m_scriptEngine;
83 public Compiler(IScriptEngine scriptEngine)
84 {
85 m_scriptEngine = scriptEngine;
86 ReadConfig();
87 }
88 public bool in_startup = true;
89 public void ReadConfig()
90 {
91
92 // Get some config
93 WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", true);
94 CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
95
96 // Get file prefix from scriptengine name and make it file system safe:
97 FilePrefix = "CommonCompiler";
98 foreach (char c in Path.GetInvalidFileNameChars())
99 {
100 FilePrefix = FilePrefix.Replace(c, '_');
101 }
102
103 // First time we start? Delete old files
104 if (in_startup)
105 {
106 in_startup = false;
107 DeleteOldFiles();
108 }
109
110 // Map name and enum type of our supported languages
111 LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
112 LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
113 LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
114 LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
115
116 // Allowed compilers
117 string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl,cs,vb,js");
118 AllowedCompilers.Clear();
119
120#if DEBUG
121 m_scriptEngine.Log.Debug("[Compiler]: Allowed languages: " + allowComp);
122#endif
123
124
125 foreach (string strl in allowComp.Split(','))
126 {
127 string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
128 if (!LanguageMapping.ContainsKey(strlan))
129 {
130 m_scriptEngine.Log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
131 }
132 else
133 {
134#if DEBUG
135 //m_scriptEngine.Log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
136#endif
137 }
138 AllowedCompilers.Add(strlan, true);
139 }
140 if (AllowedCompilers.Count == 0)
141 m_scriptEngine.Log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
142
143 // Default language
144 string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
145
146 // Is this language recognized at all?
147 if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
148 {
149 m_scriptEngine.Log.Error("[Compiler]: " +
150 "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
151 defaultCompileLanguage = "lsl";
152 }
153
154 // Is this language in allow-list?
155 if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
156 {
157 m_scriptEngine.Log.Error("[Compiler]: " +
158 "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
159 }
160 else
161 {
162#if DEBUG
163// m_scriptEngine.Log.Debug("[Compiler]: " +
164// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
165#endif
166 // LANGUAGE IS IN ALLOW-LIST
167 DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
168 }
169
170 // We now have an allow-list, a mapping list, and a default language
171
172 }
173
174 /// <summary>
175 /// Delete old script files
176 /// </summary>
177 private void DeleteOldFiles()
178 {
179
180 // CREATE FOLDER IF IT DOESNT EXIST
181 if (!Directory.Exists(ScriptEnginesPath))
182 {
183 try
184 {
185 Directory.CreateDirectory(ScriptEnginesPath);
186 }
187 catch (Exception ex)
188 {
189 m_scriptEngine.Log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
190 }
191 }
192
193 if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
194 m_scriptEngine.World.RegionInfo.RegionID.ToString())))
195 {
196 try
197 {
198 Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
199 m_scriptEngine.World.RegionInfo.RegionID.ToString()));
200 }
201 catch (Exception ex)
202 {
203 m_scriptEngine.Log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
204 m_scriptEngine.World.RegionInfo.RegionID.ToString())+ "\": " + ex.ToString());
205 }
206 }
207
208 foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
209 m_scriptEngine.World.RegionInfo.RegionID.ToString())))
210 {
211 //m_scriptEngine.Log.Error("[Compiler]: FILE FOUND: " + file);
212
213 if (file.ToLower().StartsWith(FilePrefix + "_compiled_") ||
214 file.ToLower().StartsWith(FilePrefix + "_source_"))
215 {
216 try
217 {
218 File.Delete(file);
219 }
220 catch (Exception ex)
221 {
222 m_scriptEngine.Log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
223 }
224
225 }
226 }
227
228 }
229
230 ////private ICodeCompiler icc = codeProvider.CreateCompiler();
231 //public string CompileFromFile(string LSOFileName)
232 //{
233 // switch (Path.GetExtension(LSOFileName).ToLower())
234 // {
235 // case ".txt":
236 // case ".lsl":
237 // Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
238 // return CompileFromLSLText(File.ReadAllText(LSOFileName));
239 // case ".cs":
240 // Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
241 // return CompileFromCSText(File.ReadAllText(LSOFileName));
242 // default:
243 // throw new Exception("Unknown script type.");
244 // }
245 //}
246
247 /// <summary>
248 /// Converts script from LSL to CS and calls CompileFromCSText
249 /// </summary>
250 /// <param name="Script">LSL script</param>
251 /// <returns>Filename to .dll assembly</returns>
252 public string PerformScriptCompile(string Script, string asset)
253 {
254 string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
255 m_scriptEngine.World.RegionInfo.RegionID.ToString(),
256 FilePrefix + "_compiled_" + asset + ".dll"));
257// string OutFile = Path.Combine(ScriptEnginesPath,
258// FilePrefix + "_compiled_" + asset + ".dll");
259
260 if (File.Exists(OutFile))
261 {
262 m_scriptEngine.Log.DebugFormat("[Compiler] Returning existing assembly for {0}", asset);
263 return OutFile;
264 }
265
266 if (!Directory.Exists(ScriptEnginesPath))
267 {
268 try
269 {
270 Directory.CreateDirectory(ScriptEnginesPath);
271 }
272 catch (Exception ex)
273 {
274 }
275 }
276
277 if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
278 m_scriptEngine.World.RegionInfo.RegionID.ToString())))
279 {
280 try
281 {
282 Directory.CreateDirectory(ScriptEnginesPath);
283 }
284 catch (Exception ex)
285 {
286 }
287 }
288
289 enumCompileType l = DefaultCompileLanguage;
290
291 if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
292 l = enumCompileType.cs;
293 if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
294 {
295 l = enumCompileType.vb;
296 // We need to remove //vb, it won't compile with that
297
298 Script = Script.Substring(4, Script.Length - 4);
299 }
300 if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
301 l = enumCompileType.lsl;
302
303 if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
304 l = enumCompileType.js;
305
306 if (!AllowedCompilers.ContainsKey(l.ToString()))
307 {
308 // Not allowed to compile to this language!
309 string errtext = String.Empty;
310 errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
311 throw new Exception(errtext);
312 }
313
314 string compileScript = Script;
315
316 if (l == enumCompileType.lsl)
317 {
318 // Its LSL, convert it to C#
319 compileScript = LSL_Converter.Convert(Script);
320 l = enumCompileType.cs;
321 }
322
323 // Insert additional assemblies here
324
325 //ADAM: Disabled for the moment until it's working right.
326 bool enableCommanderLSL = false;
327
328 if (enableCommanderLSL == true && l == enumCompileType.cs)
329 {
330 foreach (KeyValuePair<string,
331 ICommander> com
332 in m_scriptEngine.World.GetCommanders())
333 {
334 compileScript = com.Value.GenerateRuntimeAPI() + compileScript;
335 }
336 }
337
338 // End of insert
339
340 switch (l)
341 {
342 case enumCompileType.cs:
343 compileScript = CreateCSCompilerScript(compileScript);
344 break;
345 case enumCompileType.vb:
346 compileScript = CreateVBCompilerScript(compileScript);
347 break;
348 case enumCompileType.js:
349 compileScript = CreateJSCompilerScript(compileScript);
350 break;
351 }
352
353// m_log.Debug("[ScriptEngine.DotNetEngine]: Preparing to compile the following LSL to C# translated code");
354// m_log.Debug("");
355// m_log.Debug(compileScript);
356
357 return CompileFromDotNetText(compileScript, l, asset);
358 }
359
360 private static string CreateJSCompilerScript(string compileScript)
361 {
362 compileScript = String.Empty +
363 "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
364 "package SecondLife {\r\n" +
365 "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
366 compileScript +
367 "} }\r\n";
368 return compileScript;
369 }
370
371 private static string CreateCSCompilerScript(string compileScript)
372 {
373 compileScript = String.Empty +
374 "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
375 String.Empty + "namespace SecondLife { " +
376 String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
377 @"public Script() { } " +
378 compileScript +
379 "} }\r\n";
380 return compileScript;
381 }
382
383 private static string CreateVBCompilerScript(string compileScript)
384 {
385 compileScript = String.Empty +
386 "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
387 String.Empty + "NameSpace SecondLife:" +
388 String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " +
389 "\r\nPublic Sub New()\r\nEnd Sub: " +
390 compileScript +
391 ":End Class :End Namespace\r\n";
392 return compileScript;
393 }
394
395 /// <summary>
396 /// Compile .NET script to .Net assembly (.dll)
397 /// </summary>
398 /// <param name="Script">CS script</param>
399 /// <returns>Filename to .dll assembly</returns>
400 internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset)
401 {
402 string ext = "." + lang.ToString();
403
404 // Output assembly name
405 scriptCompileCounter++;
406 string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
407 m_scriptEngine.World.RegionInfo.RegionID.ToString(),
408 FilePrefix + "_compiled_" + asset + ".dll"));
409#if DEBUG
410// m_scriptEngine.Log.Debug("[Compiler]: Starting compile of \"" + OutFile + "\".");
411#endif
412 try
413 {
414 File.Delete(OutFile);
415 }
416 catch (Exception e) // NOTLEGIT - Should be just catching FileIOException
417 {
418 //m_scriptEngine.Log.Error("[Compiler]: Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
419 throw new Exception("Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
420 }
421 //string OutFile = Path.Combine("ScriptEngines", "SecondLife.Script.dll");
422
423 // DEBUG - write source to disk
424 if (WriteScriptSourceToDebugFile)
425 {
426 string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(OutFile) + ext;
427 try
428 {
429 File.WriteAllText(Path.Combine(Path.Combine(
430 ScriptEnginesPath,
431 m_scriptEngine.World.RegionInfo.RegionID.ToString()),
432 srcFileName), Script);
433 }
434 catch (Exception ex) // NOTLEGIT - Should be just catching FileIOException
435 {
436 m_scriptEngine.Log.Error("[Compiler]: Exception while trying to write script source to file \"" + srcFileName + "\": " + ex.ToString());
437 }
438 }
439
440 // Do actual compile
441 CompilerParameters parameters = new CompilerParameters();
442
443 parameters.IncludeDebugInformation = true;
444
445 // Add all available assemblies
446// foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
447// {
448// Console.WriteLine("Adding assembly: " + asm.Location);
449// parameters.ReferencedAssemblies.Add(asm.Location);
450// }
451
452 string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
453 string rootPathSE = Path.GetDirectoryName(GetType().Assembly.Location);
454 //Console.WriteLine("Assembly location: " + rootPath);
455 parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll"));
456 parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
457
458 parameters.GenerateExecutable = false;
459 parameters.OutputAssembly = OutFile;
460 parameters.IncludeDebugInformation = CompileWithDebugInformation;
461 //parameters.WarningLevel = 1; // Should be 4?
462 parameters.TreatWarningsAsErrors = false;
463
464//Console.WriteLine(Script);
465 CompilerResults results;
466 switch (lang)
467 {
468 case enumCompileType.vb:
469 results = VBcodeProvider.CompileAssemblyFromSource(parameters, Script);
470 break;
471 case enumCompileType.cs:
472 results = CScodeProvider.CompileAssemblyFromSource(parameters, Script);
473 break;
474 case enumCompileType.js:
475 results = JScodeProvider.CompileAssemblyFromSource(parameters, Script);
476 break;
477 default:
478 throw new Exception("Compiler is not able to recongnize language type \"" + lang.ToString() + "\"");
479 }
480
481 // Check result
482 // Go through errors
483
484 //
485 // WARNINGS AND ERRORS
486 //
487 if (results.Errors.Count > 0)
488 {
489 string errtext = String.Empty;
490 foreach (CompilerError CompErr in results.Errors)
491 {
492 errtext += "Line number " + (CompErr.Line - LinesToRemoveOnError) +
493 ", Error Number: " + CompErr.ErrorNumber +
494 ", '" + CompErr.ErrorText + "'\r\n";
495 }
496 if (!File.Exists(OutFile))
497 {
498 throw new Exception(errtext);
499 }
500 }
501
502 //
503 // NO ERRORS, BUT NO COMPILED FILE
504 //
505 if (!File.Exists(OutFile))
506 {
507 string errtext = String.Empty;
508 errtext += "No compile error. But not able to locate compiled file.";
509 throw new Exception(errtext);
510 }
511 m_scriptEngine.Log.DebugFormat("[Compiler] Compiled new assembly for {0}", asset);
512 return OutFile;
513 }
514 }
515}