예제 #1
0
        //this code needs to be completely rewritten
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
            {
                return(null);
            }
            code = code.line();                 // make sure there is an empty line at the end

            try
            {
                //handle special incudes in source code
                var lines = code.fix_CRLF().lines();
                foreach (var originalLine in lines)
                {
                    string line = originalLine;
                    originalLine.starts("//O2Include:", (includeText) =>
                    {
                        var file         = includeText;
                        var baseFile     = SourceCodeFile ?? PublicDI.CurrentScript;
                        var parentFolder = baseFile.parentFolder();
                        if (parentFolder.notValid())
                        {
                            "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error();
                        }
                        var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file, parentFolder);
                        if (resolvedFile.fileExists())
                        {
                            var fileContents = resolvedFile.contents();
                            code             = code.Replace(line, line.line().add(fileContents).line());
                        }
                        else
                        {
                            "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText);
                        }
                    });
                }

                var snippetParser = new SnippetParser(SupportedLanguage.CSharp);

                var parsedCode = snippetParser.Parse(code);
                AstErrors       = snippetParser.errors();
                CompilationUnit = new CompilationUnit();

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method
                        var blockStatement = (BlockStatement)parsedCode;
                        CompilationUnit.add_Type(default_TypeName)
                        .add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, blockStatement);

                        // remove comments from parsed code
                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);

                        // add references included in the original source code file
                        mapCodeO2References(astCSharp);

                        astCSharp.mapAstDetails();

                        astCSharp.ExtraSpecials.Clear();
                        var method     = CompilationUnit.method(default_MethodName);
                        var returntype = method.returnType();
                        var type       = CompilationUnit.type(default_TypeName);

                        type.Children.Clear();
                        var tempBlockStatement = new BlockStatement();
                        tempBlockStatement.add_Variable("a", 0);
                        method.Body = tempBlockStatement;
                        var newMethod = type.add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, tempBlockStatement);
                        newMethod.TypeReference = returntype;
                        astCSharp.mapAstDetails();
                        var csharpCode = astCSharp.AstDetails.CSharpCode
                                         .replace("Int32 a = 0;", code);

                        AstDetails          = new Ast_CSharp(csharpCode).AstDetails;
                        CreatedFromSnipptet = true;
                        DebugMode.ifDebug("Ast parsing was OK");
                        SourceCode = csharpCode;
                        onAstOK.invoke();

                        return(csharpCode);
                    }


                    CompilationUnit = (CompilationUnit)parsedCode;
                    if (CompilationUnit.Children.Count == 0)
                    {
                        return(null);
                    }

                    astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                    // add the comments from the original code

                    mapCodeO2References(astCSharp);
                    CreatedFromSnipptet = false;

                    // create sourceCode using Ast_CSharp & AstDetails
                    if (CompilationUnit.Children.Count > 0)
                    {
                        // reset the astCSharp.AstDetails object
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);

                        SourceCode = astCSharp.AstDetails.CSharpCode;

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        AstDetails = tempAstDetails;
                        DebugMode.ifDebug("Ast parsing was OK");
                        onAstOK.invoke();
                        return(SourceCode);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);
            }
            return(null);
        }
