/// <summary> /// Inspects the syntax tree and reports the comments starting with the expected prefixes. /// </summary> /// <param name="tree">Parsed syntax tree</param> /// <param name="rules">Rules of the inspection</param> /// <returns>List of comments starting with the given prefixes</returns> public static IEnumerable <Record> Inspect(SyntaxTree tree, Rules rules) { var root = (CompilationUnitSyntax)tree.GetRoot(); var irrelevantRecord = new Record("", "", 0, 0, Status.Ok); IEnumerable <Record> records = root.DescendantTrivia() // Beware: ToString() is an expensive operation on Syntax Nodes and // involves some complex logic and a string builder! // Hence we convert the trivia to string only at this single place. .Select((trivia) => (trivia, trivia.ToString())) .Select( ((SyntaxTrivia, string)t) => { var(trivia, triviaAsString) = t; var result = Text.Inspect(triviaAsString, rules); if (result == null) { return(irrelevantRecord); } var span = tree.GetLineSpan(trivia.Span); var position = span.StartLinePosition; var line = position.Line; var column = position.Character; return(new Record(result.Prefix, result.Suffix, line, column, result.Status)); })
private static CSharpSyntaxTree[] ParseCSharpSourceFiles(string[] sourceFiles, Action <string>?logger) { var syntaxTrees = new CSharpSyntaxTree[sourceFiles.Length]; for (var i = 0; i < sourceFiles.Length; i++) { var sourceFile = sourceFiles[i]; var sourceFileName = Path.GetFileName(sourceFile); logger?.Invoke($"Parsing file {sourceFileName}"); var sourceText = File.ReadAllText(sourceFile); var syntaxTree = CSharp.CSharpSyntaxTree.ParseText(sourceText, path: sourceFile, encoding: Encoding.UTF8); var hasErrors = false; foreach (var diagnostic in syntaxTree.GetDiagnostics()) { hasErrors = diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error; logger?.Invoke($"{diagnostic.Severity}: {diagnostic.GetMessage()} @ {diagnostic.Location}"); } if (hasErrors) { throw new Exception($"Syntax errors in {sourceFileName}"); } syntaxTrees[i] = syntaxTree; } return(syntaxTrees); }
public static void CreateAssemblyDefinition(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); System.Collections.Generic.IReadOnlyCollection < Microsoft.CodeAnalysis.MetadataReference> _references = new[] { Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.Reflection.Binder).Assembly.Location), Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.ValueTuple <>).Assembly.Location) }; bool enableOptimisations = true; Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions options = new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary, optimizationLevel: enableOptimisations ? Microsoft.CodeAnalysis.OptimizationLevel.Release : Microsoft.CodeAnalysis.OptimizationLevel.Debug, allowUnsafe: true ); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName: "InMemoryAssembly", options: options) .AddReferences(_references) .AddSyntaxTrees(syntaxTree); System.IO.MemoryStream stream = new System.IO.MemoryStream(); Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream); if (emitResult.Success) { stream.Seek(0, System.IO.SeekOrigin.Begin); // System.Reflection.Metadata.AssemblyDefinition assembly = System.Reflection.Metadata.AssemblyDefinition.ReadAssembly(stream); } }
private void ParseSource() { if (string.IsNullOrWhiteSpace(sourceCode)) { return; } syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); }
private bool NotExcluded(Microsoft.CodeAnalysis.SyntaxTree tree) { var rule = _excludingRules.ExcludeFiles.FirstOrDefault(r => new Regex(r).IsMatch(tree.FilePath)); if (rule != null) { _logger.Info($"{tree.FilePath} excluded because of the following rule: {rule}"); } return(rule == null); }
/// <summary> /// Inspects the syntax tree and reports the comments which seem to be dead code. /// </summary> /// <param name="tree">Parsed syntax tree</param> /// <returns>List of problematic comments</returns> public static IEnumerable <Suspect> Inspect(SyntaxTree tree) { IEnumerable <SuspectTrivia> suspectTrivias = InspectTrivias(tree); return(suspectTrivias.Select( (suspectTrivia) => { var span = tree.GetLineSpan(suspectTrivia.Trivia.Span); var position = span.StartLinePosition; return new Suspect(position.Line, position.Character, suspectTrivia.Cues); })); }
public static string CreateUniqueVariableName(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, string baseName) { var contextNode = syntaxTree.GetRoot(); var symbols = contextNode.DescendantNodes().OfType <MethodDeclarationSyntax>().Select(n => n.Identifier.ValueText).ToList(); symbols.AddRange(contextNode.DescendantNodes().OfType <LocalDeclarationStatementSyntax>().Select(n => n.Declaration.Variables.FirstOrDefault().Identifier.ValueText).ToList()); symbols.AddRange(contextNode.DescendantNodes().OfType <FieldDeclarationSyntax>().Select(n => n.Declaration.Variables.FirstOrDefault().Identifier.ValueText).ToList()); symbols.AddRange(contextNode.DescendantNodes().OfType <ParameterSyntax>().Select(n => n.Identifier.ValueText).ToList()); return(GenerateUniqueName(baseName, string.Empty, n => symbols.Where(x => x.Equals(n)).ToArray().Length == 0)); }
static List <CGFDocument> ProcessDocuments(CGFParserReporter reporter, List <Microsoft.CodeAnalysis.Document> documents, Microsoft.CodeAnalysis.Project project) { using (reporter.CreateContextScope(CGFParserReporterContext.Type.Project, project.FilePath)) { List <CGFDocument> documentsToProcess = new List <CGFDocument>(); foreach (Microsoft.CodeAnalysis.Document document in documents) { using (reporter.CreateContextScope(CGFParserReporterContext.Type.File, document.FilePath)) { List <CGFTypeSymbol> typesToProcess = new List <CGFTypeSymbol>(); Microsoft.CodeAnalysis.SemanticModel semanticModel = document.GetSemanticModelAsync().Result; Microsoft.CodeAnalysis.SyntaxTree syntaxTree = document.GetSyntaxTreeAsync().Result; IEnumerable <Microsoft.CodeAnalysis.SyntaxNode> syntaxNodes = syntaxTree.GetRoot().DescendantNodes().Where(n => (n as ClassDeclarationSyntax) != null || (n as EnumDeclarationSyntax) != null); foreach (Microsoft.CodeAnalysis.SyntaxNode node in syntaxNodes) { ClassDeclarationSyntax classSyntax = node as ClassDeclarationSyntax; if (classSyntax != null) { Microsoft.CodeAnalysis.INamedTypeSymbol typeSymbol = semanticModel.GetDeclaredSymbol(classSyntax); using (reporter.CreateContextScope(CGFParserReporterContext.Type.Type, typeSymbol.Name)) { CGFTypeSymbol cgfTypeSymbol = CGFTypeSymbol.Parse(reporter, typeSymbol); typesToProcess.Add(cgfTypeSymbol); } } else { EnumDeclarationSyntax enumSyntax = node as EnumDeclarationSyntax; Microsoft.CodeAnalysis.INamedTypeSymbol typeSymbol = semanticModel.GetDeclaredSymbol(enumSyntax); using (reporter.CreateContextScope(CGFParserReporterContext.Type.Type, typeSymbol.Name)) { CGFTypeSymbol cgfTypeSymbol = CGFTypeSymbol.Parse(reporter, typeSymbol); typesToProcess.Add(cgfTypeSymbol); } } } if (typesToProcess.Count > 0) { CGFDocument cgfDocument = CGFDocument.Parse(reporter, document, typesToProcess); documentsToProcess.Add(cgfDocument); } } } return(documentsToProcess); } }
public static string CreateUniqueVariableName(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, string baseName) { var contextNode = syntaxTree.GetRoot(); var symbols = contextNode.DescendantNodes().OfType <MethodDeclarationSyntax>().Select(n => n.Identifier.ValueText).ToList(); symbols.AddRange(contextNode.DescendantNodes().OfType <LocalDeclarationStatementSyntax>().Select(n => n.Declaration.Variables.FirstOrDefault().Identifier.ValueText).ToList()); symbols.AddRange(contextNode.DescendantNodes().OfType <FieldDeclarationSyntax>().Select(n => n.Declaration.Variables.FirstOrDefault().Identifier.ValueText).ToList()); symbols.AddRange(contextNode.DescendantNodes().OfType <ParameterSyntax>().Select(n => n.Identifier.ValueText).ToList()); var existingNames = new HashSet <string>(symbols); return(baseName.GetUniqueName(existingNames)); }
private static void UpdateCSFileCodes(Client client, SoftwareFile softwareFile, ref AppsClient.AppsResult result) { var softwareFileCodeDB = client.DB.GetCollection <SoftwareFileCode>("SoftwareFileCodes"); Microsoft.CodeAnalysis.SyntaxTree tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(softwareFile.Contents); var descendents = tree.GetRoot().DescendantNodes(); //.OfType<LiteralExpressionSyntax>(); foreach (var desc in descendents) { if (desc.GetType().Name == "MethodDeclarationSyntax") { var method = (MethodDeclarationSyntax)desc; var existingCodeList = softwareFile.SoftwareFileCodes.Where(sc => sc.Name == method.Identifier.Text); if (existingCodeList.Count() == 1) { var existingCode = existingCodeList.Single(); existingCode.CodeType = SoftwareFileCodeTypes.Method; existingCode.Contents = method.Body.ToFullString(); existingCode.Name = method.Identifier.Text; existingCode.SoftwareFileID = softwareFile.SoftwareFileID; softwareFileCodeDB.Upsert(existingCode); } else if (existingCodeList.Count() == 0) { var newCode = new SoftwareFileCode { CodeType = SoftwareFileCodeTypes.Method, Contents = method.Body != null?method.Body.ToFullString() : "", Name = method.Identifier.Text, SoftwareFileID = softwareFile.SoftwareFileID }; softwareFileCodeDB.Insert(newCode); softwareFile.SoftwareFileCodes.Add(newCode); } else { result.FailMessages.Add("More than one code found for " + method.Identifier.Text + " in file " + softwareFile.FullName); } } } }
public AppsResult Compile(string code) { var result = new AppsResult(); try { Microsoft.CodeAnalysis.SyntaxTree tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); var diags = tree.GetDiagnostics().ToList(); foreach (var diag in diags) { result.FailMessages.Add("(Start: " + diag.Location.SourceSpan.Start.ToString() + ", End: " + diag.Location.SourceSpan.End.ToString() + ") " + diag.Severity.ToString() + " " + diag.Descriptor.Id.ToString() + " " + diag.Descriptor.MessageFormat);; } result.Success = true; } catch (System.Exception ex) { new AppFlows.Publish.Compile.Exception(ex, ref result); } return(result); }
} // End Function EmitToArray // a utility method that creates Roslyn compilation // for the passed code. // The compilation references the collection of // passed "references" arguments plus // the mscore library (which is required for the basic // functionality). private static Microsoft.CodeAnalysis.CSharp.CSharpCompilation CreateCompilationWithMscorlib ( string assemblyOrModuleName, string code, Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions compilerOptions = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> references = null) { // create the syntax tree Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code, null, ""); // get the reference to mscore library Microsoft.CodeAnalysis.MetadataReference mscoreLibReference = Microsoft.CodeAnalysis.AssemblyMetadata .CreateFromFile(typeof(string).Assembly.Location) .GetReference(); // create the allReferences collection consisting of // mscore reference and all the references passed to the method System.Collections.Generic.IEnumerable< Microsoft.CodeAnalysis.MetadataReference> allReferences = new Microsoft.CodeAnalysis.MetadataReference[] {mscoreLibReference}; if (references != null) { allReferences = allReferences.Concat(references); } // create and return the compilation Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create ( assemblyOrModuleName, new[] {syntaxTree}, options: compilerOptions, references: allReferences ); return compilation; } // End Function CreateCompilationWithMscorlib
private static void CreateCsCompilation(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName, new[] { syntaxTree }, references, new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary) ); // byte[] compilationResult = compilation.EmitToArray(); // System.Reflection.Assembly.Load(compilationResult); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // _compilation = compilation; }
private static IEnumerable <SuspectTrivia> InspectTrivias(SyntaxTree tree) { var root = (CompilationUnitSyntax)tree.GetRoot(); var tracker = new OnOffTracker(); var relevantTrivias = root.DescendantTrivia() // Beware: ToString() is an expensive operation on Syntax Nodes and // involves some complex logic and a string builder! // Hence we convert the trivia to string only at this single place. .Select((trivia) => (trivia, trivia.ToString())) .Where( (t) => { var(_, triviaAsString) = t; tracker.Feed(triviaAsString); return(tracker.IsOn && TriviaIsComment(triviaAsString) && !ShouldSkipTrivia(triviaAsString)); }); foreach (var(trivia, triviaAsString) in relevantTrivias) { var span = tree.GetLineSpan(trivia.Span); var position = span.StartLinePosition; List <Cue>?cues = InspectComment(position.Line, position.Character, triviaAsString); if (cues != null) { yield return(new SuspectTrivia(trivia, cues)); } } }
internal static void ApplyNewTree(TextEditor editor, int startOffset, bool exact, TextSpan span, Microsoft.CodeAnalysis.SyntaxTree syntaxTree, Microsoft.CodeAnalysis.SyntaxTree newTree) { var caretOffset = editor.CaretOffset; var caretEndOffset = caretOffset; using (var undo = editor.OpenUndoGroup()) { int delta = 0; foreach (var change in newTree.GetChanges(syntaxTree)) { if (!exact && change.Span.Start >= caretOffset) { continue; } if (exact && !span.Contains(change.Span.Start)) { continue; } var newText = change.NewText; var length = change.Span.Length; var changeEnd = delta + change.Span.End - 1; if (changeEnd < editor.Length && changeEnd >= 0 && editor.GetCharAt(changeEnd) == '\r') { length--; } var replaceOffset = delta + change.Span.Start; editor.ReplaceText(replaceOffset, length, newText); delta = delta - length + newText.Length; if (change.Span.Start < caretOffset) { if (change.Span.End < caretOffset) { caretEndOffset += newText.Length - length; } else { caretEndOffset = replaceOffset; } } } } if (startOffset < caretOffset) { if (0 <= caretEndOffset && caretEndOffset < editor.Length) { editor.CaretOffset = caretEndOffset; } if (editor.CaretColumn == 1) { if (editor.CaretLine > 1 && editor.GetLine(editor.CaretLine - 1).Length == 0) { editor.CaretLine--; } editor.CaretColumn = editor.GetVirtualIndentationColumn(editor.CaretLine); } } }
private static bool IsFileExcludedFromAnalysis(StyleCopSettings settings, string settingsFolder, Microsoft.CodeAnalysis.SyntaxTree tree) { return((settings?.IsExcludedFile(tree.FilePath, settingsFolder)).GetValueOrDefault()); }
public AppsResult CreateAppSoftware(SoftwareTypes softwareType) { var result = new AppsResult(); try { //1. Create new app object //2. Create new software object //3. Create "Software" folder under appfolders/app //4. Create "ID" folder under "Software" //5. Run new command var newApp = new App(); var newSoftware = new Software(); var appsTable = _db.GetCollection <App>("Apps"); var softwaresTable = _db.GetCollection <Software>("Softwares"); appsTable.Upsert(newApp); //Creates primary id softwaresTable.Upsert(newSoftware); string appFoldersFolder = System.Environment.CurrentDirectory + "\\AppFolders"; if (System.IO.Directory.Exists(appFoldersFolder)) { System.IO.Directory.CreateDirectory(appFoldersFolder + "\\App" + newApp.AppID.ToString()); System.IO.Directory.CreateDirectory(appFoldersFolder + "\\App" + newApp.AppID.ToString() + "\\Software"); System.IO.Directory.CreateDirectory(appFoldersFolder + "\\App" + newApp.AppID.ToString() + "\\Software\\Software" + newSoftware.SoftwareID.ToString()); new AppFlows.Create(newApp.AppID, "Created all folders."); if (softwareType == SoftwareTypes.CoreWebService) { newApp.AppName = "CoreWebService" + newApp.AppID.ToString(); newApp.MachineName = System.Environment.MachineName; newApp.WorkingFolder = appFoldersFolder + "\\App" + newApp.AppID.ToString() + "\\Software\\Software" + newSoftware.SoftwareID.ToString(); newApp.SoftwareType = SoftwareTypes.CoreWebService; appsTable.Upsert(newApp); //Uniquely identifies in apps new AppFlows.Create(newApp.AppID, "Set app working folder."); //Command.Exec("", "cd", new Dictionary<string, string> { { "", newApp.WorkingFolder } }, newApp.WorkingFolder, ref result); //Create solution Command.Exec("dotnet", "new sln", new Dictionary <string, string> { { "-o", newApp.WorkingFolder } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Created solution."); //Create software Command.Exec("dotnet", "new", new Dictionary <string, string> { { "", "webapi" }, { "-o", "\"" + newApp.WorkingFolder + "\\" + newApp.AppName + "\"" }, { "-n", newApp.AppName } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Created app."); //Add project to solution Command.Exec("dotnet", "sln", new Dictionary <string, string> { { "add", newApp.AppName + "\\" + newApp.AppName + ".csproj" } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Added project to solution."); //Create test project Command.Exec("dotnet", "new", new Dictionary <string, string> { { "", "xunit" }, { "-o", "\"" + newApp.WorkingFolder + "\\" + newApp.AppName + ".Tests" + "\"" }, { "-n", newApp.AppName + ".Tests" } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Created test app."); //Add test app to solution Command.Exec("dotnet", "sln", new Dictionary <string, string> { { "add", newApp.WorkingFolder + "\\" + newApp.AppName + ".Tests" + "\\" + newApp.AppName + ".Tests.csproj" } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Added test app to solution."); //Add Brooksoft.Apps.Client nuget package string projFileName = newApp.AppName + ".csproj"; string projFilePath = newApp.WorkingFolder + "\\" + newApp.AppName + "\\" + projFileName; if (System.IO.File.Exists(projFilePath)) { Command.Exec("dotnet", "add", new Dictionary <string, string> { { "", newApp.AppName + "\\" + projFileName }, { "package", "Brooksoft.Apps.Client" } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Added apps nuget package."); newApp.ProjectFileFullName = projFilePath; newApp.ProjectFileExists = true; appsTable.Upsert(newApp); //Add Load string startupCSPath = newApp.WorkingFolder + "\\" + newApp.AppName + "\\Startup.cs"; string startupFile = System.IO.File.ReadAllText(startupCSPath); string start = startupFile.Substring(0, startupFile.Length - 22); string end = startupFile.Substring(startupFile.Length - 20); string inserted = "var appsClient = new AppsClient.AppsClientConfig();appsClient.Load(\"Software14\", Environment.MachineName, Environment.CurrentDirectory, Environment.Version, new List<string>(), new List<AppsClient.AppsCustomConfigItem>(), true, true, new Flows.AppFlow());"; string changed = start + inserted + end; new AppFlows.Create(newApp.AppID, "Added code to startup."); //Parse Microsoft.CodeAnalysis.SyntaxTree tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(changed); var diags = tree.GetDiagnostics().ToList(); foreach (var diag in diags) { result.FailMessages.Add("(Start: " + diag.Location.SourceSpan.Start.ToString() + ", End: " + diag.Location.SourceSpan.End.ToString() + ") " + diag.Severity.ToString() + " " + diag.Descriptor.Id.ToString() + " " + diag.Descriptor.MessageFormat);; } if (result.FailMessages.Count == 0) { System.IO.File.WriteAllText(startupCSPath, changed); result.SuccessMessages.Add("CS file updated."); new AppFlows.Create(newApp.AppID, "Written and parsed successfully!"); } else { result.FailMessages.Add("CS file did not update."); } //Run Command.Exec("dotnet", "run", new Dictionary <string, string> { { "", newApp.WorkingFolder + "\\" + newApp.AppName + "\\" + projFileName } }, newApp.WorkingFolder, ref result); new AppFlows.Create(newApp.AppID, "Started app."); result.Success = true; } else { new AppFlows.Create.Fail("Project file not found for add package: " + projFilePath, ref result); } } else { new AppFlows.Create.Fail("No software type found to create.", ref result); } } else { new AppFlows.Create.Fail("Apps folders folder not found.", ref result); } } catch (System.Exception ex) { new AppFlows.Create.Exception(ex, ref result); } return(result); }
} // End Sub CheckCompilationResult private static void CreateCompilation2(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, new[] { syntaxTree }, references, co ); // WTF !!! // byte[] compilationResult = compilation.EmitToArray(); // Load the resulting assembly into the domain. // System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(compilationResult); /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } }
private static void CreateCompilationMultiFile(string[] filenames) { string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.SyntaxTree[] syntaxTrees = new Microsoft.CodeAnalysis.SyntaxTree[filenames.Length]; Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions op = null; for (int i = 0; i < filenames.Length; ++i) { string fileContent = System.IO.File.ReadAllText(filenames[i], System.Text.Encoding.UTF8); syntaxTrees[i] = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText( fileContent , op , filenames[i] , System.Text.Encoding.UTF8 ); } Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, syntaxTrees, references, co ); // byte[] compilationResult = compilation.EmitToArray(); using (System.IO.MemoryStream dllStream = new System.IO.MemoryStream()) { using (System.IO.MemoryStream pdbStream = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(dllStream, pdbStream); if (!emitResult.Success) { CheckCompilationResult(emitResult); } // End if (!emitResult.Success) } // End Using pdbStream } // End Using dllStream /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // End Using ms }
public static DoctestsAndErrors Extract(SyntaxTree tree) { var doctests = new List <Doctest>(); var errors = new List <Error>(); // stack var stack = new Stack <NamespaceWip>(); // Push the Work-in-progress for the global namespace stack.Push(new NamespaceWip { Namespace = "", SpanEnd = tree.Length }); var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var node in NamespaceDeclsAndDocumentations(root)) { if (node.SpanStart >= stack.Peek().SpanEnd) { var wip = stack.Pop(); if (wip.Doctests.Count > 0) { doctests.AddRange(wip.Doctests); } } switch (node) { case Syntax.DocumentationCommentTriviaSyntax documentation: List <Pipeline.Code> codes = Pipeline.CodesFromDocumentation(documentation); List <Pipeline.DoctestWithoutNamespaceOrError> dtWoNsOrErrorList = codes.Select(Pipeline.SplitHeaderBody).ToList(); stack.Peek().Doctests.AddRange( dtWoNsOrErrorList .Where((dtOrErr) => dtOrErr.DoctestWithoutNamespace != null) .Select((dtOrErr) => new Doctest( stack.Peek().Namespace, dtOrErr.DoctestWithoutNamespace !.Usings, dtOrErr.DoctestWithoutNamespace !.Body, dtOrErr.DoctestWithoutNamespace !.Line, dtOrErr.DoctestWithoutNamespace !.Column))); errors.AddRange( dtWoNsOrErrorList .Where((dtOrErr) => dtOrErr.Error != null) .Select((dtOrErr) => dtOrErr.Error !)); break; case Syntax.NamespaceDeclarationSyntax namespaceDecl: string ns = (stack.Peek().Namespace == "") ? namespaceDecl.Name.ToString() : $"{stack.Peek().Namespace}.{namespaceDecl.Name.ToString()}"; stack.Push(new NamespaceWip { Namespace = ns, SpanEnd = namespaceDecl.Span.End }); break; default: continue; } } while (stack.Count != 0) { var wip = stack.Pop(); if (wip.Doctests.Count > 0) { doctests.AddRange(wip.Doctests); } } // Sort doctests by line and column doctests.Sort((doctest, otherDoctest) => { int ret = doctest.Line.CompareTo(otherDoctest.Line); if (ret == 0) { ret = doctest.Column.CompareTo(otherDoctest.Column); } return(ret); }); return(new DoctestsAndErrors(doctests, errors)); }
public void Apply(ref Microsoft.CodeAnalysis.SyntaxTree syntaxTree, CompilationOptions options) { syntaxTree = new InstrumentForInEditorDebugging().Visit(syntaxTree.GetRoot()).SyntaxTree; // TODO handle exceptions again: syntaxTree = new ExceptionHandlingInjection().Visit(syntaxTree.GetRoot()).SyntaxTree; }
internal static void ApplyNewTree(TextEditor editor, int startOffset, bool exact, TextSpan span, Microsoft.CodeAnalysis.SyntaxTree syntaxTree, Microsoft.CodeAnalysis.SyntaxTree newTree) { editor.ApplyTextChanges(newTree.GetChanges(syntaxTree)); }