public static void Main(string[] args) { string thing = @"if 10 equals 10 then end"; var compiler = new Compiler.Compiler(thing); // ew ew ew double compiler ew var machine = new Machine(); System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); try { timer.Start(); CompiledProgram program = compiler.Compile(); Console.WriteLine(program.ToString()); machine.Load(program); machine.Run(); } catch (EnglangException exp) { Console.WriteLine(exp.Message); } timer.Stop(); Console.WriteLine("Done. Time: {0}", timer.Elapsed.ToString("%m\\:ss\\.ffff")); Console.ReadLine(); }
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); }
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 { } }
public VirtualMachine.Closure CompileString(String source) { Lexer lexer = new Lexer(); List<Lexer.Lexeme> output = lexer.lex(source); Parser parser = new Parser(output); AST outpu2 = parser.Parse(); Compiler.Compiler compiler = new Compiler.Compiler(); VirtualMachine.Function compiledFunctions = compiler.CompileAST(outpu2); //Function.Print(compiledFunctions, LamnState.OutStream); return new VirtualMachine.Closure(compiledFunctions, new VirtualMachine.StackCell[0]); }
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"); }
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); }
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 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.")); }
public static void TestIntellisense(string dir) { //string dir = Path.Combine(@"c:\Work\Miks\_PABCNETGitHub\TestSuite", "intellisense_tests"); var comp = new Compiler.Compiler(); var controller = new CodeCompletion.CodeCompletionController(); CodeCompletion.CodeCompletionController.comp = comp; CodeCompletion.CodeCompletionController.SetParser(".pas"); CodeCompletion.CodeCompletionController.ParsersController = comp.ParsersController; var files = Directory.GetFiles(dir, "*.pas"); var parser = comp.ParsersController; for (int i = 0; i < files.Length; i++) { var FileName = files[i]; var content = File.ReadAllText(FileName); var dc = controller.Compile(FileName, content); string expr_without_brackets = null; var tmp = content; var ind = -1; ind = tmp.IndexOf("{@"); while (ind != -1) { var lines = tmp.Split(new string[] { System.Environment.NewLine }, System.StringSplitOptions.None); var pos = ind - 1; var line = GetLineByPos(lines, pos); var col = GetColByPos(lines, pos); var desc = CodeCompletion.CodeCompletionTester.GetDescription(pos, tmp, line, col, FileName, dc, comp.ParsersController); var should_desc = tmp.Substring(ind + 2, tmp.IndexOf("@}") - ind - 2); if (desc == null) { desc = ""; } desc = desc.Split(new string[] { "\n" }, StringSplitOptions.None)[0].Trim(); assert(desc == should_desc, FileName + ", should: " + should_desc + ", is: " + desc); tmp = tmp.Remove(ind, tmp.IndexOf("@}") + 2 - ind); ind = tmp.IndexOf("{@"); } } }
public Builder(string language) { Status = true; Extension.BPProgram = ".bp"; Extension.BPInclude = ".bpi"; Extension.BPModule = ".bpm"; Extension.LMSProgram = ".lms"; _streamI = new MemoryStream(); _streamC = new MemoryStream(); _streamA = new MemoryStream(); _compiler = new Compiler.Compiler(); _assembler = new Assembler.Assembler(); _outFolder = ""; switch (language.ToLower().Trim()) { case "ru": Language.Type = Enums.LanguageType.RU; break; case "en": Language.Type = Enums.LanguageType.EN; break; case "ua": Language.Type = Enums.LanguageType.UA; break; default: Language.Type = Enums.LanguageType.EN; break; } Data.Install(Enums.ProjectType.BP); }
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(); }
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 }; }
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 {} } } }
static void Main(string[] args) { var definitions = new List<TokenDefenition>(); definitions.Add(new TokenDefenition("\\/\\/ .*", TokenType.SINGLELINE)); definitions.Add(new TokenDefenition("\\ba new\\b", TokenType.NEW)); definitions.Add(new TokenDefenition("\\d+(?:\\.\\d+)?\\b", TokenType.NUMBER)); definitions.Add(new TokenDefenition("\\\"(?:[^\\\"\\\\]|\\\\.)*\\\"", TokenType.TEXT)); definitions.Add(new TokenDefenition("[Tt]rue|[Ff]alse", TokenType.BOOLEAN)); definitions.Add(new TokenDefenition("-?[0-9]\\d*(\\.\\d+)", TokenType.UNARYOPERATOR)); // definitions.Add(new TokenDefenition("\\-(?=\\d)", TokenType.NEGATIVE)); //definitions.Add(new TokenDefenition("\\+(?=\\d)", TokenType.POSITIVE)); definitions.Add(new TokenDefenition("\\bnot\\b", TokenType.NOT)); definitions.Add(new TokenDefenition("\\+|plus", TokenType.ADD)); // definitions.Add(new TokenDefenition("\\^", TokenType.EXPONENT)); definitions.Add(new TokenDefenition("\\%", TokenType.MODULO)); definitions.Add(new TokenDefenition("\\-|minus", TokenType.SUBTRACT)); definitions.Add(new TokenDefenition("\\*|times", TokenType.MULTIPLY)); definitions.Add(new TokenDefenition("\\/|divided by", TokenType.DIVISION)); definitions.Add(new TokenDefenition("\\(", TokenType.OPENPARENTHESE)); definitions.Add(new TokenDefenition("\\)", TokenType.CLOSEPARENTHESE)); definitions.Add(new TokenDefenition("\\bis equal to\\b", TokenType.EQUAL)); definitions.Add(new TokenDefenition("\\bis not equal to\\b|!=", TokenType.NOTEQUAL)); definitions.Add(new TokenDefenition("\\bis smaller than or equal to\\b", TokenType.SMALLEREQUAL)); definitions.Add(new TokenDefenition("\\bis smaller than\\b", TokenType.SMALLER)); definitions.Add(new TokenDefenition("\\bis larger than or equal to\\b", TokenType.LARGEREQUAL)); definitions.Add(new TokenDefenition("\\bis larger than\\b", TokenType.LARGER)); definitions.Add(new TokenDefenition("(=|\\bis\\b)", TokenType.ASSIGNMENT)); definitions.Add(new TokenDefenition("\\band\\b", TokenType.AND)); definitions.Add(new TokenDefenition("\\bor\\b", TokenType.OR)); definitions.Add(new TokenDefenition("Return\\b", TokenType.RETURN)); //definitions.Add(new TokenDefenition("\\bshould\\b", TokenType.SHOULD)); definitions.Add(new TokenDefenition("\\b[Ww]hile\\b", TokenType.WHILE)); definitions.Add(new TokenDefenition("\\b[Ff]or each\\b", TokenType.FOREACH)); //definitions.Add(new TokenDefenition("\\b(in|inside)( the)?\\b", TokenType.PREPOSITION)); definitions.Add(new TokenDefenition("\\b[Ii]f\\b", TokenType.IF)); definitions.Add(new TokenDefenition(", do:", TokenType.DO)); definitions.Add(new TokenDefenition("\\b[Ee]lse\\b", TokenType.ELSE)); //definitions.Add(new TokenDefenition("\\bRecipe\\b", TokenType.RECIPE)); //definitions.Add(new TokenDefenition("\\bwith\\b", TokenType.WITH)); //definitions.Add(new TokenDefenition("\\bnow.", TokenType.NOW)); //definitions.Add(new TokenDefenition("The\\b", TokenType.THE)); //definitions.Add(new TokenDefenition("\\bof the\\b", TokenType.OFTHE)); //definitions.Add(new TokenDefenition("When the\\b", TokenType.WHENTHE)); definitions.Add(new TokenDefenition("\\s", TokenType.WHITESPACE)); definitions.Add(new TokenDefenition("\\w+", TokenType.IDENTIFIER)); //definitions.Add(new TokenDefenition("\'s", TokenType.ACCESSOR)); definitions.Add(new TokenDefenition("\\.", TokenType.END)); definitions.Add(new TokenDefenition("\\:", TokenType.COLON)); definitions.Add(new TokenDefenition("\\,", TokenType.COMMA)); var fr = new FileReader("C:\\Dev\\42IN13SAI\\DP2\\test.txt"); var linesToTokenize = fr.readFile(); if (linesToTokenize.Count == 0) { Console.WriteLine("No lines to tokenize"); } Lexer lexer = new Lexer(definitions); List<Token> tokens = lexer.lex(linesToTokenize); //bouw Tokenlijst Console.WriteLine(" +----------------------+--------------+------------+------------+-------+"); Console.WriteLine("{0,20} {1,12} {2,10} {3,10} {4,5}", "Content | ", "Type | ", "Line | ", "Column | ", "Level |"); Console.WriteLine(" +----------------------+--------------+------------+------------+-------+"); foreach (var token in tokens) { Console.WriteLine("{0,20} {1,12} {2,10} {3,10} {4,5}", token.content, token.tokenType, token.line, token.column, token.level); } Console.WriteLine(" +----------------------+--------------+------------+------------+-------+"); Console.ReadLine(); //Compileren var compiler = new Compiler.Compiler(); Program program = null; try { program = compiler.Compile(tokens); } catch (ParsingException e) { Console.Error.WriteLine(e); //return -1; } catch { Console.Error.WriteLine("Unknown Exception in Compiler"); //return -1; } Console.WriteLine("--> compilingng done"); Compiler.GlobalsCompiler.isRunning = true; VirtualMachine vm = new VirtualMachine(); try { vm.run(program); } catch (VirtualMachineRuntimeException e) { Console.Error.WriteLine(e); //return -1; } catch { Console.Error.WriteLine("Unknown Exception in Virtual Machine"); //return -1; } Console.WriteLine("--> running done"); }
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 {} } } }
public string CompileToPHP(string source = null) { var compiler = new Compiler.Compiler(ast, source); return compiler.Compile(transformations); }
// *** CONSTRUCTION *** // #region Constructor public Manager() { #region Create Member Objects GameClasses = new Dictionary <string, Type>(); GameAttributes = new Dictionary <string, GameAttribute>(); AppearanceAttributes = new Dictionary <string, AppearanceAttribute>(); Environment = new Compiler.Environment(); PieceTypeLibrary = new PieceTypeLibrary(); EngineLibrary = new EngineLibrary(); InternalEngine = new EngineConfiguration(); InternalEngine.FriendlyName = "ChessV"; InternalEngine.InternalName = "ChessV 2.2 RC1"; #endregion #region Add ChessV Data Types to Environment Environment.AddSymbol("MoveCapability", typeof(MoveCapability)); Environment.AddSymbol("Direction", typeof(Direction)); Environment.AddSymbol("BitBoard", typeof(BitBoard)); Environment.AddSymbol("Rule", typeof(Rule)); Environment.AddSymbol("Game", typeof(Game)); Environment.AddSymbol("PieceType", typeof(PieceType)); Environment.AddSymbol("Piece", typeof(Piece)); Environment.AddSymbol("Location", typeof(Location)); #endregion #region Load Internal Games // *** LOAD INTERNAL GAMES *** // // Load games and piece types from the main ChessV.Base module Module module = typeof(Game).Module; loadPieceTypesFromModule(module); loadGamesFromModule(module); // Load games and piece types from the ChessV.Games DLL string moduleName = module.FullyQualifiedName; string modulePath = moduleName.Substring(0, Math.Max(moduleName.LastIndexOf('\\'), moduleName.LastIndexOf('/')) + 1); string gamesDllName = modulePath + "ChessV.Games.dll"; Assembly gamesAssembly = Assembly.UnsafeLoadFrom(gamesDllName); foreach (Module gamesModule in gamesAssembly.GetModules()) { loadPieceTypesFromModule((Module)gamesModule); loadGamesFromModule((Module)gamesModule); loadPieceTypePropertyAttributesFromModule((Module)gamesModule); loadRulesFromModule((Module)gamesModule); loadEvaluationsFromModule((Module)gamesModule); } #endregion #region Load Games from Include Folder // *** LOAD GAMES FROM INCLUDE FOLDER *** // // Search for the include folder. We provide some flexibility // regarding where this path is located string currPath = Directory.GetCurrentDirectory(); string includePath = Path.Combine(currPath, "Include"); if (!Directory.Exists(includePath)) { int iIndex = currPath.LastIndexOf("ChessV"); if (iIndex > 0) { iIndex = currPath.IndexOf(Path.DirectorySeparatorChar, iIndex); if (iIndex > 0) { currPath = currPath.Remove(iIndex); includePath = Path.Combine(currPath, "Include"); if (!Directory.Exists(includePath)) { currPath = Directory.GetCurrentDirectory(); iIndex = currPath.IndexOf("ChessV"); if (iIndex > 0) { iIndex = currPath.IndexOf(Path.DirectorySeparatorChar, iIndex); if (iIndex > 0) { currPath = currPath.Remove(iIndex); includePath = Path.Combine(currPath, "Include"); } } } } } } if (Directory.Exists(includePath)) { AppDomain myDomain = Thread.GetDomain(); AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "DynamicGamesAssembly"; System.Reflection.Emit.AssemblyBuilder assemblyBuilder = myDomain.DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); System.Reflection.Emit.ModuleBuilder dynamicModule = assemblyBuilder.DefineDynamicModule("ChessVDynamicGames"); Compiler.Compiler compiler = new Compiler.Compiler(assemblyBuilder, dynamicModule, Environment); string[] includeFiles = Directory.GetFiles(includePath, "*.cvc"); foreach (string file in includeFiles) { TextReader reader = new StreamReader(file); compiler.ProcessInput(reader); reader.Close(); } foreach (KeyValuePair <string, Type> pair in compiler.GameTypes) { GameClasses.Add(pair.Key, pair.Value); GameAttributes.Add(pair.Key, compiler.GameAttributes[pair.Key]); if (compiler.GameAppearances.ContainsKey(pair.Key)) { AppearanceAttributes.Add(pair.Key, compiler.GameAppearances[pair.Key]); } } } #endregion }
public void Write(Compiler.Compiler compiler, string outputFile) { var export = new SExpr("export"); var components = new SExpr("components"); var libparts = new SExpr("libparts"); var nets = new SExpr("nets"); export.children.AddLast(new SExpr("version", "D")); export.children.AddLast(components); export.children.AddLast(libparts); export.children.AddLast(nets); var chipDefinitions = new HashSet <IChipDefinition>(); foreach (var netComponent in compiler.netComponents) { var comp = new SExpr("comp"); comp.children.AddLast(new SExpr("ref", netComponent.name)); comp.children.AddLast(new SExpr("name", netComponent.componentName)); comp.children.AddLast(new SExpr("value", (string)netComponent.chip.chipAttribute["component_name"])); comp.children.AddLast(new SExpr("footprint", (string)netComponent.chip.chipAttribute["footprint_name"])); comp.children.AddLast(new SExpr("tstamp", netComponent.id.ToString("X8"))); components.children.AddLast(comp); chipDefinitions.Add(netComponent.chip); } foreach (var chipDefinition in chipDefinitions) { var libpart = new SExpr("libpart"); var pins = new SExpr("pins"); libpart.children.AddLast(new SExpr("lib", (string)chipDefinition.chipAttribute["library_name"])); libpart.children.AddLast(new SExpr("part", (string)chipDefinition.chipAttribute["component_name"])); libpart.children.AddLast(pins); foreach (var mapping in chipDefinition.portNameMappings) { foreach (var port in mapping.Values) { var pin = new SExpr("pin"); pin.children.AddLast(new SExpr("num", ((int)port.attribute["pin_assign"]).ToString())); pin.children.AddLast(new SExpr("name", port.name.baseName)); pin.children.AddLast(new SExpr("type", (string)port.attribute["pin_type"])); pins.children.AddLast(pin); } } foreach (var constPort in chipDefinition.constAssignMappings.Keys) { var pin = new SExpr("pin"); pin.children.AddLast(new SExpr("num", ((int)constPort.attribute["pin_assign"]).ToString())); pin.children.AddLast(new SExpr("name", constPort.name.baseName)); pin.children.AddLast(new SExpr("type", (string)constPort.attribute["pin_type"])); pins.children.AddLast(pin); } libparts.children.AddLast(libpart); } foreach (var netSignal in compiler.representingNet.Values.Distinct()) { var net = new SExpr("net"); net.children.AddLast(new SExpr("code", netSignal.id.ToString())); net.children.AddLast(new SExpr("name", netSignal.name)); net.children.AddLast(new SExpr("signal", netSignal.signalName)); foreach (var netNode in netSignal.adjacentNodes) { var node = new SExpr("node"); node.children.AddLast(new SExpr("ref", netNode.netComponent.name)); node.children.AddLast(new SExpr("pin", netNode.pin.ToString())); net.children.AddLast(node); } nets.children.AddLast(net); } Console.WriteLine(export); System.IO.File.WriteAllText(outputFile, export.ToString()); }
//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 { } }