예제 #2
0
        public Assembly compileSourceCode_Sync(string sourceCode)
        {
            if (sourceCode.notValid())
            {
                return(null);
            }
            try
            {
                Environment.CurrentDirectory = PublicDI.config.CurrentExecutableDirectory;
                CompiledAssembly             = null;
                beforeCompile.invoke();
                DebugMode.ifInfo("Compiling Source Code (Size: {0})", sourceCode.size());
                SourceCode = sourceCode;

                if (sourceCode.lines().starting("//CLR_3.5").notEmpty()) // allow setting compilation into 2.0 CLR
                {
                    CompilationVersion = "v3.5";
                }

                var providerOptions = new Dictionary <string, string>().add("CompilerVersion", CompilationVersion);

                var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions);
                var compilerParams     = new CompilerParameters();
                compilerParams.OutputAssembly          = "_o2_Script.dll".tempFile();
                compilerParams.IncludeDebugInformation = generateDebugSymbols;
                compilerParams.GenerateInMemory        = !generateDebugSymbols;

                foreach (var referencedAssembly in ReferencedAssemblies)
                {
                    compilerParams.ReferencedAssemblies.Add(referencedAssembly);
                }

                CompilerResults = (generateDebugSymbols)
                                      ? csharpCodeProvider.CompileAssemblyFromFile(compilerParams,
                                                                                   sourceCode.saveWithExtension(".cs"))
                                      : csharpCodeProvider.CompileAssemblyFromSource(compilerParams, sourceCode);

                if (CompilerResults.Errors.Count > 0 || CompilerResults.CompiledAssembly == null)
                {
                    CompilationErrors = "";
                    foreach (CompilerError error in CompilerResults.Errors)
                    {
                        //CompilationErrors.Add(CompilationErrors.line(error.ToString());
                        var errorMessage = String.Format("{0}::{1}::{2}::{3}::{4}", error.Line,
                                                         error.Column, error.ErrorNumber,
                                                         error.ErrorText, error.FileName);
                        CompilationErrors = CompilationErrors.line(errorMessage);
                        "[CSharp_FastCompiler] Compilation Error: {0}".error(errorMessage);
                    }
                    DebugMode.ifError("Compilation failed");
                    onCompileFail.invoke();
                }
                else
                {
                    CompiledAssembly = CompilerResults.CompiledAssembly;
                    if (CompiledAssembly.Location.fileExists())
                    {
                        CompileEngine.setCachedCompiledAssembly_toMD5(sourceCode, CompiledAssembly);
                    }
                    DebugMode.ifDebug("Compilation was OK");
                    onCompileOK.invoke();
                }
                return(CompiledAssembly);
            }
            catch (Exception ex)
            {
                ex.log("[compileSourceCode_Sync");
                return(null);
            }
        }
        public void compileSourceCode()
        {
            O2Thread.mtaThread(
                () =>
            {
                try
                {
                    if (compiling == false && compileStack.Count > 0)
                    {
                        compiling = true;
                        FinishedCompilingCode.Reset();
                        compileExtraSourceCodeReferencesAndUpdateReferencedAssemblies();
                        this.sleep(forceAstBuildDelay, DebugMode);                    // wait a bit to allow more entries to be cleared from the stack
                        var sourceCode = compileStack.Pop();
                        compileStack.Clear();
                        // remove all previous compile requests (since their source code is now out of date

                        //Files.setCurrentDirectoryToExecutableDirectory();
                        Environment.CurrentDirectory = Kernel.PublicDI.config.CurrentExecutableDirectory;
                        ;
                        this.invoke(beforeCompile);
                        DebugMode.ifInfo("Compiling Source Code (Size: {0})", sourceCode.size());
                        SourceCode          = sourceCode;
                        var providerOptions = new Dictionary <string, string>();
                        providerOptions.Add("CompilerVersion", "v3.5");
                        var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions);
                        var compilerParams     = new CompilerParameters
                        {
                            GenerateInMemory        = !generateDebugSymbols,
                            IncludeDebugInformation = generateDebugSymbols
                        };

                        foreach (var referencedAssembly in ReferencedAssemblies)
                        {
                            compilerParams.ReferencedAssemblies.Add(referencedAssembly);
                        }

                        CompilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParams, sourceCode);

                        FinishedCompilingCode.Set();

                        if (CompilerResults.Errors.Count > 0 || CompilerResults.CompiledAssembly == null)
                        {
                            CompilationErrors = "";
                            foreach (CompilerError error in CompilerResults.Errors)
                            {
                                //CompilationErrors.Add(CompilationErrors.line(error.ToString());
                                var errorMessage = String.Format("{0}::{1}::{2}::{3}::{4}", error.Line,
                                                                 error.Column, error.ErrorNumber,
                                                                 error.ErrorText, error.FileName);
                                CompilationErrors = CompilationErrors.line(errorMessage);
                                "[CSharp_FastCompiler] Compilation Error: {0}".error(errorMessage);
                            }
                            DebugMode.ifError("Compilation failed");
                            this.invoke(onCompileFail);
                        }
                        else
                        {
                            DebugMode.ifDebug("Compilation was OK");
                            this.invoke(onCompileOK);
                        }
                        compiling = false;
                        compileSourceCode();
                    }
                }
                catch (Exception ex)
                {
                    ex.log("in compileSourceCode");
                    compiling = false;
                    FinishedCompilingCode.Set();
                }
            });
        }
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
            {
                return(null);
            }
            code = code.line();                 // make sure there is an empty line at the end

            try
            {
                // handle special incudes in source code
                foreach (var originalLine in code.lines())
                {
                    originalLine.starts("//include", (includeText) =>
                    {
                        if (includeText.fileExists())
                        {
                            code = code.Replace(originalLine, originalLine.line().add(includeText.contents()));
                        }
                    });
                }
                var snippetParser = new SnippetParser(SupportedLanguage.CSharp);

                var parsedCode = snippetParser.Parse(code);
                AstErrors       = snippetParser.errors();
                CompilationUnit = new CompilationUnit();

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method

                        var blockStatement = (BlockStatement)parsedCode;
                        CompilationUnit.add_Type(default_TypeName)
                        .add_Method(default_MethodName, InvocationParameters, blockStatement);

                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                        //astCSharp.AstDetails.mapSpecials();

                        // add references included in the original source code file
                        mapCodeO2References(astCSharp);

                        CreatedFromSnipptet = true;
                    }
                    else
                    {
                        CompilationUnit = (CompilationUnit)parsedCode;
                        if (CompilationUnit.Children.Count == 0)
                        {
                            return(null);
                        }

                        astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials);
                        // add the comments from the original code

                        mapCodeO2References(astCSharp);
                        CreatedFromSnipptet = false;
                    }

                    // create sourceCode using Ast_CSharp & AstDetails
                    if (CompilationUnit.Children.Count > 0)
                    {
                        // reset the astCSharp.AstDetails object
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);

                        SourceCode = astCSharp.AstDetails.CSharpCode;

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        AstDetails = tempAstDetails;
                        DebugMode.ifDebug("Ast parsing was OK");
                        this.invoke(onAstOK);
                        return(SourceCode);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);
            }
            return(null);
        }
