예제 #1
0
파일: Emit.cs 프로젝트: obiwanjacobi/Zsharp
        public static string Build(string projectPath)
        {
            var csCompiler = new CsCompiler()
            {
                Debug       = true,
                ProjectPath = projectPath,
            };

            var runtimePath = Path.Combine(
                // [test] net5.0/debug/bin/UnitTest/src
                "..", "..", "..", "..", "..",
                "Zsharp.Runtime",
                "bin",
                csCompiler.Debug ? "Debug" : "Release",
                csCompiler.Project.TargetFrameworkMoniker,
                ZsharpRuntime);

            csCompiler.Project.AddReference(runtimePath);

            var output = csCompiler.Compile(AssemblyName);

            Console.WriteLine(output);

            if (OutputHasErrors(output))
            {
                throw new ZsharpException($"Build Failed: {projectPath}");
            }

            return(csCompiler.Project.TargetPath);
        }
예제 #2
0
파일: Program.cs 프로젝트: ssinai1/rbfx
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: ScriptPlayer.exe /path/to/script.cs --extra --parameters");
            Console.WriteLine("  Script must contain static void Main(string[] args) method.");
            Console.WriteLine("  Extra parameters will be passed to compiled script.");
        }
        var    sourceCode = new List <string>();
        string scriptDirectory;

        if (File.Exists(args[0]))
        {
            scriptDirectory = Path.GetDirectoryName(Path.GetFullPath(args[0]));
        }
        else if (Directory.Exists(args[0]))
        {
            scriptDirectory = Path.GetFullPath(args[0]);
        }
        else
        {
            Console.WriteLine($"File or directory '{args[0]}' does not exist.");
            return;
        }
        var scriptDirInfo = new DirectoryInfo(scriptDirectory);

        foreach (FileInfo fi in scriptDirInfo.GetFiles("*.cs", SearchOption.AllDirectories))
        {
            sourceCode.Add(File.ReadAllText(fi.FullName));
        }

        Assembly assembly = CsCompiler.Compile(sourceCode, null, null);

        if (assembly != null)
        {
            foreach (Type type in assembly.GetTypes())
            {
                foreach (MethodInfo method in type.GetMethods())
                {
                    if (!method.IsStatic || method.Name != "Main" || method.ReturnType != typeof(void))
                    {
                        continue;
                    }

                    ParameterInfo[] parameters = method.GetParameters();
                    if (parameters.Length != 1 || parameters[0].ParameterType != typeof(string[]))
                    {
                        continue;
                    }

                    var scriptArgs = new string[args.Length - 1];
                    Array.Copy(args, 1, scriptArgs, 0, args.Length - 1);
                    method.Invoke(null, new object[] { scriptArgs });
                    return;
                }
            }
        }
    }
예제 #3
0
        public void ProjectRelease()
        {
            var path = Path.Combine(Path.GetDirectoryName(
                                        Assembly.GetExecutingAssembly().Location), "csout");

            var csc = new CsCompiler
            {
                ProjectPath = path,
                Debug       = false
            };

            var stdOutput = csc.Compile("CsTestAssembly");

            Console.WriteLine(stdOutput);

            File.Exists(csc.Project.TargetPath).Should().BeTrue();
        }
