static void Compile(string srcFile, string destFile = null) { try { Program.srcFile = srcFile; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Init(); //compiler.SetCompileSwitch("IDE"); //compiler.SetCompileSwitch("SkipPoint=R19:C30"); if (!isXml) { string destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.mub", Path.GetFileNameWithoutExtension(srcFile))); if (destFile != null) { destFileName = destFile; } using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream destCompiledBin = new FileStream(destFileName, FileMode.Create, FileAccess.Write)) using (Stream bufferedDestStream = new BufferedStream(destCompiledBin)) { compiler.Compile(sourceMML, bufferedDestStream, appendFileReaderCallback); } } else { string destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.xml", Path.GetFileNameWithoutExtension(srcFile))); if (destFile != null) { destFileName = destFile; } MmlDatum[] dest = null; using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { dest = compiler.Compile(sourceMML, appendFileReaderCallback); } XmlSerializer serializer = new XmlSerializer(typeof(MmlDatum[]), typeof(MmlDatum[]).GetNestedTypes()); using (StreamWriter sw = new StreamWriter(destFileName, false, Encoding.UTF8)) { serializer.Serialize(sw, dest); } } } catch (Exception ex) { Log.WriteLine(LogLevel.FATAL, ex.Message); Log.WriteLine(LogLevel.FATAL, ex.StackTrace); } finally { } }
public void SimpleExpression1_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression1.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH; G.Directives["TinyPG"]["OutputPath"] = OUTPUTPATH; // basic checks string temp = G.PrintFirsts(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); temp = G.GetOutputPath(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); temp = G.PrintGrammar(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+7/3*2+(4*2)"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
private IList <JsType> Compile(string program) { var compilation = PreparedCompilation.CreateCompilation("X", new[] { new MockSourceFile("file.cs", program) }, new[] { Common.Mscorlib }, new string[0]); var compiler = new Compiler.Compiler(new MockMetadataImporter(), new MockNamer(), new MockRuntimeLibrary(), new MockErrorReporter()); return(compiler.Compile(compilation).ToList()); }
private ModuleImage CompileInternal(ICodeSource source) { RegisterScopeIfNeeded(); var parser = new PreprocessingLexer(); foreach (var variable in _preprocessorVariables) { parser.Define(variable); } parser.UnknownDirective += (sender, args) => { // все неизвестные директивы возвращать назад и обрабатывать старым кодом args.IsHandled = true; }; parser.Code = source.Code; var compiler = new Compiler.Compiler(); compiler.ProduceExtraCode = ProduceExtraCode; compiler.DirectiveHandler = ResolveDirective; if (DirectiveResolver != null) { DirectiveResolver.Source = source; } ModuleImage compiledImage; try { compiledImage = compiler.Compile(parser, _currentContext); } catch (ScriptException e) { if (e.ModuleName == null) { e.ModuleName = source.SourceDescription; } throw; } finally { if (DirectiveResolver != null) { DirectiveResolver.Source = null; } } var mi = new ModuleInformation(); mi.CodeIndexer = parser.Iterator; // пока у модулей нет собственных имен, будет совпадать с источником модуля mi.ModuleName = source.SourceDescription; mi.Origin = source.SourceDescription; compiledImage.ModuleInfo = mi; return(compiledImage); }
public void Serializes() { var c = new Compiler.Compiler <TestClass>(); var serializer = c.CompileILSerialize(c.Compile((i) => { return(new Container(new Member((PropertyInfo)i))); })); var result = serializer(new TestClass { MyProperty = "testing 1, 2, 3" }); result .Should() .NotBeNull(); result.Length .Should() .Be(1); result[0] .Should() .Be("testing 1, 2, 3"); }
internal Tuple <string, ICompilation, IMetadataImporter, MockErrorReporter> Compile(string source, bool includeLinq = false, bool expectErrors = false) { var sourceFile = new MockSourceFile("file.cs", source); var md = new MetadataImporter.ScriptSharpMetadataImporter(false); var n = new DefaultNamer(); var er = new MockErrorReporter(!expectErrors); PreparedCompilation compilation = null; var rtl = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => { var t = tr.Resolve(compilation.Compilation).GetDefinition(); return(new JsTypeReferenceExpression(t.ParentAssembly, md.GetTypeSemantics(t).Name)); }); var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: false); var references = includeLinq ? new[] { Common.Mscorlib, Common.Linq } : new[] { Common.Mscorlib }; compilation = compiler.CreateCompilation(new[] { sourceFile }, references, null); var compiledTypes = compiler.Compile(compilation); if (expectErrors) { Assert.That(er.AllMessages, Is.Not.Empty, "Compile should have generated errors"); return(Tuple.Create((string)null, compilation.Compilation, (IMetadataImporter)md, er)); } er.AllMessagesText.Should().BeEmpty("Compile should not generate errors"); var js = new OOPEmulator.ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, er).Rewrite(compiledTypes, compilation.Compilation); js = new GlobalNamespaceReferenceImporter().ImportReferences(js); string script = string.Join("", js.Select(s => OutputFormatter.Format(s, allowIntermediates: false))); if (Output == OutputType.GeneratedScript) { Console.WriteLine(script); } return(Tuple.Create(script, compilation.Compilation, (IMetadataImporter)md, er)); }
public void SupportsIL() { var c = new Compiler.Compiler <TestClass>(); c.SupportsIL(c.Compile((i) => { return(new Container(new Member((PropertyInfo)i))); })) .Should() .BeTrue(); }
private ScriptModuleHandle Compile(ICodeSource source) { RegisterScopeIfNeeded(); var parser = new Parser(); parser.Code = source.Code; var compiler = new Compiler.Compiler(); compiler.DirectiveHandler = ResolveDirective; ModuleImage compiledImage; try { compiledImage = compiler.Compile(parser, _currentContext); } catch (ScriptException e) { if (e.ModuleName == null) { e.ModuleName = source.SourceDescription; } throw; } foreach (var item in _predefinedVariables) { var varDef = _scope.GetVariable(item); if (varDef.Type == SymbolType.ContextProperty) { compiledImage.ExportedProperties.Add(new ExportedSymbol() { SymbolicName = varDef.Identifier, Index = varDef.Index }); } } var mi = new ModuleInformation(); mi.CodeIndexer = parser.GetCodeIndexer(); // пока у модулей нет собственных имен, будет совпадать с источником модуля mi.ModuleName = source.SourceDescription; mi.Origin = source.SourceDescription; compiledImage.ModuleInfo = mi; return(new ScriptModuleHandle() { Module = compiledImage }); }
private ModuleImage CompileInternal(ICodeSource source) { RegisterScopeIfNeeded(); var parser = new Parser(); parser.Code = source.Code; var compiler = new Compiler.Compiler(); compiler.ProduceExtraCode = ProduceExtraCode; compiler.DirectiveHandler = ResolveDirective; if (DirectiveResolver != null) { DirectiveResolver.Source = source; } ModuleImage compiledImage; try { compiledImage = compiler.Compile(parser, _currentContext); } catch (ScriptException e) { if (e.ModuleName == null) { e.ModuleName = source.SourceDescription; } throw; } finally { if (DirectiveResolver != null) { DirectiveResolver.Source = null; } } var mi = new ModuleInformation(); mi.CodeIndexer = parser.GetCodeIndexer(); // пока у модулей нет собственных имен, будет совпадать с источником модуля mi.ModuleName = source.SourceDescription; mi.Origin = source.SourceDescription; compiledImage.ModuleInfo = mi; return(compiledImage); }
public void SimpleExpression1_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression1_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+7/3*2+(4*2)"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
public void Deserializes() { var c = new Compiler.Compiler <TestClass>(); var deserializer = c.CompileILDeserialize(c.Compile((i) => { return(new Container(new Member((PropertyInfo)i))); })); int l = 0; deserializer(new object[] { "testing 1, 2, 3" }, ref l, out var result) .Should().BeTrue(); result.MyProperty.Should().Be("testing 1, 2, 3"); }
private CompileResult Compile(Language language, string fileName, string sourceCode) { var compiler = new Compiler.Compiler { CompilerPath = language.CompilerPath, CompilerOptionsTemplate = language.CompilerOptionsTemplate, OutputFileTemplate = language.OutputFileTemplate }; var compileSource = new CompileSource { FileName = fileName, SourceCode = sourceCode }; return(compiler.Compile(compileSource, _workingDirectory)); }
public void SimpleExpression2_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression2_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives.Add(new Directive("TinyPG")); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+8/4*2+(4*2)"); Assert.IsTrue(Convert.ToInt32(result.Value) == 17); }
public void SimpleExpression4_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"GrammarHighlighter_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives.Add(new Directive("TinyPG")); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("using System.IO;\r\n"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
/// <summary> /// Calculates integral with given inputs. /// </summary> private async void ExecuteCalculateCommand(object parameter) { _isCalculating = true; CalculateCommand.RaiseCanExecuteChanged(); // Compiles formula expression and gets function pointer on formula. var cr = await _compiler.Compile(Formula).ConfigureAwait(false); if (cr.Errors.Count == 0) { // f is function pointer. var f = _compiler.GetLambda(cr); Result = await _calculator.Integrate(f, From, To, N); } Application.Current.Dispatcher.Invoke(() => { // Enables "Calculate" button. _isCalculating = false; CalculateCommand.RaiseCanExecuteChanged(); }); }
private CompileResult Compile(Language language, string fileName, string sourceCode) { if (!File.Exists(language.CompilerPath)) { this.logger.Error($"Compiler not found: {language.Name}, {language.CompilerPath}"); return(CompileResult.NotFound()); } var compiler = new Compiler.Compiler(this.logger) { CompilerPath = language.CompilerPath, CompilerOptionsTemplate = language.CompilerOptionsTemplate, OutputFileTemplate = language.OutputFileTemplate }; var compileSource = new CompileSource { FileName = fileName, SourceCode = sourceCode }; return(compiler.Compile(compileSource, _workingDirectory)); }
static void Main(string[] args) { // Test stream // Foo = 10.5 // Bar = 20 string test = "50 > 49.5 and 50 < 50.5"; byte[] byteArray = Encoding.ASCII.GetBytes(test); MemoryStream stream = new MemoryStream(byteArray); var Tokenizer = new Tokenizer.Tokenizer(); // Token definitions Tokenizer.AddTokenDefinition(TokenType.Ignored, @" "); Tokenizer.AddTokenDefinition(TokenType.NewLine, @"\\n\\r"); Tokenizer.AddTokenDefinition(TokenType.EndOfFile, ""); Tokenizer.AddTokenDefinition(TokenType.LogicalOr, @"\|\|"); Tokenizer.AddTokenDefinition(TokenType.LogicalOr, @"or"); Tokenizer.AddTokenDefinition(TokenType.LogicalAnd, @"&&"); Tokenizer.AddTokenDefinition(TokenType.LogicalAnd, @"and"); Tokenizer.AddTokenDefinition(TokenType.Bool, "true|TRUE|True"); Tokenizer.AddTokenDefinition(TokenType.Bool, "false|FALSE|False"); Tokenizer.AddTokenDefinition(TokenType.Ident, "[a-zA-Z][a-zA-Z0-9]+"); //Tokenizer.AddTokenDefinition(TokenType.Int, "(-)?[0-9]+"); Tokenizer.AddTokenDefinition(TokenType.Float, @"(-)?[0-9]+(\.[0-9]+)?(e\+[0-9]+)?"); Tokenizer.AddTokenDefinition(TokenType.Equals, @"=="); Tokenizer.AddTokenDefinition(TokenType.NotEquals, @"!="); Tokenizer.AddTokenDefinition(TokenType.LessThan, @"<"); Tokenizer.AddTokenDefinition(TokenType.GreaterThan, @">"); Tokenizer.AddTokenDefinition(TokenType.LessThanEquals, @"<="); Tokenizer.AddTokenDefinition(TokenType.GreaterThanEquals, @">="); Tokenizer.AddTokenDefinition(TokenType.Addition, @"\+"); Tokenizer.AddTokenDefinition(TokenType.Subtraction, @"-"); Tokenizer.AddTokenDefinition(TokenType.Multiplication, @"\*"); Tokenizer.AddTokenDefinition(TokenType.Division, @"\/"); Tokenizer.AddTokenDefinition(TokenType.Modulo, @"%"); Tokenizer.AddTokenDefinition(TokenType.Not, @"!"); Tokenizer.AddTokenDefinition(TokenType.OpenBracket, @"\("); Tokenizer.AddTokenDefinition(TokenType.CloseBracket, @"\)"); Stopwatch sw = new Stopwatch(); sw.Start(); Tokenizer.Tokenize(stream); long tokenizerMs = sw.ElapsedMilliseconds; // Tokenizer debug output //foreach (IToken token in Tokenizer.Tokens) // Console.WriteLine($"{token.TokenType}, {token.Text}, {token.LineNumber}:{token.ColumnNumber}"); Dictionary <string, Variable> vars = new Dictionary <string, Variable> { { "foobar", new BoolVariable("foobar", true) }, { "foo", new FloatVariable("foo", 10.5f) }, { "bar", new FloatVariable("bar", 20) } }; Compiler.Compiler compiler = new Compiler.Compiler(); sw.Restart(); Expression expr = compiler.Compile(Tokenizer.Tokens, vars); long compilerMs = sw.ElapsedMilliseconds; sw.Stop(); Console.WriteLine($"Tokenized in {tokenizerMs}ms"); Console.WriteLine($"Compiled in {compilerMs}ms"); Console.WriteLine($"Result: {(expr as IExpression<bool>).Evaluate()}"); Console.ReadLine(); }
public bool Compile(CompilerOptions options, ErrorReporterWrapper er) { string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName(); try { // Compile the assembly var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er); if (er.HasErrors) { return(false); } if (!options.AlreadyCompiled) { // Compile the assembly var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er)); var d = new Mono.CSharp.Driver(ctx); d.Compile(); if (er.HasErrors) { return(false); } } // Compile the script var md = new MetadataImporter.ScriptSharpMetadataImporter(options.MinimizeScript); var n = new DefaultNamer(); PreparedCompilation compilation = null; var rtl = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => new JsTypeReferenceExpression(tr.Resolve(compilation.Compilation).GetDefinition())); var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: options.References.Count == 0 /* We allow user-defined structs in mscorlib only, which can be identified by the fact that it has no references*/); var references = LoadReferences(settings.AssemblyReferences, er); if (references == null) { return(false); } compilation = compiler.CreateCompilation(options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references, options.DefineConstants); var compiledTypes = compiler.Compile(compilation); IMethod entryPoint = null; if (options.HasEntryPoint) { List <IMethod> candidates; if (!string.IsNullOrEmpty(options.EntryPointClass)) { var t = compilation.Compilation.MainAssembly.GetTypeDefinition(new FullTypeName(options.EntryPointClass)); if (t == null) { er.Region = DomRegion.Empty; er.Message(7950, "Could not find the entry point class " + options.EntryPointClass + "."); return(false); } candidates = t.Methods.Where(IsEntryPointCandidate).ToList(); } else { candidates = compilation.Compilation.MainAssembly.GetAllTypeDefinitions().SelectMany(t => t.Methods).Where(IsEntryPointCandidate).ToList(); } if (candidates.Count != 1) { er.Region = DomRegion.Empty; er.Message(7950, "Could not find a unique entry point."); return(false); } entryPoint = candidates[0]; } var js = new ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, n, er).Process(compiledTypes, compilation.Compilation, entryPoint); js = new DefaultLinker(md, n).Process(js, compilation.Compilation.MainAssembly); if (er.HasErrors) { return(false); } string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll"); string outputScriptPath = !string.IsNullOrEmpty(options.OutputScriptPath) ? options.OutputScriptPath : Path.ChangeExtension(options.SourceFiles[0], ".js"); if (!options.AlreadyCompiled) { try { File.Copy(intermediateAssemblyFile, outputAssemblyPath, true); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7950, ex.Message); return(false); } if (!string.IsNullOrEmpty(options.DocumentationFile)) { try { File.Copy(intermediateDocFile, options.DocumentationFile, true); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7952, ex.Message); return(false); } } } if (options.MinimizeScript) { js = ((JsBlockStatement)Minifier.Process(new JsBlockStatement(js))).Statements; } string script = string.Join("", js.Select(s => options.MinimizeScript ? OutputFormatter.FormatMinified(s) : OutputFormatter.Format(s))); try { File.WriteAllText(outputScriptPath, script, settings.Encoding); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7951, ex.Message); return(false); } return(true); } catch (Exception ex) { er.Region = DomRegion.Empty; er.InternalError(ex.ToString()); return(false); } finally { if (!options.AlreadyCompiled) { try { File.Delete(intermediateAssemblyFile); } catch {} try { File.Delete(intermediateDocFile); } catch {} } } }
//static void Compile(string srcFile) //{ // try // { // Program.srcFile = srcFile; // Compiler.Compiler compiler = new Compiler.Compiler(); // compiler.Init(); // if (!isXml) // { // string destFileName = Path.Combine( // Path.GetDirectoryName(Path.GetFullPath(srcFile)) // , string.Format("{0}.mub", Path.GetFileNameWithoutExtension(srcFile))); // using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) // using (FileStream destCompiledBin = new FileStream(destFileName, FileMode.Create, FileAccess.Write)) // using (Stream bufferedDestStream = new BufferedStream(destCompiledBin)) // { // compiler.Compile(sourceMML, bufferedDestStream, appendFileReaderCallback); // } // } // else // { // string destFileName = Path.Combine( // Path.GetDirectoryName(Path.GetFullPath(srcFile)) // , string.Format("{0}.xml", Path.GetFileNameWithoutExtension(srcFile))); // MmlDatum[] dest = null; // using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) // { // dest = compiler.Compile(sourceMML, appendFileReaderCallback); // } // XmlSerializer serializer = new XmlSerializer(typeof(MmlDatum[]), typeof(MmlDatum[]).GetNestedTypes()); // using (StreamWriter sw = new StreamWriter(destFileName, false, Encoding.UTF8)) // { // serializer.Serialize(sw, dest); // } // } // } // catch (Exception ex) // { // Log.WriteLine(LogLevel.FATAL, ex.Message); // Log.WriteLine(LogLevel.FATAL, ex.StackTrace); // } // finally // { // } //} static void Compile(string srcFile, string destFile = null) { try { if (Path.GetExtension(srcFile) == "") { srcFile = Path.Combine( Path.GetDirectoryName(Path.GetFullPath(srcFile)) , string.Format("{0}.muc", Path.GetFileNameWithoutExtension(srcFile)) ); } srcFile = Path.Combine( Path.GetDirectoryName(Path.GetFullPath(srcFile)) , srcFile ); Program.srcFile = srcFile; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Init(); //compiler.SetCompileSwitch("IDE"); //compiler.SetCompileSwitch("SkipPoint=R19:C30"); if (!isXml) { string destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.mub", Path.GetFileNameWithoutExtension(srcFile))); if (destFile != null) { destFileName = destFile; } if (!File.Exists(srcFile)) { Log.WriteLine(LogLevel.ERROR, string.Format(msg.get("E0601"), srcFile)); return; } bool isSuccess = false; using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (MemoryStream destCompiledBin = new MemoryStream()) using (Stream bufferedDestStream = new BufferedStream(destCompiledBin)) { isSuccess = compiler.Compile(sourceMML, bufferedDestStream, appendFileReaderCallback); if (isSuccess) { bufferedDestStream.Flush(); byte[] destbuf = destCompiledBin.ToArray(); File.WriteAllBytes(destFileName, destbuf); } } } else { string destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.xml", Path.GetFileNameWithoutExtension(srcFile))); if (destFile != null) { destFileName = destFile; } MmlDatum[] dest = null; using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { dest = compiler.Compile(sourceMML, appendFileReaderCallback); } XmlSerializer serializer = new XmlSerializer(typeof(MmlDatum[]), typeof(MmlDatum[]).GetNestedTypes()); using (StreamWriter sw = new StreamWriter(destFileName, false, Encoding.UTF8)) { serializer.Serialize(sw, dest); } } } catch (Exception ex) { Log.WriteLine(LogLevel.FATAL, ex.Message); Log.WriteLine(LogLevel.FATAL, ex.StackTrace); } finally { } }
private static void Compile(string[] args, int argIndex) { try { //mc向け引数のリストを作る List <string> lstMcArg = new List <string>(); for (int i = argIndex; i < args.Length; i++) { lstMcArg.Add(args[i]); } Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Init(); compiler.mcArgs = lstMcArg.ToArray(); env = new Common.Environment(); env.AddEnv("arranger"); env.AddEnv("composer"); env.AddEnv("user"); env.AddEnv("mcopt"); env.AddEnv("pmd"); compiler.env = env.GetEnv(); //各種ファイルネームを得る int s = 0; foreach (string arg in compiler.mcArgs) { if (string.IsNullOrEmpty(arg)) { continue; } if (arg[0] == '-' || arg[0] == '/') { continue; } if (s == 0) { srcFile = arg; } else if (s == 1) { ffFile = arg; } else if (s == 2) { desFile = arg; } s++; } if (string.IsNullOrEmpty(srcFile)) { Log.WriteLine(LogLevel.ERROR, msg.get("E0601")); return; } byte[] ffFileBuf = null; if (!string.IsNullOrEmpty(ffFile) && File.Exists(ffFile)) { ffFileBuf = File.ReadAllBytes(ffFile); compiler.SetFfFileBuf(ffFileBuf); } #if DEBUG compiler.SetCompileSwitch("IDE"); //compiler.SetCompileSwitch("SkipPoint=R17:C18"); #endif if (!isXml) { //デフォルトはソースファイル名の拡張子を.Mに変更したものにする string destFileName = ""; if (!string.IsNullOrEmpty(srcFile)) { destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.M", Path.GetFileNameWithoutExtension(srcFile))); } //TagからFilenameを得る string srcText; using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(sourceMML, Encoding.GetEncoding("Shift_JIS"))) srcText = sr.ReadToEnd(); string outFileName = ""; Tuple <string, string>[] tags = compiler.GetTags(srcText, appendFileReaderCallback); if (tags != null && tags.Length > 0) { foreach (Tuple <string, string> tag in tags) { #if DEBUG Log.WriteLine(LogLevel.TRACE, string.Format("{0}\t: {1}", tag.Item1, tag.Item2)); #endif //出力ファイル名を得る if (tag.Item1.ToUpper().IndexOf("#FI") != 0) { continue; //mcは3文字まで判定している為 } outFileName = tag.Item2; } } //TagにFileName指定がある場合はそちらを適用する if (!string.IsNullOrEmpty(outFileName)) { if (outFileName[0] != '.') { //ファイル名指定の場合 destFileName = Path.Combine( Path.GetDirectoryName(Path.GetFullPath(srcFile)) , outFileName); } else { //拡張子のみの指定の場合 destFileName = Path.Combine( Path.GetDirectoryName(Path.GetFullPath(srcFile)) , string.Format("{0}{1}" , Path.GetFileNameWithoutExtension(srcFile) , outFileName)); } } //最終的にdesFileの指定がある場合は、そちらを優先する if (desFile != null) { destFileName = desFile; } bool isSuccess = false; using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) //using (FileStream destCompiledBin = new FileStream(destFileName, FileMode.Create, FileAccess.Write)) using (MemoryStream destCompiledBin = new MemoryStream()) using (Stream bufferedDestStream = new BufferedStream(destCompiledBin)) { isSuccess = compiler.Compile(sourceMML, bufferedDestStream, appendFileReaderCallback); if (isSuccess) { bufferedDestStream.Flush(); byte[] destbuf = destCompiledBin.ToArray(); File.WriteAllBytes(destFileName, destbuf); if (compiler.outFFFileBuf != null) { string outfn = Path.Combine(Path.GetDirectoryName(destFileName), compiler.outFFFileName); File.WriteAllBytes(outfn, compiler.outFFFileBuf); } } } } else { string destFileName = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(srcFile)), string.Format("{0}.xml", Path.GetFileNameWithoutExtension(srcFile))); if (desFile != null) { destFileName = desFile; } MmlDatum[] dest = null; //xmlの時はIDEモードでコンパイル compiler.SetCompileSwitch("IDE"); using (FileStream sourceMML = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { dest = compiler.Compile(sourceMML, appendFileReaderCallback); } XmlSerializer serializer = new XmlSerializer(typeof(MmlDatum[]), typeof(MmlDatum[]).GetNestedTypes()); using (StreamWriter sw = new StreamWriter(destFileName, false, Encoding.UTF8)) { serializer.Serialize(sw, dest); } } } catch (Exception ex) { Log.WriteLine(LogLevel.FATAL, ex.Message); Log.WriteLine(LogLevel.FATAL, ex.StackTrace); } finally { } }
public bool Compile(CompilerOptions options, ErrorReporterWrapper er) { string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName(); try { // Compile the assembly var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er); if (er.HasErrors) { return(false); } if (!options.AlreadyCompiled) { // Compile the assembly var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er)); var d = new Mono.CSharp.Driver(ctx); d.Compile(); if (er.HasErrors) { return(false); } } // Compile the script var md = new MetadataImporter.ScriptSharpMetadataImporter(options.MinimizeScript); var n = new DefaultNamer(); PreparedCompilation compilation = null; var rtl = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => { var t = tr.Resolve(compilation.Compilation).GetDefinition(); return(new JsTypeReferenceExpression(t.ParentAssembly, md.GetTypeSemantics(t).Name)); }); var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: options.References.Count == 0 /* We allow user-defined structs in mscorlib only, which can be identified by the fact that it has no references*/); var references = LoadReferences(settings.AssemblyReferences, er); if (references == null) { return(false); } compilation = compiler.CreateCompilation(options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references, options.DefineConstants); var compiledTypes = compiler.Compile(compilation); var js = new ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, er).Rewrite(compiledTypes, compilation.Compilation); js = new GlobalNamespaceReferenceImporter().ImportReferences(js); if (er.HasErrors) { return(false); } string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll"); string outputScriptPath = !string.IsNullOrEmpty(options.OutputScriptPath) ? options.OutputScriptPath : Path.ChangeExtension(options.SourceFiles[0], ".js"); if (!options.AlreadyCompiled) { try { File.Copy(intermediateAssemblyFile, outputAssemblyPath, true); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7950, ex.Message); return(false); } if (!string.IsNullOrEmpty(options.DocumentationFile)) { try { File.Copy(intermediateDocFile, options.DocumentationFile, true); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7952, ex.Message); return(false); } } } string script = string.Join("", js.Select(s => options.MinimizeScript ? OutputFormatter.FormatMinified(Minifier.Process(s)) : OutputFormatter.Format(s))); try { File.WriteAllText(outputScriptPath, script, settings.Encoding); } catch (IOException ex) { er.Region = DomRegion.Empty; er.Message(7951, ex.Message); return(false); } return(true); } catch (Exception ex) { er.Region = DomRegion.Empty; er.InternalError(ex.ToString()); return(false); } finally { if (!options.AlreadyCompiled) { try { File.Delete(intermediateAssemblyFile); } catch {} try { File.Delete(intermediateDocFile); } catch {} } } }