private static string CreateCompilationErrorMessage([NotNull] EmitResult emitResult, [NotNull] SyntaxTree syntaxTree) { if (emitResult == null) { throw new ArgumentNullException(nameof(emitResult)); } if (syntaxTree == null) { throw new ArgumentNullException(nameof(syntaxTree)); } if (emitResult.Success) { throw new ArgumentException("EmitResult should contain failed compilation result.", nameof(emitResult)); } var message = new StringBuilder() .AppendLine("Compilation failed:"); foreach (var diagnostic in emitResult.Diagnostics.Where(item => item.Severity == DiagnosticSeverity.Error)) { message .Append(diagnostic.Id) .Append(": ") .AppendLine(diagnostic.GetMessage(CultureInfo.InvariantCulture)); } var code = Formatter.Format(syntaxTree.GetRoot(), new AdhocWorkspace()).ToString(); message.AppendLine() .AppendLine("Generated code:") .AppendLine() .AppendLine(code); return(message.ToString()); }
/// <summary> /// Save generated code as a string. /// </summary> /// <param name="cu">Generated code.</param> /// <returns>Generated code as a string.</returns> public string SaveCodeAsString(CompilationUnitSyntax cu) { if (cu == null) { throw new ArgumentNullException(nameof(cu)); } var workspace = CreateWorkspace(); var formattedCode = Formatter.Format(cu, workspace); return(formattedCode.ToFullString()); }
/// <summary> /// Save generated code to a file. /// </summary> /// <param name="cu">Generated code.</param> /// <param name="path">Full output path.</param> public void SaveCodeToFile(CompilationUnitSyntax cu, string path) { if (cu == null) { throw new ArgumentNullException(nameof(cu)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Value cannot be null or empty.", nameof(path)); } var workspace = CreateWorkspace(); var formattedCode = Formatter.Format(cu, workspace); using (var sourceWriter = new StreamWriter(path)) { formattedCode.WriteTo(sourceWriter); } }