예제 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public EmitResultAssembly Compile(string assemblyName, out string filePath)
        {
            var generatedContext    = _codeGen.GenerateContext(assemblyName, _script);
            var generatedDonut      = _codeGen.GenerateDonut(assemblyName, _script);
            var generatedFeatureGen = _codeGen.GenerateFeatureGenerator(assemblyName, _script);

#if DEBUG
            WriteDonutCode(assemblyName, "DonutContext.cs", generatedContext);
            WriteDonutCode(assemblyName, "DonutFile.cs", generatedDonut);
            WriteDonutCode(assemblyName, "FeatureEmitter.cs", generatedFeatureGen);
#endif
            var builder = new CsCompiler(assemblyName, _assembliesDir);
            //Add our reference libs
            builder.AddReferenceFromType(typeof(BsonDocument));
            builder.AddReferenceFromType(typeof(DonutContext));
            builder.AddReferenceFromType(typeof(CacheSet <>));
            builder.AddReferenceFromType(typeof(Dictionary <,>));
            builder.AddReferenceFromType(typeof(IServiceProvider));
            //builder.AddReferenceFromType(typeof(nvoid.extensions.Arrays));
            builder.AddReferenceFromType(typeof(System.Linq.Enumerable));
            builder.AddReferenceFromType(typeof(TransformBlock <,>));
            builder.AddReferenceFromType(typeof(IMongoCollection <>));
            builder.AddReferenceFromType(typeof(IRedisCacher));
            var clrDep =
                Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
            var asmCollections = Assembly.Load("System.Collections");
            var asmMongo       = Assembly.Load("MongoDB.Driver.Core");
            var asmTasks       = Assembly.Load("System.Threading.Tasks");
            builder.AddReference(clrDep);
            builder.AddReference(asmCollections);
            builder.AddReference(asmMongo);
            builder.AddReference(asmTasks);
#if DEBUG
            var projectDefinition = builder.GenerateProjectDefinition(assemblyName, _script);
            WriteDonutCode(assemblyName, $"{assemblyName}.csproj", projectDefinition);
#endif
            var sources = new List <SourceContent>();
            sources.Add(new SourceContent(generatedContext, "DonutContext.cs"));
            sources.Add(new SourceContent(generatedDonut, "DonutFile.cs"));
            sources.Add(new SourceContent(generatedFeatureGen, "FeatureEmitter.cs"));
            var emitResult = builder.Compile(sources.ToArray());
            filePath = builder.Filepath;
            return(emitResult);
        }
예제 #5
0
        public void Compile_should_dinamically_compile_and_execute_code()
        {
            var          externalAssemblyRef = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Grappachu.Core.dll");
            const string code = @"
                using System;
                using Grappachu.Core.Lang.Domain;

                namespace Test
                {
                    public class FooClass
                    {
                        public static MessageArgs GetData(int value)
                        {
                              return new MessageArgs(""Runned on: ""+DateTime.Now.ToString(""dd-MM-yyyy"")+"" with param ""+value);
                        }
                    }
                }
            ";

            var val = CsCompiler.Compile(code, new[] { externalAssemblyRef })
                      .Run <MessageArgs>("Test.FooClass", "GetData", new object[] { 5 });

            val.Message.Should().Be.EqualTo($"Runned on: {DateTime.Now:dd-MM-yyyy} with param 5");
        }
예제 #6
0
        public string Compile(string filePath, string configuration, string outputAssemblyPath, string[] references)
        {
            var console = new StringBuilder();

            // parse code and build AST
            var code       = File.ReadAllText(filePath);
            var moduleName = Path.GetFileNameWithoutExtension(filePath);
            var messages   = ParseAst(filePath, moduleName, code);

            foreach (var message in messages)
            {
                console.AppendLine(message.ToString());
            }

            if (messages.HasErrors())
            {
                return(console.ToString());
            }

            var assemblyName = Path.GetFileNameWithoutExtension(outputAssemblyPath);
            var outputDir    = Path.GetDirectoryName(outputAssemblyPath) ?? ".\\";
            var module       = Context.Modules.Modules.First();
            var emit         = new EmitCode(assemblyName);

            emit.Visit(module);

            var csFile     = $"{assemblyName}.cs";
            var csFilePath = String.IsNullOrEmpty(outputDir) ? csFile : Path.Combine(outputDir, csFile);

            emit.SaveAs(csFilePath);

            var csCompiler = new CsCompiler()
            {
                Debug       = configuration == "Debug",
                ProjectPath = outputDir,
            };

            foreach (var reference in references)
            {
                csCompiler.Project.AddReference(reference);
            }

            csCompiler.Project.Executable = true;
            var buildOutput = csCompiler.Compile(assemblyName);

            if (buildOutput.Contains("Build FAILED") ||
                buildOutput.Contains("error"))
            {
                console.AppendLine();
                console.AppendLine($"Error: Generating Assembly {assemblyName} failed.");
                console.AppendLine();
                console.AppendLine(buildOutput);
            }
            else
            {
                console.AppendLine();
                console.AppendLine($"Compiled Z# assembly: {csCompiler.Project.TargetPath}");
            }

            return(console.ToString());
        }