Пример #1
0
 public void CompilesHelloWorld()
 {
     var options = new Options() { Output = "hello.exe", Verbose = true };
     options.AddInput("hello.ceylon");
     var compiler = new RoslynCompiler();
     compiler.Compile(options);
 }
        public void Compile_SimpleTestScript_AddMethodReturnsCorrectValue()
        {
            var compiler = new RoslynCompiler();

            var outputStream = new MemoryStream();

            var compilationPackage = new CompilationPackage();

            compilationPackage.AddReferenceAssembly(typeof(ISimpleScript).Assembly);
            compilationPackage.SourceCodes.Add(new SourceCodeUnit(TestScripts.SimpleScript, "Test.cs"));

            var compilationOutput = new CompilationOutput(CompilationOutputKind.DynamicallyLinkedLibrary,
                                                          new StreamCompilationOutputData(outputStream));

            var compilerResult = compiler.Compile(compilationPackage, compilationOutput);

            Assert.Empty(compilerResult.Messages.Where(x => x.MessageType == CompilationMessageType.Error));

            var assembly = Assembly.Load(outputStream.ToArray());

            var simpleScript = assembly.CreateInstance(
                "CreativeCoders.CodeCompilation.UnitTests.TestData.SimpleScript") as ISimpleScript;

            var value = simpleScript?.AddIntegers(12, 34);

            Assert.Equal(46, value);
        }
        public void Compile()
        {
            if (State == AssemblyState.Compiling)
            {
                return;
            }

            State = AssemblyState.Compiling;
            State = RoslynCompiler.Compile(this) ? AssemblyState.Ready : AssemblyState.CompilingError;
        }
        public override Assembly CompileAssembly(out byte[] bytes)
        {
            RoslynCompiler compiler = new RoslynCompiler();

            foreach (Type type in Types)
            {
                compiler.AddAssemblyReference(type.Assembly.Location);
            }

            compiler.AddAssemblyReference(typeof(GraphType).Assembly.Location);

            bytes = compiler.Compile(AssemblyName ?? 8.RandomLetters(), new DirectoryInfo(SourceDirectoryPath));
            return(Assembly.Load(bytes));
        }
Пример #5
0
        public byte[] CompileFromSource(Action <float> callback = null)
        {
            RoslynCompiler compiler = new RoslynCompiler();

            using (Stream s = GitHub.DownloadRepo(Id, Commit, out string fileName))
                using (ZipArchive zip = new ZipArchive(s))
                {
                    callback?.Invoke(0);
                    for (int i = 0; i < zip.Entries.Count; i++)
                    {
                        ZipArchiveEntry entry = zip.Entries[i];
                        CompileFromSource(compiler, entry);
                        callback?.Invoke(i / (float)zip.Entries.Count);
                    }
                    callback?.Invoke(1);
                }
            return(compiler.Compile(assemblyName + '_' + Path.GetRandomFileName(), out _));
        }
Пример #6
0
        public void Test()
        {
            string         toCompile = @"using System;
namespace Bam.Net.Dynamic
{
    public class WorkerPropertyResolver
    {
        public WorkState WorkState { get; set; }

        public Job Job { get; set; }

        public {{PropertyType}} Resolve()
        {
            return Resolve({{PropertyResolverLambda}});
        }

        public {{PropertyType}} Resolve(Func<WorkState, Job> propertyResolver)
        {
            return propertyResolver(WorkState, Job);
        }
    }
}";
            RoslynCompiler compiler  = new RoslynCompiler();

            compiler.AddAssemblyReference(
                "C:\\bam\\nuget\\global\\runtime.win-x64.microsoft.netcore.app\\2.2.2\\runtimes\\win-x64\\lib\\netcoreapp2.2\\Microsoft.CSharp.dll");
            compiler.AddAssemblyReference(typeof(ExpandoObject).Assembly.Location);
            compiler.AddAssemblyReference("C:\\bam\\nuget\\global\\runtime.win-x64.microsoft.netcore.app\\2.2.2\\runtimes\\win-x64\\lib\\netcoreapp2.2\\System.Runtime.dll");
            compiler.AddAssemblyReference("C:\\bam\\nuget\\global\\runtime.win-x64.microsoft.netcore.app\\2.2.2\\runtimes\\win-x64\\lib\\netcoreapp2.2\\System.Core.dll");
            byte[]   assBytes       = compiler.Compile(toCompile.Sha1(), toCompile);
            Assembly compiled       = Assembly.Load(assBytes);
            Type     dynamicContext = compiled.GetTypes().FirstOrDefault();
            object   instance       = dynamicContext.Construct();

            Expect.IsNotNull(dynamicContext);
            object output = instance.Invoke("Fun", (Func <string>)(() => "baloney"));

            Expect.IsNotNull(output);
            Console.WriteLine(output.ToString());
        }
