Exemple #1
0
        private static object ConvertAndRunCode(
            EngineWrapper engine,
            Microsoft.CodeAnalysis.SyntaxNode csharpAstNode,
            string[] requiredImports = null)
        {
            var rewritten     = MultiLineLambdaRewriter.RewriteMultiLineLambdas(csharpAstNode);
            var pythonAst     = new CSharpToPythonConvert().Visit(rewritten);
            var convertedCode = PythonAstPrinter.PrintPythonAst(pythonAst);
            var extraImports  = requiredImports is null ? "" : string.Join("\r\n", requiredImports.Select(i => "import " + i));

            convertedCode = "import clr\r\n" + extraImports + "\r\n" + convertedCode;

            if (pythonAst is PyAst.SuiteStatement suiteStmt)
            {
                var pythonStatements = suiteStmt.Statements
                                       .Where(s => !(s is PyAst.FromImportStatement || s is PyAst.ImportStatement)).ToList();
                // If the AST contained only a function definition, run it
                if (pythonStatements.Count == 1 && pythonStatements.Single() is PyAst.FunctionDefinition funcDef)
                {
                    convertedCode += $"\r\n{funcDef.Name}()";
                }

                if (pythonStatements.Count >= 1 && pythonStatements.All(s => s is PyAst.ClassDefinition))
                {
                    var lastClassDef = (PyAst.ClassDefinition)pythonStatements.Last();
                    convertedCode += $"\r\n{lastClassDef.Name}()";
                }
            }
            var scope  = engine.Engine.CreateScope();
            var source = engine.Engine.CreateScriptSourceFromString(convertedCode, Microsoft.Scripting.SourceCodeKind.AutoDetect);

            return(source.Execute(scope));
        }
Exemple #2
0
        private static string ConvertCsharpAST(Microsoft.CodeAnalysis.SyntaxNode csharpAst)
        {
            var rewritten = MultiLineLambdaRewriter.RewriteMultiLineLambdas(csharpAst);
            var pythonAst = new CSharpToPythonConvert().Visit(rewritten);

            return(PythonAstPrinter.PrintPythonAst(pythonAst));
        }
        public static string PrintPythonAst(PyAst.Node node)
        {
            var printer = new PythonAstPrinter();

            printer.Visit(node);
            return(printer.stringBuilder.ToString());
        }
 public Indenter(PythonAstPrinter printer)
 {
     Printer = printer;
     printer.IndentLevel++;
 }