public void ShouldResolveMethodOfExternalInterface()
 {
     var csharp = DecompilationResult.CreateFromDelegate <NullCursor, string>(_delegateReader, (cursor, args, keys) =>
     {
         ISomeInterface foo = new SomeInterace("abc");
         return(foo.Greeting("def"));
     });
     var redIL = _csharpCompiler.Compile(csharp) as RootNode;
 }
Example #2
0
        public IHandle <TRes> GetHandle <TRes>(Func <ICursor, RedisValue[], RedisKey[], TRes> action)
            where TRes : RedResult
        {
            var decompilation = _decompiler.Decompile(action);
            var redIL         = _csharpCompiler.Compile(decompilation);

            var handle = _luaHandler.CreateHandle <TRes>(redIL);

            return(handle);
        }
        public void ShouldResolveConstructor()
        {
            var csharp = DecompilationResult.CreateFromDelegate <NullCursor, bool>(_delegateReader, (cursor, args, keys) =>
            {
                var foo = new Foo <double>(3.5);
                return(true);
            });
            var redIL = _csharpCompiler.Compile(csharp) as RootNode;
            var block = redIL.Body as BlockNode;

            block.Children.Count.Should().Be(2);
            var varDec = block.Children.First() as VariableDeclareNode;

            varDec.Value.Should().BeEquivalentTo(new ConstantValueNode(DataValueType.Float, (double)3.5));
        }
Example #4
0
        public static ExtensionLoader BuildLoader <TCodeSource>(
            ILog logger,
            IEnumerable <ExtensionTypeRecord> typeRecords,
            IEnumerable <TCodeSource> selectedSources,
            IEnumerable <TCodeSource> additionalSources = null,
            CSharpCompilerOptions compilerOptions       = null,
            Options options = null)
            where TCodeSource : ICodeSource
        {
            options = options ?? new Options();
            var compiler            = new CSharpCompiler <TCodeSource>(compilerOptions ?? new CSharpCompilerOptions());
            var selectedSourcesList = selectedSources as IList <TCodeSource> ?? selectedSources.ToList();
            var results             = compiler.Compile(selectedSourcesList, additionalSources).ToDictionary(r => r.Source.UniqueName);

            var assemblies      = new List <Assembly>(results.Count);
            var orderedSelected = selectedSourcesList.Select(s => results[s.UniqueName]).ToList();

            if (options.InclusionStrategy == InclusionStrategy.AfterFirst)
            {
                // TODO: implement
                throw new NotImplementedException("non-None inclusion strategies not yet implemented, pull requests welcome.");
            }
            else if (options.InclusionStrategy == InclusionStrategy.AfterLast)
            {
                // TODO: implement
                throw new NotImplementedException("non-None inclusion strategies not yet implemented, pull requests welcome.");
            }

            return(new ExtensionLoader(logger, assemblies, typeRecords, options.ThrowOnConstructorMissing));
        }
Example #5
0
        public override string Render()
        {
            string executableCode = ((CSharpParser)parser).Parse(codeTemplate, variables, values);

            compiler.Compile(executableCode);
            return(compiler.Result);
        }
Example #6
0
        protected async Task <CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(
                fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories)
                .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(),
                ManagedAssets.FrameworkAssemblies.Concat(
                    AppDomain.CurrentDomain.GetAssemblies()
                    .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location))
                    .Select(each => each.Location)
                    .Concat(new[]
            {
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                             "Microsoft.Rest.ClientRuntime.dll"),
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                             "Microsoft.Rest.ClientRuntime.Azure.dll")
            })
                    ));
            var result = await compiler.Compile(OutputKind.DynamicallyLinkedLibrary);

            // if it failed compiling and we're in an interactive session
            if (!result.Succeeded && System.Environment.OSVersion.Platform == PlatformID.Win32NT && System.Environment.UserInteractive)
            {
                var error = result.Messages.FirstOrDefault(each => each.Severity == DiagnosticSeverity.Error);
                if (error != null)
                {
                    // use this to dump the files to disk for examination
                    // open in Favorite Code Editor
                    InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name), error.Location.GetMappedLineSpan());
                }
            }

            return(result);
        }