Пример #7
0
        public override Assembly GetAssembly()
        {
            if (Directory.Exists(Id))
            {
                RoslynCompiler compiler = new RoslynCompiler(FolderSettings.DebugBuild);
                bool           hasFile  = false;
                StringBuilder  sb       = new StringBuilder();
                sb.Append("Compiling files from ").Append(Id).Append(":").AppendLine();
                foreach (var file in GetProjectFiles(Id))
                {
                    using (FileStream fileStream = File.OpenRead(file))
                    {
                        hasFile = true;
                        string name = file.Substring(Id.Length + 1, file.Length - (Id.Length + 1));
                        sb.Append(name).Append(", ");
                        compiler.Load(fileStream, file);
                    }
                }

                if (hasFile)
                {
                    sb.Length -= 2;
                    LogFile.WriteLine(sb.ToString());
                }
                else
                {
                    throw new IOException("No files were found in the directory specified.");
                }

                byte[]   data = compiler.Compile(FriendlyName + '_' + Path.GetRandomFileName(), out byte[] symbols);
                Assembly a    = Assembly.Load(data, symbols);
                Version = a.GetName().Version;
                return(a);
            }

            throw new DirectoryNotFoundException("Unable to find directory '" + Id + "'");
        }
Пример #8
0
        public override void Add(Action <string> output = null, Action <string> error = null)
        {
            try
            {
                HashSet <FileInfo>         codeFiles = new HashSet <FileInfo>();
                HandlebarsTemplateRenderer renderer  = new HandlebarsTemplateRenderer(new HandlebarsEmbeddedResources(GetType().Assembly));
                RoslynCompiler             compiler  = new RoslynCompiler();
                ShellGenConfig             config    = GetConfig();

                Type baseType = null;
                if (!Arguments.Contains("generateBaseType"))
                {
                    Message("Searching current AppDomain for specified base type ({0})", output, config.BaseTypeName);
                    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        baseType = FindType(assembly, config.BaseTypeNamespace, config.BaseTypeName);
                        if (baseType != null)
                        {
                            Message("Found base type ({0}) in assembly ({1})", output, config.BaseTypeName, assembly.FullName);
                            break;
                        }
                    }
                }

                CommandLineDelegatedClassModel model = CommandLineDelegatedClassModel.Create(config.ConcreteTypeName, config.BaseTypeName);
                model.Namespace = config.Namespace;
                SetConcreteModelProperties(model.ConcreteClass, config);

                ShellDescriptor descriptor = new ShellDescriptor();
                if (baseType != null)
                {
                    descriptor = new ShellDescriptor(baseType);
                    model.SetMethods(baseType.GetMethods().Where(m => m.IsAbstract).Select(m => m.Name).ToArray());
                }
                else
                {
                    model.SetMethods(GetArgument("methodNames",
                                                 "Please enter the method names to define on the base type (comma separated).")
                                     .DelimitSplit(","));

                    compiler.AddAssemblyReference(typeof(IRegisterArguments));
                    EnsureBaseType(config.BaseTypeName, config.WriteTo, renderer, model, codeFiles);
                }
                model.SetBaseTypeName(config.BaseTypeName);

                GenerateDelegator(config.WriteTo, model.DelegatorClass, renderer, codeFiles);

                GenerateConcreteType(config.WriteTo, config.ConcreteTypeName, renderer, model.ConcreteClass, codeFiles);

                byte[] delegatorAssembly = compiler.Compile(config.ConcreteTypeName, codeFiles.ToArray());

                descriptor = ShellGenerationRepository.Save(descriptor);
                ShellWrapperAssembly wrapperAssembly = new ShellWrapperAssembly {
                    ShellDescriptorKey = descriptor.Key(), Base64Assembly = delegatorAssembly.ToBase64()
                };
                ShellGenerationRepository.Save(wrapperAssembly);
            }
            catch (Exception ex)
            {
                error(ex.Message);
                Exit(1);
            }
        }