예제 #5
0
        ///
        /// <summary>
        /// Returns a compilable C# file from and Snippet
        ///
        /// Dev Note:this code needs to be refactored (since it is too big and complex)
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code)
        {
            if (code.empty())
            {
                return(null);
            }
            code = code.line();                 // make sure there is an empty line at the end

            try
            {
                //handle special incudes in source code
                var lines = code.fix_CRLF().lines();
                foreach (var originalLine in lines)
                {
                    var line = originalLine;
                    if (originalLine.starts("//O2Include:"))
                    {
                        var includeText  = line.subString_After("//O2Include:");
                        var file         = includeText;
                        var baseFile     = CompilerOptions.SourceCodeFile ?? PublicDI.CurrentScript;
                        var parentFolder = baseFile.parentFolder();
                        if (parentFolder.notValid())
                        {
                            "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error();
                        }
                        var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file, parentFolder);
                        if (resolvedFile.fileExists())
                        {
                            var fileContents = resolvedFile.contents();
                            code = code.Replace(line, line.line().add(fileContents).line());
                        }
                        else
                        {
                            "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText);
                        }
                    }
                    ;
                }

                var snippetParser = new SnippetParser(SupportedLanguage.CSharp);

                var parsedCode = snippetParser.Parse(code);
                this.astErrors(snippetParser.errors());

                this.compilationUnit(new CompilationUnit());

                if (parsedCode is BlockStatement || parsedCode is CompilationUnit)
                {
                    Ast_CSharp astCSharp;
                    if (parsedCode is BlockStatement)
                    {
                        // map parsedCode into a new type and method
                        var blockStatement = (BlockStatement)parsedCode;

                        var csharpCode = blockStatement.ast_CSharp_CreateCompilableClass(snippetParser, code,
                                                                                         CompilerOptions, CompilerArtifacts, ExecutionOptions);

                        this.astDetails(new Ast_CSharp(csharpCode).AstDetails);
                        this.createdFromSnippet(true);
                        DebugMode.ifDebug("Ast parsing was OK");
                        this.sourceCode(csharpCode);
                        this.raise_OnAstOK();

                        return(csharpCode);
                    }


                    this.compilationUnit((CompilationUnit)parsedCode);
                    if (this.compilationUnit().Children.Count == 0)
                    {
                        return(null);
                    }

                    astCSharp = new Ast_CSharp(this.compilationUnit(), snippetParser.Specials);
                    // add the comments from the original code

                    astCSharp.mapCodeO2References(CompilerOptions);
                    this.createdFromSnippet(false);

                    // create sourceCode using Ast_CSharp & AstDetails
                    if (this.compilationUnit().Children.Count > 0)
                    {
                        // reset the astCSharp.AstDetails object
                        astCSharp.mapAstDetails();
                        // add the comments from the original code
                        astCSharp.ExtraSpecials.AddRange(snippetParser.Specials);

                        this.sourceCode(astCSharp.AstDetails.CSharpCode);

                        //once we have the created SourceCode we need to create a new AST with it
                        var tempAstDetails = new Ast_CSharp(this.sourceCode()).AstDetails;
                        //note we should try to add back the specials here (so that comments make it to the generated code
                        this.astDetails(tempAstDetails);
                        DebugMode.ifDebug("Ast parsing was OK");
                        this.raise_OnAstOK();
                        return(this.sourceCode());
                    }
                }
            }
            catch (Exception ex)
            {
                DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message);
            }
            return(null);
        }