Example #7
0
        public FileCompileResult Compile(string fileToCompile)
        {
            CompileResult result;

            if (fileToCompile.EndsWith(".cs"))
            {
                var compiler       = new CSharpCompiler();
                var copiedFileName = fileToCompile + ".cs";
                File.Copy(fileToCompile, copiedFileName);
                result = compiler.Compile(this.csharpCompilerPath, copiedFileName, "/optimize+ /nologo /reference:System.Numerics.dll");
            }
            else if (fileToCompile.EndsWith(".zip"))
            {
                var compiler       = new MsBuildCompiler();
                var copiedFileName = fileToCompile + ".zip";
                File.Copy(fileToCompile, copiedFileName);
                result = compiler.Compile(this.msbuildCompilerPath, copiedFileName, "/t:rebuild /p:Configuration=Release,Optimize=true /verbosity:quiet /nologo");
            }
            else
            {
                throw new ArgumentException("Invalid file extension", "fileToCompile");
            }

            return(new FileCompileResult(result));
        }
Example #8
0
        protected async Task <Microsoft.Rest.CSharp.Compiler.Compilation.CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(fileSystem.GetFiles("", "*.cs", SearchOption.AllDirectories)
                                              .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadAllText(each))).ToArray(), _assemblies);

            return(await compiler.Compile(OutputKind.DynamicallyLinkedLibrary));
        }
Example #9
0
        static void CompilerTest(string[] args)
        {
            var compiler = new CSharpCompiler();
            var dllPath  = Path.GetFullPath("TestClasses") + CommonFolders.Sep + "TestApp.dll";
            var results  = compiler.Compile("TestApp", "TestClasses", new List <string> {
                Path.GetFullPath("TestClasses/TestClass1.cs"),
                Path.GetFullPath("TestClasses/TestClass2.cs")
            });

            foreach (CompilerError err in results.Errors)
            {
                Console.WriteLine($"{(err.IsWarning ? "WARNING :" : "ERROR  :")} {err.ErrorText}");
            }

            if (!results.Errors.HasErrors)
            {
                var loader = new AppDomainLoader("TestApp", dllPath);

                if (loader.IsLoaded)
                {
                    var testClass1 = loader.RunRemoteFunc <object>(() => {
                        Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationName);

                        return(null);
                    });
                }
            }
        }
Example #10
0
 public void CompileTest()
 {
     var compiler = new CSharpCompiler("test");
       var func = compiler.Compile("test.prop2 = test.prop;");
       dynamic test = new ExpandoObject();
       test.prop = "test";
       func(test, null);
       Assert.AreEqual(test.prop, test.prop2);
 }
Example #11
0
 public void ShouldResolveArrayLength()
 {
     var csharp = DecompilationResult.CreateFromDelegate <NullCursor, int>(_delegateReader, (cursor, args, keys) =>
     {
         var arr = new int[] { 1, 2, 3 };
         return(arr.Length);
     });
     var redIL = _csharpCompiler.Compile(csharp) as RootNode;
 }
Example #12
0
        public void CompileFailed()
        {
            var code = "class TestClass { void TestMethod() { var i = 0 } }";

            var ex = Assert.Throws <CompilationException>(() => CSharpCompiler.Compile("test", CSharpCompiler.ParseText(code)));

            Assert.Contains("Error", ex.Message);
            Assert.Contains("; expected", ex.Message);
        }
Example #13
0
            private static List <TreeItem <MemberInfo> > Collect(string code)
            {
                var assemblyName = Guid.NewGuid().ToString();
                var syntaxTree   = CSharpCompiler.ParseText(code);

                var(_, assembly) = CSharpCompiler.Compile(assemblyName, syntaxTree);
                var syntaxItems = CSharpHelper.CollectSyntax(syntaxTree.GetRoot());

                return(CSharpHelper.CollectMembers(assembly, syntaxItems));
            }
Example #14
0
        public void Create_process_code_should_can_be_compiled()
        {
            // Arrange
            using (var compiler = new CSharpCompiler())
            {
                // Act
                var asm = compiler.Compile(Code);

                // Assert
                asm.HasErrors.Should().BeFalse();
            }
        }
