private IView CompileAndInstance(string code, Assembly modelAssembly) { modelAssembly = modelAssembly ?? Assembly.GetEntryAssembly(); var compilation = CSharpCompilation.Create("AppViewAssembly") .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(typeof(Object).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(typeof(IView).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(Assembly.GetEntryAssembly().Location)) .AddReferences(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("netstandard")).Location)) .AddReferences(MetadataReference.CreateFromFile(modelAssembly.Location)); var netStandartAssembly = Assembly.Load(new AssemblyName("netstandart")).GetReferencedAssemblies(); foreach (var assembly in netStandartAssembly) { compilation.AddReferences(MetadataReference.CreateFromFile(Assembly.Load(assembly).Location)); } compilation = compilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); using (var memoryStream = new MemoryStream()) { var compilationResult = compilation.Emit(memoryStream); if (!compilationResult.Success) { var errors = compilationResult.Diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error); var errorsHtml = new StringBuilder(); errorsHtml.AppendLine($"<h1>{errors.Count()} errors:</h1>"); foreach (var error in errors) { errorsHtml.AppendLine($"<div>{error.Location} => {error.GetMessage()}</div>"); } errorsHtml.AppendLine($"<pre>{WebUtility.HtmlEncode(code)}</pre>"); return(new ErrorView(errorsHtml.ToString())); } memoryStream.Seek(0, SeekOrigin.Begin); var assemblyBytes = memoryStream.ToArray(); var assembly = Assembly.Load(assemblyBytes); var type = assembly.GetType("AppViewContentNamespace.AppViewCode"); if (type == null) { Console.WriteLine("AppViewCode not found."); return(null); } var instance = Activator.CreateInstance(type); if (instance == null) { Console.WriteLine("AppViewCode cannot be instanciated."); return(null); } return(instance as IView); } }
public List <IndicatorValue> CalculateIndicatorValues(string Formula, int IndicatorId) { List <IndicatorValue> indicatorValues = new List <IndicatorValue>(); string formula_test = Formula; List <Region> regions = _context.Region.ToList(); foreach (var region in regions) { IndicatorValue indicatorValue = _context.IndicatorValue.AsNoTracking().FirstOrDefault(iv => iv.RegionId == region.Id && iv.IndicatorId == IndicatorId); if (indicatorValue == null) { indicatorValue = new IndicatorValue() { Id = 0, IndicatorId = IndicatorId }; } indicatorValue.RegionId = region.Id; indicatorValue.Region = region; indicatorValue.Year = region.Year; indicatorValues.Add(indicatorValue); } // => calculate values string code = $"decimal?[] r = new decimal?[{indicatorValues.Count().ToString()}];"; for (int i = 0; i < indicatorValues.Count(); i++) { code += @" "; string formula_code = formula_test; while (formula_code.IndexOf("Area") >= 0) { formula_code = formula_code.Replace("Area", indicatorValues[i].Region.Area.ToString()); } while (formula_code.IndexOf("Population") >= 0) { formula_code = formula_code.Replace("Population", indicatorValues[i].Region.Area.ToString()); } while (formula_code.IndexOf("$") >= 0) { DollarRate dollarRate = _context.DollarRate.AsNoTracking().FirstOrDefault(d => d.Year == indicatorValues[i].Region.Year); decimal? dollarRateValue = dollarRate == null ? null : dollarRate.Value; formula_code = formula_code.Replace("$", dollarRateValue == null ? "null" : dollarRateValue.ToString()); } while (formula_code.IndexOf("Min") >= 0) { int M = formula_code.IndexOf("Min"), I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M), d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I); int indicatorId = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1)); ReferencePoint referencePoint = _context.ReferencePoint .FirstOrDefault(r => r.IndicatorId == indicatorId); decimal referencePointValue = referencePoint != null ? referencePoint.Min : 0; formula_code = formula_code.Remove(M, d - M + 1 + 1); formula_code = formula_code.Insert(M, referencePointValue.ToString()); } while (formula_code.IndexOf("Max") >= 0) { int M = formula_code.IndexOf("Max"), I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M), d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I); int indicatorId = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1)); ReferencePoint referencePoint = _context.ReferencePoint .FirstOrDefault(r => r.IndicatorId == indicatorId); decimal referencePointValue = referencePoint != null ? referencePoint.Max : 0; formula_code = formula_code.Remove(M, d - M + 1 + 1); formula_code = formula_code.Insert(M, referencePointValue.ToString()); } while (formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]) >= 0) { int I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]), d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"]); int indicatorId = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1)); IndicatorValue indicatorValue = _context.IndicatorValue .AsNoTracking() .FirstOrDefault(iv => iv.IndicatorId == indicatorId && iv.RegionId == indicatorValues[i].RegionId && iv.Year == indicatorValues[i].Year); decimal?indicatorValueValue = indicatorValue != null ? indicatorValue.Value : null; string indicatorValueValueString = indicatorValueValue != null?indicatorValueValue.ToString() : "null"; formula_code = formula_code.Remove(I, d - I + 1); formula_code = formula_code.Insert(I, indicatorValueValueString); } formula_code = formula_code.Replace(',', '.'); for (int j = formula_code.Length - 1; j >= 0; j--) { bool insert = false; if (Char.IsDigit(formula_code[j])) { insert = true; } if (j != formula_code.Length - 1) { if (formula_code[j + 1] == '.' || Char.IsDigit(formula_code[j + 1])) { insert = false; } } if (insert) { formula_code = formula_code.Insert(j + 1, "M"); } } if (formula_code.Contains("null")) { formula_code = "null"; } code += $"r[{i.ToString()}] = null;" + "try{" + $"r[{i.ToString()}] = (decimal?)({formula_code});" + "} catch { }"; } string codeToCompile = @"using System; namespace RoslynCompile { public class Calculator { public decimal?[] Calculate() { " + code + @" return r; } } }"; SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile); string assemblyName = Path.GetRandomFileName(); MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location) }; CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); indicatorValues = new List <IndicatorValue>(); } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); var type = assembly.GetType("RoslynCompile.Calculator"); var instance = assembly.CreateInstance("RoslynCompile.Calculator"); var meth = type.GetMember("Calculate").First() as MethodInfo; decimal?[] r = meth.Invoke(instance, null) as decimal?[]; for (int i = 0; i < indicatorValues.Count(); i++) { indicatorValues[i].Value = r[i]; } } } // <= return(indicatorValues); }
public void Generate_test() { var compilation = CSharpCompilation.Create("test"); //R4MvcGenerator.Generate(compilation); }
/// <summary> /// CreateCompilation creates a CSharpCompilation /// </summary> /// <param name="source">string of source code</param> /// <returns></returns> private static Compilation CreateCompilation(string source) => CSharpCompilation.Create( assemblyName: "compilation", syntaxTrees: new[] { CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Preview)) }, references: new[] { MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location) }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
public string RewriteAndMerge(string[] paths, string[] additionalAssemblyNames = null, string[] excludeTypes = null) { var syntaxTrees = paths .Select(p => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(p)).WithFilePath(p)) .Select(c => c.WithRootAndOptions(UpdateUsings(c.GetCompilationUnitRoot()), c.Options)) .ToArray(); var references = new List <MetadataReference>() { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(Queryable).GetTypeInfo().Assembly.Location) }; if (additionalAssemblyNames != null) { var assemblyPath = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location); log.LogMessage("FrameworkPath: " + assemblyPath); if (assemblyPath == null) { throw new InvalidOperationException(); } var facadesLoaded = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); var loadedAssemblies = new List <string>(); references.AddRange(additionalAssemblyNames.SelectMany(n => { var results = new List <MetadataReference>(); if (File.Exists(n)) { var facadesPath = Path.Combine(Path.GetDirectoryName(n) ?? "", "Facades"); results.Add(MetadataReference.CreateFromFile(n)); loadedAssemblies.Add(n); if (Directory.Exists(facadesPath) && !facadesLoaded.Contains(facadesPath)) { facadesLoaded.Add(facadesPath); results.AddRange(Directory.GetFiles(facadesPath).Select(facadeDll => MetadataReference.CreateFromFile(facadeDll))); } return(results); } if (File.Exists(Path.Combine(assemblyPath, n))) { results.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, n))); return(results); } log.LogError($"Could find ResolveProjectReferencesResolveProjectReferencesreferenced assembly: {n}"); return(results); }).Where(c => c != null)); log.LogMessage($"Loaded assemblies: {string.Join(",", loadedAssemblies)}"); } var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); this.compilation = CSharpCompilation .Create("Temp", syntaxTrees, references, options); this.lookup = new CompilationLookup(this.compilation); var retval = this.RewriteAndMerge(syntaxTrees, compilation, excludeTypes).ToString(); #if OUTPUT_COMPILER_ERRORS var emitResult = this.compilation.Emit(Stream.Null); if (emitResult.Diagnostics.Any()) { log.LogMessage("Compiler errors:"); foreach (var diagnostic in emitResult.Diagnostics) { var message = diagnostic.GetMessage(); if (diagnostic.Severity == DiagnosticSeverity.Info) { log.LogError(message); } else { log.LogMessage(message); } } } #endif return(retval); }
private IView GenerateExecutableCоde(string csharpCode, object viewModel) { var compileResult = CSharpCompilation.Create("ViewAssembly") .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(typeof(IView).Assembly.Location)); if (viewModel != null) { if (viewModel.GetType().IsGenericType) { var genericArguments = viewModel.GetType().GenericTypeArguments; foreach (var genericArgument in genericArguments) { compileResult = compileResult .AddReferences(MetadataReference.CreateFromFile(genericArgument.Assembly.Location)); } } compileResult = compileResult .AddReferences(MetadataReference.CreateFromFile(viewModel.GetType().Assembly.Location)); } var libraries = Assembly.Load( new AssemblyName("netstandard")).GetReferencedAssemblies(); foreach (var library in libraries) { compileResult = compileResult .AddReferences(MetadataReference.CreateFromFile( Assembly.Load(library).Location)); } compileResult = compileResult.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(csharpCode)); using (MemoryStream memoryStream = new MemoryStream()) { EmitResult result = compileResult.Emit(memoryStream); if (!result.Success) { return(new ErrorView(result.Diagnostics .Where(x => x.Severity == DiagnosticSeverity.Error) .Select(x => x.GetMessage()), csharpCode)); } try { memoryStream.Seek(0, SeekOrigin.Begin); var byteAssembly = memoryStream.ToArray(); var assembly = Assembly.Load(byteAssembly); var viewType = assembly.GetType("ViewNamespace.ViewClass"); var instance = Activator.CreateInstance(viewType); return((instance as IView) ?? new ErrorView(new List <string> { "Instance is null!" }, csharpCode)); } catch (Exception ex) { return(new ErrorView(new List <string> { ex.ToString() }, csharpCode)); } } }
/// <inheritdoc/> public byte[] Compile(string code, IEnumerable <KeyValuePair <string, string> > metadataPropertyKeys) { _ = code ?? throw new ArgumentNullException(nameof(code)); // Parse the code code = Parse(code, metadataPropertyKeys, _executionState); // Get the compilation CSharpParseOptions parseOptions = new CSharpParseOptions(); SourceText sourceText = SourceText.From(code, Encoding.UTF8); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceText, parseOptions, AssemblyName); CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic> { // ensure that specific warnings about assembly references are always suppressed // https://github.com/dotnet/roslyn/issues/5501 { "CS1701", ReportDiagnostic.Suppress }, { "CS1702", ReportDiagnostic.Suppress }, { "CS1705", ReportDiagnostic.Suppress }, // we don't care about unreachable code { "CS0162", ReportDiagnostic.Suppress }, }); // Get reference assemblies CompilationReferences references = new CompilationReferences(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { references.TryAddReference(assembly); } foreach (Assembly assembly in _executionState.ClassCatalog.GetAssemblies()) { references.TryAddReference(assembly); } references.TryAddReference(Assembly.GetEntryAssembly(), true); references.TryAddReference(Assembly.GetCallingAssembly(), true); references.TryAddReference(Assembly.GetExecutingAssembly(), true); // Create the compilation string assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); CSharpCompilation compilation = CSharpCompilation.Create(AssemblyName, new[] { syntaxTree }, references, compilationOptions); // For some reason, Roslyn really wants these added by filename // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime compilation = compilation.AddReferences( MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))); // Emit the assembly ILogger logger = _executionState.Services.GetRequiredService <ILogger <ScriptHelper> >(); using (MemoryStream ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); // Log warnings List <string> warningMessages = result.Diagnostics .Where(x => x.Severity == DiagnosticSeverity.Warning) .Select(GetCompilationErrorMessage) .ToList(); if (warningMessages.Count > 0) { logger.LogWarning( "{0} warnings compiling script:{1}{2}", warningMessages.Count, Environment.NewLine, string.Join(Environment.NewLine, warningMessages)); } // Log errors List <string> errorMessages = result.Diagnostics .Where(x => x.Severity == DiagnosticSeverity.Error) .Select(GetCompilationErrorMessage) .ToList(); if (errorMessages.Count > 0) { logger.LogError( "{0} errors compiling script:{1}{2}", errorMessages.Count, Environment.NewLine, string.Join(Environment.NewLine, errorMessages)); } // Throw for errors or not success if (!result.Success || errorMessages.Count > 0) { throw new ScriptCompilationException(errorMessages); } ms.Seek(0, SeekOrigin.Begin); return(ms.ToArray()); } }
// </Snippet1> static void Main(string[] args) { // <Snippet2> SyntaxTree tree = CSharpSyntaxTree.ParseText(programText); var root = (CompilationUnitSyntax)tree.GetRoot(); // </Snippet2> // <Snippet3> var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences(MetadataReference.CreateFromFile( typeof(string).Assembly.Location)) .AddSyntaxTrees(tree); // </Snippet3> // <Snippet4> SemanticModel model = compilation.GetSemanticModel(tree); // </Snippet4> // <Snippet5> // Use the syntax tree to find "using System" UsingDirectiveSyntax usingSystem = root.Usings[0]; NameSyntax systemName = usingSystem.Name; // Use the semantic model for symbol information: SymbolInfo nameInfo = model.GetSymbolInfo(systemName); // </Snippet5> // <Snippet6> var systemSymbol = (INamespaceSymbol)nameInfo.Symbol; foreach (INamespaceSymbol ns in systemSymbol.GetNamespaceMembers()) { Console.WriteLine(ns.Name); } // </Snippet6> // <Snippet7> // Use the syntax model to find the literal string: LiteralExpressionSyntax helloWorldString = root.DescendantNodes() .OfType <LiteralExpressionSyntax>() .Single(); // Use the semantic model for type information: TypeInfo literalInfo = model.GetTypeInfo(helloWorldString); // </Snippet7> // <Snippet8> var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type; // </Snippet8> Console.Clear(); // build the linq query in steps: // Exploratory code. You can look at the variables // from each step in the query to gain more understanding // of the logic to find the correct method names. // <Snippet9> var allMembers = stringTypeSymbol.GetMembers(); // </Snippet9> // <Snippet10> var methods = allMembers.OfType <IMethodSymbol>(); // </Snippet10> // <Snippet11> var publicStringReturningMethods = methods .Where(m => m.ReturnType.Equals(stringTypeSymbol) && m.DeclaredAccessibility == Accessibility.Public); // </Snippet11> // <Snippet12> var distinctMethods = publicStringReturningMethods.Select(m => m.Name).Distinct(); // </Snippet12> // <Snippet13> foreach (string name in (from method in stringTypeSymbol .GetMembers().OfType <IMethodSymbol>() where method.ReturnType.Equals(stringTypeSymbol) && method.DeclaredAccessibility == Accessibility.Public select method.Name).Distinct()) { Console.WriteLine(name); } // </Snippet13> }
private static void Main(string[] args) { string code = "using System; using System.Linq; namespace InMemoryApp {class Program{private static void Main(string[] args){ foreach (string arg in args) {Console.WriteLine(arg);} args.Where(x => !string.IsNullOrEmpty(x)); dynamic number = 1; Console.WriteLine(number);} } }"; var syntaxTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.CSharp8)); string basePath = Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location); var root = syntaxTree.GetRoot() as CompilationUnitSyntax; var references = root.Usings; var referencePaths = new List <string> { typeof(object).GetTypeInfo().Assembly.Location, typeof(Console).GetTypeInfo().Assembly.Location, Path.Combine(basePath, "System.Runtime.dll"), Path.Combine(basePath, "System.Runtime.Extensions.dll"), Path.Combine(basePath, "mscorlib.dll"), Path.Combine(basePath, "Microsoft.CSharp.dll"), Path.Combine(basePath, "System.Linq.Expressions.dll"), Path.Combine(basePath, "netstandard.dll") }; referencePaths.AddRange(references.Select(x => Path.Combine(basePath, $"{x.Name}.dll"))); var executableReferences = new List <PortableExecutableReference>(); foreach (var reference in referencePaths) { if (File.Exists(reference)) { executableReferences.Add(MetadataReference.CreateFromFile(reference)); } } var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, executableReferences, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); using (var memoryStream = new MemoryStream()) { EmitResult compilationResult = compilation.Emit(memoryStream); if (!compilationResult.Success) { var errors = compilationResult.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)?.ToList() ?? new List <Diagnostic>(); foreach (var error in errors) { Console.WriteLine(error.GetMessage()); } } else { memoryStream.Seek(0, SeekOrigin.Begin); AssemblyLoadContext assemblyContext = new AssemblyLoadContext(Path.GetRandomFileName(), true); Assembly assembly = assemblyContext.LoadFromStream(memoryStream); var entryPoint = compilation.GetEntryPoint(CancellationToken.None); var type = assembly.GetType($"{entryPoint.ContainingNamespace.MetadataName}.{entryPoint.ContainingType.MetadataName}"); var instance = assembly.CreateInstance(type.FullName); var method = type.GetMethod(entryPoint.MetadataName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); method.Invoke(instance, BindingFlags.InvokeMethod, Type.DefaultBinder, new object[] { new string[] { "abc" } }, null); assemblyContext.Unload(); } } }
public void BuildTo(BuildType type) { SyntaxTree systree = CSharpSyntaxTree.ParseText(input.Text); Assembly[] assemblies = new List <Assembly> { typeof(object).GetTypeInfo().Assembly, typeof(Console).GetTypeInfo().Assembly, typeof(Enumerable).GetTypeInfo().Assembly, typeof(File).GetTypeInfo().Assembly, typeof(Assembly).GetTypeInfo().Assembly, typeof(CSharpArgumentInfo).GetTypeInfo().Assembly, typeof(CSharpSyntaxTree).GetTypeInfo().Assembly, typeof(System.Dynamic.CallInfo).GetTypeInfo().Assembly, typeof(RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ConvertBinder).GetTypeInfo().Assembly, typeof(ExpressionType).GetTypeInfo().Assembly, typeof(MessageBox).GetTypeInfo().Assembly, //Assembly.Load(new AssemblyName("Microsoft.CSharp")), //Assembly.Load(new AssemblyName("netstandard")), //Assembly.Load(new AssemblyName("System.Dynamic.Runtime")), //Assembly.Load(new AssemblyName("System.Runtime")), //Assembly.Load(new AssemblyName("mscorlib")) }.Distinct().ToArray(); string[] assemblyPaths = new string[assemblies.Length]; for (int x = 0; x < assemblies.Length; x++) { assemblyPaths[x] = assemblies[x].Location; } List <PortableExecutableReference> references = assemblyPaths.Select (r => MetadataReference.CreateFromFile(r)).ToList(); CSharpCompilationOptions options; if (type == BuildType.DLL) { options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); } else { options = new CSharpCompilationOptions(OutputKind.ConsoleApplication); } CSharpCompilation compilation = CSharpCompilation.Create( "csharptestbuild", syntaxTrees: new[] { systree }, references: references, options: options); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); DisplayErrors(failures); return; } else { SaveFileDialog sfd = new SaveFileDialog(); if (type == BuildType.DLL) { sfd.Filter = "Assembly (*.dll)|*.dll"; } if (type == BuildType.EXE) { sfd.Filter = "Executable (*.exe)|*.exe"; } if (sfd.ShowDialog() != DialogResult.OK) { return; } File.WriteAllBytes(sfd.FileName, ms.ToArray()); } } }
// 根据生成的类,动态编译把json转成protobuf private static void ExportExcelProtobuf(ConfigType configType) { string classPath = GetClassDir(configType); List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); List <string> protoNames = new List <string>(); foreach (string classFile in Directory.GetFiles(classPath, "*.cs")) { protoNames.Add(Path.GetFileNameWithoutExtension(classFile)); syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile))); } List <PortableExecutableReference> references = new List <PortableExecutableReference>(); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { if (assembly.IsDynamic) { continue; } if (assembly.Location == "") { continue; } } catch (Exception e) { Console.WriteLine(e); throw; } PortableExecutableReference reference = MetadataReference.CreateFromFile(assembly.Location); references.Add(reference); } CSharpCompilation compilation = CSharpCompilation.Create( null, syntaxTrees.ToArray(), references.ToArray(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using MemoryStream memSteam = new MemoryStream(); EmitResult emitResult = compilation.Emit(memSteam); if (!emitResult.Success) { StringBuilder stringBuilder = new StringBuilder(); foreach (Diagnostic t in emitResult.Diagnostics) { stringBuilder.AppendLine(t.GetMessage()); } throw new Exception($"动态编译失败:\n{stringBuilder}"); } memSteam.Seek(0, SeekOrigin.Begin); Assembly ass = Assembly.Load(memSteam.ToArray()); string dir = GetProtoDir(configType); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (string protoName in protoNames) { Type type = ass.GetType($"ET.{protoName}Category"); Type subType = ass.GetType($"ET.{protoName}"); Serializer.NonGeneric.PrepareSerializer(type); Serializer.NonGeneric.PrepareSerializer(subType); string json = File.ReadAllText(Path.Combine(string.Format(jsonDir, configType), $"{protoName}.txt")); object deserialize = BsonSerializer.Deserialize(json, type); string path = Path.Combine(dir, $"{protoName}Category.bytes"); using FileStream file = File.Create(path); Serializer.Serialize(file, deserialize); } }
// events private void RunToolStripMenuItem_Click(object sender, EventArgs e) { SyntaxTree systree = CSharpSyntaxTree.ParseText(input.Text); Assembly[] assemblies = new List <Assembly> { typeof(object).GetTypeInfo().Assembly, typeof(Console).GetTypeInfo().Assembly, typeof(Enumerable).GetTypeInfo().Assembly, typeof(File).GetTypeInfo().Assembly, typeof(Assembly).GetTypeInfo().Assembly, typeof(CSharpArgumentInfo).GetTypeInfo().Assembly, typeof(CSharpSyntaxTree).GetTypeInfo().Assembly, typeof(System.Dynamic.CallInfo).GetTypeInfo().Assembly, typeof(RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ConvertBinder).GetTypeInfo().Assembly, typeof(ExpressionType).GetTypeInfo().Assembly, typeof(MessageBox).GetTypeInfo().Assembly, //Assembly.Load(new AssemblyName("Microsoft.CSharp")), //Assembly.Load(new AssemblyName("netstandard")), //Assembly.Load(new AssemblyName("System.Dynamic.Runtime")), //Assembly.Load(new AssemblyName("System.Runtime")), //Assembly.Load(new AssemblyName("mscorlib")) }.Distinct().ToArray(); string[] assemblyPaths = new string[assemblies.Length]; for (int x = 0; x < assemblies.Length; x++) { assemblyPaths[x] = assemblies[x].Location; } List <PortableExecutableReference> references = assemblyPaths.Select (r => MetadataReference.CreateFromFile(r)).ToList(); var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); CSharpCompilation compilation = CSharpCompilation.Create( "csharptestbuild", syntaxTrees: new[] { systree }, references: references, options: options); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); DisplayErrors(failures); return; } else { ms.Flush(); ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); var type = assembly.GetTypes()[0]; if (!type.GetMethods().Any(mi => mi.IsStatic)) { MessageBox.Show("No (PUBLIC STATIC) method found to use as the entry point."); return; } var methd = type.GetMethods().First(mi => mi.IsStatic) as MethodInfo; try { bool alloc = allocConsoleToolStripMenuItem.Checked; IntPtr consoleHandle = IntPtr.Zero; if (alloc) { consoleHandle = GetConsoleWindow(); Console.Clear(); ShowWindow(consoleHandle, SW_SHOW); } methd.Invoke(null, new object[] { new string[] { "Hello", "World!" } }); if (consoleHandle != IntPtr.Zero) { ShowWindow(consoleHandle, SW_HIDE); } } catch (Exception exc) { MessageBox.Show(exc.Message, "Runtime Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } }
public void RollbackProcess_ShouldRollbackAllCompileErrors() { var syntaxTree = CSharpSyntaxTree.ParseText(@"using System; namespace ExampleProject { public class Calculator { public string Subtract(string first, string second) { if(Environment.GetEnvironmentVariable(""ActiveMutation"") == ""6"") { while (first.Length > 2) { return first - second; } while (first.Length < 2) { return second + first; } return null; } else { while (first.Length > 2) { return first + second; } while (first.Length < 2) { return System.Environment.GetEnvironmentVariable(""ActiveMutation"") == ""7"" ? second - first : second + first; } return null; } } } }"); var root = syntaxTree.GetRoot(); var mutantIf1 = root.DescendantNodes().OfType <IfStatementSyntax>().First(); root = root.ReplaceNode( mutantIf1, mutantIf1.WithAdditionalAnnotations(new SyntaxAnnotation("MutationIf", "6")) ); var mutantIf2 = root.DescendantNodes().OfType <ConditionalExpressionSyntax>().First(); root = root.ReplaceNode( mutantIf2, mutantIf2.WithAdditionalAnnotations(new SyntaxAnnotation("MutationConditional", "7")) ); var annotatedSyntaxTree = root.SyntaxTree; var compiler = CSharpCompilation.Create("TestCompilation", syntaxTrees: new Collection <SyntaxTree>() { annotatedSyntaxTree }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), references: new List <PortableExecutableReference>() { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Environment).Assembly.Location) }); var target = new RollbackProcess(); using (var ms = new MemoryStream()) { var compileResult = compiler.Emit(ms); var fixedCompilation = target.Start(compiler, compileResult.Diagnostics); var rollbackedResult = fixedCompilation.Compilation.Emit(ms); rollbackedResult.Success.ShouldBeTrue(); fixedCompilation.RollbackedIds.ShouldBe(new Collection <int> { 6, 7 }); } }
public void RollbackProcess_ShouldRollbackError_RollbackedCompilationShouldCompileWhenUriIsEmpty() { var syntaxTree = CSharpSyntaxTree.ParseText(@" using System; namespace ExampleProject { public class Query { public void Break() { if(System.Environment.GetEnvironmentVariable(""ActiveMutation"")==""1"") { string someQuery = ""test""; new Uri(new Uri(string.Empty), ""/API?"" - someQuery); } else { string someQuery = ""test""; new System.Uri(new System.Uri(string.Empty), ""/API?"" + someQuery); } } } }"); var ifStatement = syntaxTree.GetRoot() .DescendantNodes() .Where(x => x is IfStatementSyntax) .First(); var annotatedSyntaxTree = syntaxTree.GetRoot() .ReplaceNode( ifStatement, ifStatement.WithAdditionalAnnotations(new SyntaxAnnotation("MutationIf", "1")) ).SyntaxTree; var compiler = CSharpCompilation.Create("TestCompilation", syntaxTrees: new Collection <SyntaxTree>() { annotatedSyntaxTree }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), references: new List <PortableExecutableReference>() { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Environment).Assembly.Location), MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location), }); var target = new RollbackProcess(); using (var ms = new MemoryStream()) { var compileResult = compiler.Emit(ms); var fixedCompilation = target.Start(compiler, compileResult.Diagnostics); var rollbackedResult = fixedCompilation.Compilation.Emit(ms); rollbackedResult.Success.ShouldBeTrue(); // validate that only one of the compile errors marked the mutation as rollbacked. fixedCompilation.RollbackedIds.ShouldBe(new Collection <int> { 1 }); } }
protected static Compilation CreateCompilation(string source, params MetadataReference[] metadataReferences) => CSharpCompilation.Create("compilation", new[] { CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Preview)) }, metadataReferences.Concat(new[]
private void saCompile_Execute(object sender, SimpleActionExecuteEventArgs e) { var CurrentCode = (Script)e.CurrentObject; SyntaxTree syntaxTree; if (CurrentCode.Language == ScriptLanguage.CSharp) { syntaxTree = CSharpSyntaxTree.ParseText(CurrentCode.ScriptCode); } else { syntaxTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(CurrentCode.ScriptCode); } string assemblyName = Path.GetRandomFileName(); List <MetadataReference> Ref = new List <MetadataReference>(); Script CurrentScript = (Script)e.CurrentObject; foreach (ScriptAssemblyReference item in CurrentScript.ScriptAssemblyReferences) { Ref.Add(MetadataReference.CreateFromFile(item.AssemblyPath)); } CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: Ref, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { CompilationResult(CurrentCode, result); MessageOptions options = new MessageOptions(); options.Duration = 5000; options.Message = string.Format("There are compilation errors, please check the compilation result"); options.Type = InformationType.Error; options.Web.Position = InformationPosition.Bottom; options.Win.Caption = "Error"; options.Win.Type = WinMessageType.Flyout; Application.ShowViewStrategy.ShowMessage(options); } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); if (CurrentScript.Assembly == null) { CurrentScript.Assembly = this.View.ObjectSpace.CreateObject <FileData>(); } ms.Seek(0, SeekOrigin.Begin); CurrentScript.Assembly.LoadFromStream(assemblyName, ms); if (this.View.ObjectSpace.IsModified) { this.View.ObjectSpace.CommitChanges(); } MessageOptions options = new MessageOptions(); options.Duration = 5000; options.Message = string.Format("Compilation is completed!"); options.Type = InformationType.Success; options.Web.Position = InformationPosition.Top; options.Win.Caption = "Success"; options.Win.Type = WinMessageType.Flyout; Application.ShowViewStrategy.ShowMessage(options); //ExecuteAssemblyCode(assembly); } } }
public void Recursive() { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace RoslynSandbox { public class Foo { private Bar bar1; private Bar bar2; public Bar Bar1 { get { return this.bar1; } set { if (Equals(value, this.bar1)) { return; } if (value != null && this.bar2 != null) { this.Bar2 = null; } if (this.bar1 != null) { this.bar1.Selected = false; } this.bar1 = value; if (this.bar1 != null) { this.bar1.Selected = true; } } } public Bar Bar2 { get { return this.bar2; } set { if (Equals(value, this.bar2)) { return; } if (value != null && this.bar1 != null) { this.Bar1 = null; } if (this.bar2 != null) { this.bar2.Selected = false; } this.bar2 = value; if (this.bar2 != null) { this.bar2.Selected = true; } } } } public class Bar { public bool Selected { get; set; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes()); var semanticModel = compilation.GetSemanticModel(syntaxTree); var fieldDeclaration = syntaxTree.FindFieldDeclaration("bar1"); var field = semanticModel.GetDeclaredSymbolSafe(fieldDeclaration, CancellationToken.None); using (var assignedValues = AssignedValueWalker.Borrow(field, semanticModel, CancellationToken.None)) { var actual = string.Join(", ", assignedValues); Assert.AreEqual("null, value", actual); } }
private void TestAction_Execute(object sender, SimpleActionExecuteEventArgs e) { var CurrentCode = (Script)e.CurrentObject; #region SampleCode string SampleText = @" using System; namespace RoslynCompileSample { public class Writer { public void Write(string message) { Console.WriteLine(message); } } }"; #endregion SampleCode //SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(SampleText); SyntaxTree syntaxTree; if (CurrentCode.Language == ScriptLanguage.CSharp) { syntaxTree = CSharpSyntaxTree.ParseText(CurrentCode.ScriptCode); } else { syntaxTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(CurrentCode.ScriptCode); } string assemblyName = Path.GetRandomFileName(); List <MetadataReference> Ref = new List <MetadataReference>(); Script CurrentScript = (Script)e.CurrentObject; foreach (ScriptAssemblyReference item in CurrentScript.ScriptAssemblyReferences) { Ref.Add(MetadataReference.CreateFromFile(item.AssemblyPath)); } CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: Ref, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { CompilationResult(CurrentCode, result); } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); if (CurrentScript.Assembly == null) { CurrentScript.Assembly = this.View.ObjectSpace.CreateObject <FileData>(); } ms.Seek(0, SeekOrigin.Begin); CurrentScript.Assembly.LoadFromStream(assemblyName, ms); if (this.View.ObjectSpace.IsModified) { this.View.ObjectSpace.CommitChanges(); } //ExecuteAssemblyCode(assembly); } } }
private void Compile(string executableName, string blockKey, string codeBlock, bool cache) { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeBlock); CSharpCompilationOptions compilerOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); List<MetadataReference> references = new List<MetadataReference>(); Assembly[] currentDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in currentDomainAssemblies) { if (assembly.IsDynamic || string.IsNullOrEmpty(assembly.Location) || !File.Exists(assembly.Location)) continue; if (assembly.Location.IndexOf(Loader.Current.Path) > -1) continue; references.Add( MetadataReference.CreateFromFile(assembly.Location)); } CSharpCompilation compiler = CSharpCompilation.Create( executableName, options: compilerOptions, syntaxTrees: new List<SyntaxTree> { syntaxTree }, references: references ); Stream assemblyFS = null; try { assemblyFS = new FileStream( Path.Combine(Loader.Current.Path, string.Format("{0}.dll", executableName)), FileMode.Create, FileAccess.ReadWrite ); EmitResult eR = compiler.Emit(assemblyFS); if (!eR.Success) { System.Text.StringBuilder sB = new System.Text.StringBuilder(); foreach (Diagnostic diag in eR.Diagnostics) sB.AppendLine(diag.ToString()); throw new System.Exception(sB.ToString()); } } catch (System.Exception ex) { throw ex; } finally { if (assemblyFS != null) assemblyFS.Close(); } if (cache) this._StatementExecutables.TryAdd(blockKey, executableName); }
// 根据生成的类,动态编译把json转成protobuf private static void ExportExcelProtobuf(ConfigType configType) { string classPath = string.Format(classDir, configType); List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); List <string> protoNames = new List <string>(); foreach (string classFile in Directory.GetFiles(classPath, "*.cs")) { protoNames.Add(Path.GetFileNameWithoutExtension(classFile)); syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(classFile))); } List <PortableExecutableReference> references = new List <PortableExecutableReference>(); string assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); references.Add(AssemblyMetadata.CreateFromFile(typeof(object).Assembly.Location).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(typeof(ProtoMemberAttribute).Assembly.Location).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(typeof(BsonDefaultValueAttribute).Assembly.Location).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(typeof(IConfig).Assembly.Location).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(typeof(Attribute).Assembly.Location).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(Path.Combine(assemblyPath, "System.dll")).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(Path.Combine(assemblyPath, "netstandard.dll")).GetReference()); references.Add(AssemblyMetadata.CreateFromFile(typeof(ISupportInitialize).Assembly.Location).GetReference()); CSharpCompilation compilation = CSharpCompilation.Create( null, syntaxTrees.ToArray(), references.ToArray(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using MemoryStream memSteam = new MemoryStream(); EmitResult emitResult = compilation.Emit(memSteam); if (!emitResult.Success) { StringBuilder stringBuilder = new StringBuilder(); foreach (Diagnostic t in emitResult.Diagnostics) { stringBuilder.AppendLine(t.GetMessage()); } throw new Exception($"动态编译失败:\n{stringBuilder}"); } memSteam.Seek(0, SeekOrigin.Begin); Assembly ass = Assembly.Load(memSteam.ToArray()); string dir = string.Format(protoDir, configType.ToString()); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (string protoName in protoNames) { Type type = ass.GetType($"ET.{protoName}Category"); Type subType = ass.GetType($"ET.{protoName}"); Serializer.NonGeneric.PrepareSerializer(type); Serializer.NonGeneric.PrepareSerializer(subType); string json = File.ReadAllText(Path.Combine(string.Format(jsonDir, configType), $"{protoName}.txt")); object deserialize = BsonSerializer.Deserialize(json, type); string path = Path.Combine(dir, $"{protoName}Category.bytes"); using FileStream file = File.Create(path); Serializer.Serialize(file, deserialize); } }
public string GetIl(string code) { var imports = new StringBuilder(); foreach (var import in Imports) { imports.AppendLine($"using {import};"); } string toExecute = $@" {imports} namespace Eval {{ public class Code {{ public object Main() {{ {code} }} }} }} "; var opts = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8).WithKind(SourceCodeKind.Regular); var scriptSyntaxTree = CSharpSyntaxTree.ParseText(toExecute, opts); var compOpts = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithOptimizationLevel(OptimizationLevel.Debug).WithAllowUnsafe(true).WithPlatform(Platform.AnyCpu); var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString(), options: compOpts, references: References).AddSyntaxTrees(scriptSyntaxTree); var sb = new StringBuilder(); using (var pdb = new MemoryStream()) using (var dll = new MemoryStream()) { var result = compilation.Emit(dll, pdb); if (!result.Success) { sb.AppendLine("Emit Failed"); sb.AppendLine(string.Join(Environment.NewLine, result.Diagnostics.Select(a => a.GetMessage()))); } else { dll.Seek(0, SeekOrigin.Begin); using (var module = ModuleDefinition.ReadModule(dll)) using (var writer = new StringWriter(sb)) { module.Name = compilation.AssemblyName; var plainOutput = new PlainTextOutput(writer); var rd = new ReflectionDisassembler(plainOutput, CancellationToken.None) { DetectControlStructure = true }; var ignoredMethods = new[] { ".ctor" }; var methods = module.Types.SelectMany(a => a.Methods).Where(a => !ignoredMethods.Contains(a.Name)); foreach (var method in methods) { rd.DisassembleMethod(method); plainOutput.WriteLine(); } } } var final = sb.ToString(); return(final); } }
public CompilationContext CompileProject( ICompilationProject project, ILibraryKey target, IEnumerable <IMetadataReference> incomingReferences, IEnumerable <ISourceReference> incomingSourceReferences, Func <IList <ResourceDescriptor> > resourcesResolver) { var path = project.ProjectDirectory; var name = project.Name.TrimStart('/'); var isMainAspect = string.IsNullOrEmpty(target.Aspect); var isPreprocessAspect = string.Equals(target.Aspect, "preprocess", StringComparison.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(target.Aspect)) { name += "!" + target.Aspect; } _watcher.WatchProject(path); _watcher.WatchFile(project.ProjectFilePath); if (_cacheContextAccessor.Current != null) { _cacheContextAccessor.Current.Monitor(new FileWriteTimeCacheDependency(project.ProjectFilePath)); if (isMainAspect) { // Monitor the trigger {projectName}_BuildOutputs var buildOutputsName = project.Name + "_BuildOutputs"; _cacheContextAccessor.Current.Monitor(_namedDependencyProvider.GetNamedDependency(buildOutputsName)); } _cacheContextAccessor.Current.Monitor(_namedDependencyProvider.GetNamedDependency(project.Name + "_Dependencies")); } var exportedReferences = incomingReferences.Select(ConvertMetadataReference); Logger.TraceInformation("[{0}]: Compiling '{1}'", GetType().Name, name); var sw = Stopwatch.StartNew(); var compilationSettings = project.GetCompilerOptions(target.TargetFramework, target.Configuration) .ToCompilationSettings(target.TargetFramework); var sourceFiles = Enumerable.Empty <String>(); if (isMainAspect) { sourceFiles = project.Files.SourceFiles; } else if (isPreprocessAspect) { sourceFiles = project.Files.PreprocessSourceFiles; } var parseOptions = new CSharpParseOptions(languageVersion: compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines); IList <SyntaxTree> trees = GetSyntaxTrees( project, sourceFiles, incomingSourceReferences, parseOptions, isMainAspect); var embeddedReferences = incomingReferences.OfType <IMetadataEmbeddedReference>() .ToDictionary(a => a.Name, ConvertMetadataReference); var references = new List <MetadataReference>(); references.AddRange(exportedReferences); var compilation = CSharpCompilation.Create( name, trees, references, compilationSettings.CompilationOptions); compilation = ApplyVersionInfo(compilation, project, parseOptions); var compilationContext = new CompilationContext( compilation, project, target.TargetFramework, target.Configuration, incomingReferences, () => resourcesResolver() .Select(res => new ResourceDescription( res.Name, res.StreamFactory, isPublic: true)) .ToList()); // Apply strong-name settings ApplyStrongNameSettings(compilationContext); if (isMainAspect && project.Files.PreprocessSourceFiles.Any()) { try { var modules = GetCompileModules(target).Modules; foreach (var m in modules) { compilationContext.Modules.Add(m); } } catch (Exception ex) { var compilationException = ex.InnerException as RoslynCompilationException; if (compilationException != null) { // Add diagnostics from the precompile step foreach (var diag in compilationException.Diagnostics) { compilationContext.Diagnostics.Add(diag); } Logger.TraceError("[{0}]: Failed loading meta assembly '{1}'", GetType().Name, name); } else { Logger.TraceError("[{0}]: Failed loading meta assembly '{1}':\n {2}", GetType().Name, name, ex); } } } if (compilationContext.Modules.Count > 0) { var precompSw = Stopwatch.StartNew(); foreach (var module in compilationContext.Modules) { module.BeforeCompile(compilationContext.BeforeCompileContext); } precompSw.Stop(); Logger.TraceInformation("[{0}]: Compile modules ran in in {1}ms", GetType().Name, precompSw.ElapsedMilliseconds); } sw.Stop(); Logger.TraceInformation("[{0}]: Compiled '{1}' in {2}ms", GetType().Name, name, sw.ElapsedMilliseconds); return(compilationContext); }
/// <summary> /// Generates and compiles an assembly for the provided grains. /// </summary> /// <param name="generatedSyntax"> /// The generated code. /// </param> /// <param name="assemblyName"> /// The name for the generated assembly. /// </param> /// <param name="emitDebugSymbols"> /// Whether or not to emit debug symbols for the generated assembly. /// </param> /// <returns> /// The raw assembly. /// </returns> /// <exception cref="CodeGenerationException"> /// An error occurred generating code. /// </exception> public static GeneratedAssembly CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName, bool emitDebugSymbols) { // Add the generated code attribute. var code = AddGeneratedCodeAttribute(generatedSyntax); // Reference everything which can be referenced. var assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location)) .Select(asm => MetadataReference.CreateFromFile(asm.Location)) .Cast <MetadataReference>() .ToArray(); var logger = LogManager.GetLogger("CodeGenerator"); // Generate the code. var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string source = null; if (logger.IsVerbose3) { source = GenerateSourceCode(code); // Compile the code and load the generated assembly. logger.LogWithoutBulkingAndTruncating( Severity.Verbose3, ErrorCode.CodeGenSourceGenerated, "Generating assembly {0} with source:\n{1}", assemblyName, source); } var compilation = CSharpCompilation.Create(assemblyName) .AddSyntaxTrees(code.SyntaxTree) .AddReferences(assemblies) .WithOptions(options); var outputStream = new MemoryStream(); var symbolStream = emitDebugSymbols ? new MemoryStream() : null; try { var compilationResult = compilation.Emit(outputStream, symbolStream); if (!compilationResult.Success) { source = source ?? GenerateSourceCode(code); var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString())); logger.Warn( ErrorCode.CodeGenCompilationFailed, "Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}", assemblyName, errors, source); throw new CodeGenerationException(errors); } logger.Verbose( ErrorCode.CodeGenCompilationSucceeded, "Compilation of assembly {0} succeeded.", assemblyName); return(new GeneratedAssembly { RawBytes = outputStream.ToArray(), DebugSymbolRawBytes = symbolStream?.ToArray() }); } finally { outputStream.Dispose(); symbolStream?.Dispose(); } }
/// <summary> /// Creates the service assembly for a service /// </summary> /// <param name="org">The Organization code for the service owner</param> /// <param name="service">The service code for the current service</param> /// <param name="outputLocation">The directory where the resulting assembly should be saved</param> /// <param name="loadAssemblyContext">Defines if assembly should be loaded in context</param> /// <returns>The assembly name</returns> public CodeCompilationResult CreateServiceAssembly(string org, string service, string outputLocation = null, bool loadAssemblyContext = true) { CodeCompilationResult compilationResult = new CodeCompilationResult() { CompileStarted = DateTime.Now }; string assemblykey = org + "_" + service; List <AltinnCoreFile> implementationFiles = _repository.GetImplementationFiles(org, service); DateTime lastChanged = new DateTime(2000, 01, 01); foreach (AltinnCoreFile file in implementationFiles) { if (file.LastChanged > lastChanged) { lastChanged = file.LastChanged; } } if (_assemblyNames.ContainsKey(assemblykey) && _assemblyNames[assemblykey].CompileStarted > lastChanged && string.IsNullOrWhiteSpace(outputLocation)) { compilationResult = _assemblyNames[assemblykey]; return(compilationResult); } SyntaxTree[] syntaxTrees = GetSyntaxTrees(org, service); List <MetadataReference> references = new List <MetadataReference>(); Assembly root = Assembly.GetEntryAssembly(); string assemblyName = Path.GetRandomFileName(); MetadataReferenceFeature referenceFeature = new MetadataReferenceFeature(); _partManager.PopulateFeature(referenceFeature); CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: syntaxTrees, references: referenceFeature.MetadataReferences, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var pdbMs = new MemoryStream()) using (var ms = new MemoryStream()) { EmitResult result; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); if (!string.IsNullOrEmpty(outputLocation)) { result = compilation.Emit(outputLocation + assemblyName + ".dll", outputLocation + assemblyName + ".pdb"); } else { result = compilation.Emit(ms, pdbMs); } stopWatch.Stop(); compilationResult.TimeUsed = stopWatch.Elapsed; compilationResult.CompilationInfo = new List <CompilationInfo>(); foreach (Diagnostic diag in result.Diagnostics) { // TODO: Decide how to handle this special CS1701 we get if (!diag.Id.Equals("CS1701")) { var compInfo = new CompilationInfo { Info = diag.GetMessage(), FilePath = diag.Location.SourceTree.FilePath, FileName = System.IO.Path.GetFileName(diag.Location.SourceTree.FilePath), Severity = diag.Severity.ToString(), Code = diag.Id, WarningLevel = diag.WarningLevel, LineNumber = diag.Location.GetLineSpan().StartLinePosition.Line + 1 }; if (diag.Severity.Equals(DiagnosticSeverity.Warning)) { compilationResult.Warnings++; } else if (diag.Severity.Equals(DiagnosticSeverity.Error)) { compilationResult.Errors++; } compilationResult.CompilationInfo.Add(compInfo); } } if (!result.Success) { LogEmitResult(result); } else { compilationResult.AssemblyName = compilation.AssemblyName; compilationResult.Succeeded = true; if (string.IsNullOrEmpty(outputLocation) && loadAssemblyContext) { ms.Seek(0, SeekOrigin.Begin); pdbMs.Seek(0, SeekOrigin.Begin); AssemblyLoadContext.Default.LoadFromStream(ms, pdbMs); ms.Seek(0, SeekOrigin.Begin); MetadataReference newReference = MetadataReference.CreateFromStream(ms); if (_roslynCompilation.ServiceReferences.ContainsKey(assemblykey)) { _roslynCompilation.ServiceReferences.Remove(assemblykey); } _roslynCompilation.ServiceReferences.Add(assemblykey, newReference); if (_assemblyNames.ContainsKey(assemblykey)) { _assemblyNames.Remove(assemblykey); } _assemblyNames.Add(assemblykey, compilationResult); } return(compilationResult); } } return(compilationResult); }
private void CompileSourceToAssembly(string source) { CSharpParseOptions parseOptions; if (IsCSharp(Language)) { switch (Language) { case Language.CSharpVersion1: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp1); break; case Language.CSharpVersion2: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp2); break; case Language.CSharpVersion3: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp3); break; case Language.CSharpVersion4: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp4); break; case Language.CSharpVersion5: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp5); break; case Language.CSharpVersion6: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6); break; case Language.CSharpVersion7: parseOptions = new CSharpParseOptions(LanguageVersion.CSharp7); break; case Language.CSharp: parseOptions = new CSharpParseOptions(); break; default: parseOptions = null; break; } } else { ErrorRecord errorRecord = new ErrorRecord( new Exception(String.Format(CultureInfo.CurrentCulture, AddTypeStrings.SpecialNetVersionRequired, Language.ToString(), string.Empty)), "LANGUAGE_NOT_SUPPORTED", ErrorCategory.InvalidArgument, Language); ThrowTerminatingError(errorRecord); parseOptions = null; } SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions); var references = s_defaultAssemblies.Value; if (ReferencedAssemblies.Length > 0) { var tempReferences = new List <PortableExecutableReference>(s_autoReferencedAssemblies.Value); foreach (string assembly in ReferencedAssemblies) { if (string.IsNullOrWhiteSpace(assembly)) { continue; } string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); // Ignore some specified reference assemblies string fileName = PathType.GetFileName(resolvedAssemblyPath); if (s_refAssemblyNamesToIgnore.Value.Contains(fileName)) { WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath)); continue; } tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath)); } references = tempReferences.ToArray(); } CSharpCompilation compilation = CSharpCompilation.Create( PathType.GetRandomFileName(), syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputAssemblyTypeToOutputKind(OutputType))); EmitResult emitResult; if (InMemory) { using (var ms = new MemoryStream()) { emitResult = compilation.Emit(ms); if (emitResult.Success) { ms.Flush(); ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); CheckTypesForDuplicates(assembly); if (PassThru) { WriteTypes(assembly); } } } } else { emitResult = compilation.Emit(outputAssembly); if (emitResult.Success) { if (PassThru) { Assembly assembly = Assembly.LoadFrom(outputAssembly); CheckTypesForDuplicates(assembly); WriteTypes(assembly); } } } if (emitResult.Diagnostics.Length > 0) { HandleCompilerErrors(GetErrors(emitResult.Diagnostics)); } }
private static CompilationResult CompileInternal(string originalName, string cSharpSafeName, MemberDeclarationSyntax @class, Dictionary <string, string> extentions = null) { var name = cSharpSafeName + "." + Guid.NewGuid() + IndexExtension; var @namespace = RoslynHelper.CreateNamespace(IndexNamespace) .WithMembers(SyntaxFactory.SingletonList(@class)); var res = GetUsingDirectiveAndSyntaxTreesAndRefrences(extentions); var compilationUnit = SyntaxFactory.CompilationUnit() .WithUsings(RoslynHelper.CreateUsings(res.UsingDirectiveSyntaxes)) .WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(@namespace)) .NormalizeWhitespace(); SyntaxNode formatedCompilationUnit; using (var workspace = new AdhocWorkspace()) { formatedCompilationUnit = Formatter.Format(compilationUnit, workspace); } string sourceFile = null; if (EnableDebugging) { sourceFile = Path.Combine(Path.GetTempPath(), name + ".cs"); File.WriteAllText(sourceFile, formatedCompilationUnit.ToFullString(), Encoding.UTF8); } var st = EnableDebugging ? SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourceFile), path: sourceFile, encoding: Encoding.UTF8) : SyntaxFactory.ParseSyntaxTree(formatedCompilationUnit.ToFullString()); res.SyntaxTrees.Add(st); var syntaxTrees = res.SyntaxTrees; var compilation = CSharpCompilation.Create( assemblyName: name + ".dll", syntaxTrees: syntaxTrees, references: res.References, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptimizationLevel(OptimizationLevel.Release) ); var code = formatedCompilationUnit.SyntaxTree.ToString(); var asm = new MemoryStream(); var pdb = EnableDebugging ? new MemoryStream() : null; var result = compilation.Emit(asm, pdb, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); if (result.Success == false) { IEnumerable <Diagnostic> failures = result.Diagnostics .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); var sb = new StringBuilder(); sb.AppendLine($"Failed to compile index {originalName}"); sb.AppendLine(); sb.AppendLine(code); sb.AppendLine(); foreach (var diagnostic in failures) { sb.AppendLine(diagnostic.ToString()); } throw new IndexCompilationException(sb.ToString()); } asm.Position = 0; Assembly assembly; if (EnableDebugging) { pdb.Position = 0; assembly = AssemblyLoadContext.Default.LoadFromStream(asm, pdb); } else { assembly = AssemblyLoadContext.Default.LoadFromStream(asm); } return(new CompilationResult { Code = code, Type = assembly.GetType($"{IndexNamespace}.{cSharpSafeName}") }); }
public void TestGetTypeByNameAndArity() { string source1 = @" namespace System { public class TestClass { } public class TestClass<T> { } } "; string source2 = @" namespace System { public class TestClass { } } "; var c1 = CSharpCompilation.Create("Test1", syntaxTrees: new[] { Parse(source1) }, references: new[] { TestReferences.NetFx.v4_0_21006.mscorlib }); Assert.Null(c1.GetTypeByMetadataName("DoesntExist")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2")); NamedTypeSymbol c1TestClass = c1.GetTypeByMetadataName("System.TestClass"); Assert.NotNull(c1TestClass); NamedTypeSymbol c1TestClassT = c1.GetTypeByMetadataName("System.TestClass`1"); Assert.NotNull(c1TestClassT); Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2")); var c2 = CSharpCompilation.Create("Test2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(source2) }, references: new MetadataReference[] { new CSharpCompilationReference(c1), TestReferences.NetFx.v4_0_21006.mscorlib }); NamedTypeSymbol c2TestClass = c2.GetTypeByMetadataName("System.TestClass"); Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly); var c3 = CSharpCompilation.Create("Test3", references: new MetadataReference[] { new CSharpCompilationReference(c2), TestReferences.NetFx.v4_0_21006.mscorlib }); NamedTypeSymbol c3TestClass = c3.GetTypeByMetadataName("System.TestClass"); Assert.NotSame(c2TestClass, c3TestClass); Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly)); Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1")); var c4 = CSharpCompilation.Create("Test4", references: new MetadataReference[] { new CSharpCompilationReference(c1), new CSharpCompilationReference(c2), TestReferences.NetFx.v4_0_21006.mscorlib }); NamedTypeSymbol c4TestClass = c4.GetTypeByMetadataName("System.TestClass"); Assert.Null(c4TestClass); Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1")); }
public void Run() { Write("Let's compile!"); string codeToCompile = @" using System; namespace RoslynCompileSample { public class Writer { public void Write(string message) { Console.WriteLine($""you said '{message}!'""); } } }"; Write("Parsing the code into the SyntaxTree"); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile); string assemblyName = Path.GetRandomFileName(); var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); List <MetadataReference> references = new List <MetadataReference>() { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location) }; references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll"))); references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Console.dll"))); references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))); Write("Compiling ..."); CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { Write("Compilation failed!"); IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } } else { Write("Compilation successful! Now instantiating and executing the code ..."); ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); var type = assembly.GetType("RoslynCompileSample.Writer"); var instance = assembly.CreateInstance("RoslynCompileSample.Writer"); var meth = type.GetMember("Write").First() as MethodInfo; meth.Invoke(instance, new [] { "joel" }); } } }
private void CompileTimeAndRuntimeAssemblies( ImmutableArray <MetadataReference> compileReferences, ImmutableArray <MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateEmptyCompilation(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create <MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(5, parameters.Length); var actualReturnType = parameters[0].Type; Assert.Equal(TypeKind.Class, actualReturnType.TypeKind); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); }
/// <summary> /// 编译dll /// </summary> /// <param name="rootpaths"></param> /// <param name="output"></param> static public bool BuildByRoslyn(string[] dlls, string[] codefiles, string output, bool isdebug = false, bool isUseDefine = false) { if (Application.platform == RuntimePlatform.OSXEditor) { for (int i = 0; i < dlls.Length; i++) { dlls[i] = dlls[i].Replace("\\", "/"); } for (int i = 0; i < codefiles.Length; i++) { codefiles[i] = codefiles[i].Replace("\\", "/"); } output = output.Replace("\\", "/"); } //添加语法树 //宏解析 var Symbols = defineList; List <Microsoft.CodeAnalysis.SyntaxTree> codes = new List <Microsoft.CodeAnalysis.SyntaxTree>(); CSharpParseOptions opa = null; if (isUseDefine) { opa = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: Symbols); } else { opa = new CSharpParseOptions(LanguageVersion.Latest); } foreach (var cs in codefiles) { //判断文件是否存在 if (!File.Exists(cs)) { continue; } // var content = File.ReadAllText(cs); var syntaxTree = CSharpSyntaxTree.ParseText(content, opa, cs, Encoding.UTF8); codes.Add(syntaxTree); } //添加dll List <MetadataReference> assemblies = new List <MetadataReference>(); foreach (var dll in dlls) { var metaref = MetadataReference.CreateFromFile(dll); if (metaref != null) { assemblies.Add(metaref); } } //创建目录 var dir = Path.GetDirectoryName(output); Directory.CreateDirectory(dir); //编译参数 CSharpCompilationOptions option = null; if (isdebug) { option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, warningLevel: 4, allowUnsafe: true); } else { option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, warningLevel: 4, allowUnsafe: true); } //创建编译器代理 var assemblyname = Path.GetFileNameWithoutExtension(output); var compilation = CSharpCompilation.Create(assemblyname, codes, assemblies, option); EmitResult result = null; if (!isdebug) { result = compilation.Emit(output); } else { var pdbPath = output + ".pdb"; var emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbPath); using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { result = compilation.Emit(dllStream, pdbStream, options: emitOptions); File.WriteAllBytes(output, dllStream.GetBuffer()); File.WriteAllBytes(pdbPath, pdbStream.GetBuffer()); } } // 编译失败,提示 if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (var diagnostic in failures) { Debug.LogError(diagnostic.ToString()); } } return(result.Success); }