Example #15
0
        static void OkScenario(CSRunner.Base.Environment env)
        {
            var assembly = CSharpCompiler.Compile(env.CommandLine, (string errors, object[] parameters) =>
            {
                System.Console.WriteLine(string.Format(errors, parameters));
            });

            var runner         = assembly.ExportedTypes.Where(t => t.IsSubclassOf(typeof(Runner))).SingleOrDefault();
            var runnerInstance = Activator.CreateInstance(runner, new[] { env }) as Runner;

            runnerInstance.Run();
        }
Example #16
0
        internal static FileInfo CompileCodeIntoLocation(string source, IEnumerable <string> embeddedResources, IEnumerable <string> referencedAssemblies, DirectoryInfo location)
        {
            if (!location.Exists)
            {
                throw new ArgumentException(string.Format("Directory '{0}' does not exist", location.FullName), "location");
            }

            var binaryPath = Path.Combine(location.FullName, string.Format("{0}.dll", Guid.NewGuid()));

            CSharpCompiler.Compile(source, binaryPath, embeddedResources, referencedAssemblies);

            return(new FileInfo(binaryPath));
        }
Example #17
0
        public void LoadScripts()
        {
            string[] files = CSharpCompiler.GetScripts("*.cs");
            Console.WriteLine("Found {0} Scripts.", files.Length);
            CSharpCompiler.Compile(files);
            // So look for our new assembly
            string   dll = Path.Combine(ServerGlobals.BaseDirectory, "Scripts\\Scripts.dll");
            Assembly a   = Assembly.LoadFrom(dll);

            if (a != null)
            {
                ScriptResolver.LoadScriptObjects(a);
            }
        }
Example #18
0
 public void CompileThrowsCompilerExceptionTest()
 {
     var compiler = new CSharpCompiler("test");
       try
       {
     var func = compiler.Compile("not valid c# code");
     func(null, null);
     Assert.Fail();
       }
       catch (Exception err)
       {
     Assert.IsInstanceOfType(err, typeof(CompilerException));
       }
 }
Example #19
0
        /// <summary>
        /// Accepts a Function delegate and creates a non-initialized handle for executing the function
        /// </summary>
        /// <param name="function">A delegate with the function to execute</param>
        /// <typeparam name="TRes">The return type of the function</typeparam>
        /// <returns>A non-initialized handle for executing the function</returns>
        public IHandle <TRes> GetHandle <TRes>(Function <TCursor, TRes> function)
        {
            var decompilation = DecompilationResult.CreateFromDelegate(_delegateReader, function);
            var redIL         = _csharpCompiler.Compile(decompilation);

            // We create the Lua handle regardless of whether we in Debug or not
            // Because we still want to fail/throw if RedIL/Lua compilation has failed
            var luaHandle = _luaHandler.CreateHandle <TRes>(redIL);

            if (DebuggingEnabled && Debugger.IsAttached && !(DebugInstance is null))
            {
                return(new DebugHandle <TCursor, TRes>(luaHandle, DebugInstance, function));
            }

            return(luaHandle);
        }
Example #20
0
        public void Run_can_accept_vary_input(int size)
        {
            // Arrange
            var compiler = new CSharpCompiler();
            var asm      = compiler.Compile(Code);
            var path     = asm.PathToAssembly;

            var info = new SandboxRunInfo
            {
                LimitProcessCount = 1,
                MemoryLimitMb     = 150.0f,
                Path        = path,
                TimeLimitMs = 3000
            };

            // Act
            var ior = Sandbox.BeginRun(info);

            // Assert
            var input    = new string('林', size);
            var expected = string.Format("Hey {0}!", input);

            var writer    = new StreamWriter(ior.InputWriteStream);
            var writeTask = writer.WriteAsync(input).ContinueWith(a => writer.Close());

            var reader   = new StreamReader(ior.OutputReadStream);
            var readTask = reader.ReadToEndAsync();

            var res = Sandbox.EndRun(ior.InstanceHandle);

            writeTask.Wait();
            readTask.Wait();

            res.Succeed.Should().BeTrue();
            res.MemoryMb.Should().BeLessThan(info.MemoryLimitMb);
            res.TimeMs.Should().BeLessThan(info.TimeLimitMs);
            res.ExitCode.Should().Be(0);

            var actual = readTask.Result;

            actual.Should().Be(expected);

            Console.WriteLine("Time: {0}ms", res.TimeMs);
            Console.WriteLine("Memory: {0}MB", res.MemoryMb);

            compiler.Dispose();
        }
        private CompiledTypes Compile(
            IFieldResolverDescriptor[] resolverDescriptors,
            IDirectiveMiddlewareDescriptor[] middlewareDescriptors)
        {
            GeneratedClass resolverClass = _codeGenerator
                                           .Generate(resolverDescriptors);
            GeneratedClass middlewareClass = _codeGenerator
                                             .Generate(middlewareDescriptors);

            Assembly assembly = CSharpCompiler.Compile(
                resolverClass.SourceText,
                middlewareClass.SourceText);

            return(new CompiledTypes(
                       assembly.GetType(resolverClass.FullName),
                       assembly.GetType(middlewareClass.FullName)));
        }
        public void CSharpCompilerShouldWorkWhenGivenValidSourceCode()
        {
            const string Source = @"using System;
class Program
{
    static void Main()
    {
        Console.WriteLine(""It works!"");
    }
}";

            var compiler = new CSharpCompiler();
            var result = compiler.Compile(CSharpCompilerPath, FileHelpers.SaveStringToTempFile(Source), string.Empty);

            Assert.IsTrue(result.IsCompiledSuccessfully, "Compilation is not successful");
            Assert.IsFalse(string.IsNullOrWhiteSpace(result.OutputFile), "Output file is null");
            Assert.IsTrue(result.OutputFile.EndsWith(".exe"), "Output file does not ends with .exe");
        }
Example #23
0
        public void CSharpCompilerShouldWorkWhenGivenValidSourceCode()
        {
            const string Source = @"using System;
class Program
{
    static void Main()
    {
        Console.WriteLine(""It works!"");
    }
}";

            var compiler = new CSharpCompiler(CSharpCompilerProcessExitTimeOutMultiplier);
            var result   = compiler.Compile(CSharpCompilerPath, FileHelpers.SaveStringToTempFile(Source), string.Empty);

            Assert.IsTrue(result.IsCompiledSuccessfully, "Compilation is not successful");
            Assert.IsFalse(string.IsNullOrWhiteSpace(result.OutputFile), "Output file is null");
            Assert.IsTrue(result.OutputFile.EndsWith(".exe"), "Output file does not ends with .exe");
        }
Example #24
0
        protected async Task <CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(
                fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories)
                .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(),
                ManagedAssets.FrameworkAssemblies.Concat(
                    AppDomain.CurrentDomain.GetAssemblies()
                    .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location))
                    .Select(each => each.Location)
                    .Concat(new[]
            {
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                             "Microsoft.Rest.ClientRuntime.dll")
            })
                    ));

            return(await compiler.Compile(OutputKind.DynamicallyLinkedLibrary));
        }
Example #25
0
        private static List <Disassembler> GetFileDisassemblers(DisassembleFileOptions options, MessageWriter writer)
        {
            var begin = DateTime.Now;

            // Parsing

            writer.Write("; Parsing from file ... ");

            var syntaxTree = CSharpCompiler.ParseFrom(options.FilePath);
            var parsed     = DateTime.Now;

            writer.WriteLine($"done. ({Diff(begin, parsed)})");

            // Compiling

            writer.Write("; Compiling ... ");

            var compilationOptions = new CompilationOptions
            {
                SaveAssembly        = options.SaveAssembly,
                DisableOptimization = options.DisableOptimization
            };

            var assemblyName = Path.GetFileNameWithoutExtension(options.FilePath);

            var(_, assembly) = CSharpCompiler.Compile(assemblyName, syntaxTree, compilationOptions);
            var compiled = DateTime.Now;

            writer.WriteLine($"done. ({Diff(parsed, compiled)})");

            // Analyzing

            writer.Write("; Analyzing ... ");

            var syntaxItems   = CSharpHelper.CollectSyntax(syntaxTree.GetRoot());
            var memberItems   = CSharpHelper.CollectMembers(assembly, syntaxItems);
            var disassemblers = memberItems.Select(Disassembler.Create).ToList();
            var analyzed      = DateTime.Now;

            writer.WriteLine($"done. ({Diff(compiled, analyzed)})");
            writer.WriteLine("");

            return(disassemblers);
        }
Example #26
0
        public void Create_multiple_process_in_limit_should_be_ok(int limitCount, int createCount, bool result)
        {
            // Arrange
            using (var compiler = new CSharpCompiler())
            {
                var asm = compiler.Compile(Code);

                var info = new SandboxRunInfo
                {
                    LimitProcessCount = limitCount,
                    MemoryLimitMb     = 40.0f,
                    Path        = asm.PathToAssembly,
                    TimeLimitMs = 1000,
                };

                var ior = Sandbox.BeginRun(info);
                using (var writer = new StreamWriter(ior.InputWriteStream))
                {
                    writer.Write(createCount);
                }

                var res = Sandbox.EndRun(ior.InstanceHandle);

                res.Succeed.Should().BeTrue();

                if (result)
                {
                    res.ExitCode.Should().Be(0);
                }
                else
                {
                    res.ExitCode.Should().NotBe(0);
                }

                res.TimeMs.Should().BeLessThan(info.TimeLimitMs);
                res.MemoryMb.Should().BeLessThan(info.MemoryLimitMb);

                Console.WriteLine("Time: {0}ms", res.TimeMs);
                Console.WriteLine("Memory: {0}MB", res.MemoryMb);
                Console.WriteLine(info.Path);
                Thread.Sleep(10);
            }
        }
Example #27
0
        protected async Task <CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(fileSystem.GetFiles("", "*.cs", SearchOption.AllDirectories)
                                              .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadAllText(each))).ToArray(), _assemblies);
            var result = await compiler.Compile(OutputKind.DynamicallyLinkedLibrary);

#if false
            // if it failed compiling and we're in an interactive session
            if (!result.Succeeded && Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.UserInteractive)
            {
                var error = result.Messages.FirstOrDefault(each => each.Severity == DiagnosticSeverity.Error);
                if (error != null)
                {
                    // use this to dump the files to disk for examination
                    // open in Favorite Code Editor
                    InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name), error.Location.GetMappedLineSpan());
                }
            }
#endif
            return(result);
        }
Example #28
0
        public void Run_can_accept_unicode_input()
        {
            // Arrange
            var compiler = new CSharpCompiler();
            var asm      = compiler.Compile(Code);
            var path     = asm.PathToAssembly;

            var info = new SandboxRunInfo
            {
                LimitProcessCount = 1,
                MemoryLimitMb     = 10.0f,
                Path        = path,
                TimeLimitMs = 1000
            };

            // Act
            var ior = Sandbox.BeginRun(info);

            // Assert
            using (var writer = new StreamWriter(ior.InputWriteStream))
            {
                writer.WriteAsync("Flash中文");
            }
            var reader   = new StreamReader(ior.OutputReadStream);
            var readTask = reader.ReadToEndAsync();

            var res = Sandbox.EndRun(ior.InstanceHandle);

            readTask.Result.Should().Be("Hey Flash中文!");

            res.Succeed.Should().BeTrue();
            res.MemoryMb.Should().BeGreaterThan(0);
            res.TimeMs.Should().BeGreaterOrEqualTo(0);
            compiler.Dispose();

            Console.WriteLine("Time: {0}ms", res.TimeMs);
            Console.WriteLine("Memory: {0}MB", res.MemoryMb);
        }
Example #29
0
        public void CompilePassed()
        {
            var code = "class TestClass { void TestMethod() { var i = 0; } }";

            Assert.NotNull(CSharpCompiler.Compile("test", CSharpCompiler.ParseText(code)));
        }
Example #30
0
 private Action<object, object> Compile()
 {
     var compiler = new CSharpCompiler(Field);
       return compiler.Compile(_code);
 }