### Install roslyn-language-server as a .NET tool Source: https://github.com/dotnet/roslyn/blob/main/src/LanguageServer/roslyn-language-server/README.md Installs the language server globally as a .NET tool with the --prerelease flag to get the latest prerelease version. Requires .NET 10.0 or later runtime. ```bash dotnet tool install --global roslyn-language-server --prerelease ``` -------------------------------- ### Complete Program.cs for binding expressions example Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/csharp-semantic.docx The full Program.cs file after adding all the steps. It parses a HelloWorld program, creates a compilation, gets the semantic model, binds the using directive name, and then binds the string literal to enumerate public methods of System.String. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SemanticsCS { class Program { static void Main(string[] args) { SyntaxTree tree = CSharpSyntaxTree.ParseText(@" using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( new MetadataFileReference( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); var model = compilation.GetSemanticModel(tree); var nameInfo = model.GetSymbolInfo(root.Usings[0].Name); var systemSymbol = (INamespaceSymbol)nameInfo.Symbol; foreach (var ns in systemSymbol.GetNamespaceMembers()) { Console.WriteLine(ns.Name); } var helloWorldString = root.DescendantNodes() .OfType() .First(); var literalInfo = model.GetTypeInfo(helloWorldString); var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type; Console.Clear(); foreach (var name in (from method in stringTypeSymbol.GetMembers() .OfType() where method.ReturnType.Equals(stringTypeSymbol) && method.DeclaredAccessibility == Accessibility.Public select method.Name).Distinct()) { Console.WriteLine(name); } } } } ``` -------------------------------- ### CI build summary with -cachestats:$BUILD_START Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Design/compiler-output-cache-experiment.md Record build start time, run a build with `-p:Features=use-global-cache`, then use the start timestamp to get a per-build cache summary. As long as no other builds run in parallel against the same cache, the result shows what the cache did during that build. ```shell # Record the start time BUILD_START=$(date -u +"%Y-%m-%dT%H:%M:%SZ") # Run the build (with cache enabled) dotnet build -p:Features=use-global-cache # Show what the cache did during this build VBCSCompiler -cachestats:$BUILD_START ``` -------------------------------- ### Example syntax trees (file1.cs, file2.cs, file3.cs) Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md Three C# files used as examples to illustrate how the predicate and transform behave with multiple syntax trees. ```csharp // file1.cs public class Class1 { public int Method1() => 0; } // file2.cs public class Class2 { public Class1 Method2() => null; } // file3.cs public class Class3 {} ``` -------------------------------- ### Install Microsoft.Net.Compilers.Toolset with nuget install Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Compiler Toolset NuPkgs.md Run this command to install the C# and VB compilers from the NuGet package. The comment indicates it installs both compilers. ```cmd > nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers ``` -------------------------------- ### Start replay with -w to get PID Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/Replay/README.md Starts the replay tool with the -w option to wait for a key press after starting the compiler server. The output shows the server process ID (48752) and pipe name, which are needed for attaching a profiler. ```cmd e:\code\roslyn\src\Tools\Replay> dotnet run --framework net10.0 --configuration Release e:\code\example\msbuild.binlog -w Binary Log: E:\code\example\msbuild.binlog Client Directory: E:\code\roslyn\artifacts\bin\Replay\Release\net10.0\ Output Directory: E:\code\roslyn\src\Tools\Replay\output Pipe Name: 0254ccf8-294e-4b8f-a606-70f105b9e4a1 Parallel: 6 Starting server Process Id: 48752 Press any key to continue ``` -------------------------------- ### Select usage example Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md Example showing how to use Select to extract paths from AdditionalTexts and then prefix them. ```csharp // get the additional text provider IncrementalValuesProvider additionalTexts = initContext.AdditionalTextsProvider; // apply a 1-to-1 transform on each text, which represents extracting the path IncrementalValuesProvider transformed = additionalTexts.Select(static (text, _) => text.Path); // transform each extracted path into something else IncrementalValuesProvider prefixTransform = transformed.Select(static (path, _) => "prefix_" + path); ``` -------------------------------- ### HelloWorldTest class with Setup and Test methods Source: https://github.com/dotnet/roslyn/blob/main/src/Test/Perf/readme.md Defines a PerfTest subclass that sets up paths in Setup and runs csc.exe in Test, then flushes the logger. The Test method is called once per iteration. ```cs class HelloWorldTest : PerfTest { public override void Setup() { _pathToHelloWorld = Path.Combine(MyWorkingDirectory, "HelloWorld.cs"); _pathToOutput = Path.Combine(TempDirectory, "HelloWorld.exe"); } public override void Test() { ShellOutVital(Path.Combine(MyBinaries(), "csc.exe"), _pathToHelloWorld + " /out:" + _pathToOutput, MyWorkingDirectory); _logger.Flush(); } ``` -------------------------------- ### Install mdv tool Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic Inputs.md Install the MetaData Viewer (mdv) tool from the dotnet/metadata-tools repository using the dotnet tool install command with the specified package source. ```bash dotnet tool install mdv -g --prerelease --add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json ``` -------------------------------- ### Example invocation with paths Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Razor/tools/HtmlCompletionDataGenerator/README.md Example invocation using the VS HTML Editor schema directory and the Razor output file path. ```powershell dotnet run -- "Q:\src\webtools\src\Languages\html\Editor\Schemas\SchemaFiles" "..\..\src\Microsoft.CodeAnalysis.Remote.Razor\Completion\Html\Generated\HtmlCompletionData.g.cs" ``` -------------------------------- ### Install locally built Microsoft.RoslynTools package Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/dotnet-roslyn-tools/Tool/README.md Installs the locally built package from artifacts/packages/Debug/NonShipping using a tool-path and the local feed. Replace with the actual version. ```console dotnet tool install Microsoft.RoslynTools \ --tool-path .tools \ --add-source artifacts/packages/Debug/NonShipping \ --version ``` -------------------------------- ### Parse source text and get root in Main Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/vb-syntax.docx Parses a hard-coded source string containing many Imports statements and gets the root CompilationUnitSyntax node. This is the starting point for the walker example. ```vb Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText("Imports Microsoft.VisualBasicImports SystemImports System.CollectionsImports Microsoft.Win32Imports System.LinqImports System.TextImports Microsoft.CodeAnalysisImports System.ComponentModelImports System.Runtime.CompilerServicesImports Microsoft.CodeAnalysis.VisualBasicNamespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End ModuleEnd Namespace") Dim root As CompilationUnitSyntax = tree.GetRoot() ``` -------------------------------- ### Open Visual Studio with startvs.cmd Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Opens Visual Studio with the Razor solution after setting required environment variables. Optionally specify `-chooseVS` to display a list of installed Visual Studio instances and prompt for selection; by default the newest recently installed instance is launched. ```ps1 .\startvs.cmd ``` -------------------------------- ### Parse C# source and get root node Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-C Parses C# source text into a SyntaxTree and gets the root CompilationUnitSyntax node. This is the starting point for manual tree traversal. ```C# SyntaxTree tree = CSharpSyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); ``` -------------------------------- ### Sample .ruleset file Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Rule Set Format.md Complete example of a .ruleset file. Shows the required root element with Name and ToolsVersion attributes, an Include element that pulls in another rule set with Action="Default", and two Rules elements that set actions for individual rules (CA1027, CA1309, CA2217, CA1401, CA2101). ```XML ``` -------------------------------- ### Get first member of root node Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-C Stores the first member of the root CompilationUnitSyntax node. In the example, this is the namespace declaration. ```C# var firstMember = root.Members[0]; ``` -------------------------------- ### nameof expression for ArgumentNullException Source: https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C Use nameof to get the string name of a program element, checked by the compiler. The example names the argument x. ```csharp if (x == null) throw new ArgumentNullException(nameof(x)); ``` -------------------------------- ### XmlExampleElement(SyntaxList) Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/Microsoft.CodeAnalysis.CSharp.txt Creates an XML example element with the specified content list. ```APIDOC ## XmlExampleElement(SyntaxList) ### Description Creates an XML example element with the specified content list. ### Method Factory method ### Signature `public static XmlExampleElementSyntax XmlExampleElement(SyntaxList content)` ### Parameters - **content** (SyntaxList) - Required - The content nodes of the example element. ### Returns - **XmlExampleElementSyntax** - The created XML example element syntax node. ``` -------------------------------- ### Complete Program.cs Transformation Example Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/csharp-syntax-transform.pdf The final state of the Program.cs file demonstrating the construction and replacement of syntax nodes. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ConstructionCS { class Program { static void Main(string[] args) { NameSyntax name = IdentifierName("System"); name = QualifiedName(name, IdentifierName("Collections")); name = QualifiedName(name, IdentifierName("Generic")); SyntaxTree tree = CSharpSyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } }"); ``` ```csharp var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); ``` ```csharp newUsing); } } } ``` -------------------------------- ### Bind Name with GetSymbolInfo (VB.NET) Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-VB-Semantic-Analysis.md Gets the first Imports clause, then uses SemanticModel.GetSymbolInfo to retrieve a SymbolInfo for the imported name. The Symbol property is null for expressions that don't refer to anything, and Symbol.Kind returns SymbolKind.Namespace for this example. ```VB.NET Dim firstImport As SimpleImportsClauseSyntax = root.Imports(0).ImportsClauses(0) Dim nameInfo = model.GetSymbolInfo(firstImport.Name) ``` -------------------------------- ### Query syntax over constrained type parameter error (C#) Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/CSharp/Compiler Breaking Changes - post VS2019.md Starting Visual Studio 2019 version 16.9, the compiler no longer allows query syntax over constrained type parameters. This example triggers error CS0119. ```C# using System; using System.Collections.Generic; class C { static void M() where T : C { var q = from x in T select x; // error CS0119: 'T' is a type parameter, which is not valid in the given context } static Func, IEnumerable> Select = null; } ``` -------------------------------- ### Build App.sln with msbuild Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/BuildBoss/README.md Builds App.sln with the Release configuration. This example demonstrates that when a solution includes only App.csproj but App.csproj references Util.csproj, both projects are built, but Util.csproj receives the default configuration value instead of Release. ```cmd msbuild /p:Configuration=Release App.sln ``` -------------------------------- ### Use tuples in C# with System.ValueTuple Source: https://github.com/dotnet/roslyn/blob/main/docs/features/tuples.md Shows how to use tuples in C# 7.0 after installing VS2017 and adding the System.ValueTuple NuGet package. The example defines a method that takes and returns a tuple, creates tuples with and without named fields, and accesses a field by name. ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` -------------------------------- ### XmlExampleElement(XmlNodeSyntax[]) Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/Microsoft.CodeAnalysis.CSharp.txt Creates an XML example element with the specified content nodes. ```APIDOC ## XmlExampleElement(XmlNodeSyntax[]) ### Description Creates an XML example element with the specified content nodes. ### Method Factory method ### Signature `public static XmlExampleElementSyntax XmlExampleElement(params XmlNodeSyntax[] content)` ### Parameters - **content** (XmlNodeSyntax[]) - Required - The content nodes of the example element. ### Returns - **XmlExampleElementSyntax** - The created XML example element syntax node. ``` -------------------------------- ### Parse and navigate a C# syntax tree with Roslyn Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/csharp-syntax.docx This snippet parses a Hello World program string into a SyntaxTree and uses property-based navigation to reach the Main method's parameter. It requires the Microsoft.CodeAnalysis.CSharp packages and is the starting point for the query methods example. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace GettingStartedCS { class Program { static void Main(string[] args) { SyntaxTree tree = CSharpSyntaxTree.ParseText(@"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var firstMember = root.Members[0]; var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember; var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0]; var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0]; var argsParameter = mainDeclaration.ParameterList.Parameters[0]; } } } ``` -------------------------------- ### Build on Windows with build.cmd Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Builds the entire project on the command line on Windows. Tests are not run by default; use the `-test` option to run tests in addition to building. ```ps1 .\build.cmd ``` -------------------------------- ### Nullable attribute mismatch in overrides (C#) Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/CSharp/Compiler Breaking Changes - post VS2019.md Starting Visual Studio 2019 version 16.5, the compiler checks usage of nullable flow annotation attributes in overrides or implementations. This example shows a derived method not honoring the nullability declaration from the base method. ```C# public class Base { [return: NotNull] public virtual T M() { ... } } public class Derived : Base { public override string? M() { ... } // Derived.M doesn't honor the nullability declaration made by Base.M with its [NotNull] attribute } ``` -------------------------------- ### Parse VB source text and get root node Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-VB-Syntax-Analysis Parses a hardcoded VB source string into a SyntaxTree and retrieves its root CompilationUnitSyntax node. The parsed source includes imports, a namespace, and a module with a Main method. This is the starting point for manual tree traversal. ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` -------------------------------- ### Simple file-based app example Source: https://github.com/dotnet/roslyn/blob/main/docs/features/file-based-programs-vscode.md A minimal file-based application that prints to the console. ```cs Console.WriteLine("Hello World!"); ``` -------------------------------- ### Use tuples in Visual Basic 15 with System.ValueTuple Source: https://github.com/dotnet/roslyn/blob/main/docs/features/tuples.md Shows how to use tuples in Visual Basic 15 after installing VS2017 and adding the System.ValueTuple NuGet package. The example defines a function that takes and returns a tuple, creates tuples with and without named fields, and accesses a field by name. ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` -------------------------------- ### List all benchmarks Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/perf/Microbenchmarks/readme.md Run without parameters to be offered a list of all benchmarks to choose from. ```bash dotnet run -c Release ``` -------------------------------- ### Create a C# Roslyn Console Application (Program.cs) Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/csharp-semantic.docx Replace the contents of Program.cs with this code to set up a syntax tree for a simple HelloWorld program. It includes the necessary using directives and creates a SyntaxTree from a string. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SemanticsCS { class Program { static void Main(string[] args) { SyntaxTree tree = CSharpSyntaxTree.ParseText(@"using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); } } } ``` -------------------------------- ### Complete Module1.vb for binding expressions Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/documents/vb-semantic.pdf Complete Module1.vb after following the example steps. It parses a VB source string, creates a compilation, gets the semantic model, binds the first import name, and then binds the string literal to enumerate public methods of System.String that return strings. Requires Option Strict Off and references to the Roslyn assemblies. ```VB Option Strict Off Module Module1 Sub Main() Dim tree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections.Generic Imports System.Text Namespace HelloWorld Class Class1 Shared Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Class End Namespace") Dim root As CompilationUnitSyntax = tree.GetRoot() Dim compilation As Compilation = VisualBasicCompilation.Create("HelloWorld"). AddReferences(New MetadataFileReference( GetType(Object).Assembly.Location)). AddSyntaxTrees(tree) Dim model = compilation.GetSemanticModel(tree) Dim firstImport As MembersImportsClauseSyntax = root.Imports(0).ImportsClauses(0) Dim nameInfo = model.GetSymbolInfo(firstImport.Name) Dim systemSymbol As INamespaceSymbol = nameInfo.Symbol For Each ns In systemSymbol.GetNamespaceMembers() Console.WriteLine(ns.Name) Next Dim helloWorldString = root.DescendantNodes(). OfType(Of LiteralExpressionSyntax)(). First() Dim literalInfo = model.GetTypeInfo(helloWorldString) Dim stringTypeSymbol As INamedTypeSymbol = literalInfo.Type Dim methodNames = From method In stringTypeSymbol.GetMembers(). OfType(Of IMethodSymbol)() Where method.ReturnType.Equals(stringTypeSymbol) AndAlso method.DeclaredAccessibility = Accessibility.Public Select method.Name Distinct ``` -------------------------------- ### Complete Program.cs with Roslyn binding example Source: https://github.com/dotnet/roslyn/wiki/docs/csharp-semantic.docx The full Program.cs file after following the steps, showing the complete program that parses a C# program, binds names and expressions, and prints public methods of System.String that return string. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SemanticsCS { class Program { static void Main(string[] args) { SyntaxTree tree = CSharpSyntaxTree.ParseText(@" using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( new MetadataFileReference( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); var model = compilation.GetSemanticModel(tree); var nameInfo = model.GetSymbolInfo(root.Usings[0].Name); var systemSymbol = (INamespaceSymbol)nameInfo.Symbol; foreach (var ns in systemSymbol.GetNamespaceMembers()) { Console.WriteLine(ns.Name); } var helloWorldString = root.DescendantNodes() .OfType() .First(); var literalInfo = model.GetTypeInfo(helloWorldString); var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type; Console.Clear(); foreach (var name in (from method in stringTypeSymbol.GetMembers() .OfType() where method.ReturnType.Equals(stringTypeSymbol) && method.DeclaredAccessibility == Accessibility.Public select method.Name).Distinct()) { Console.WriteLine(name); } } } } ``` -------------------------------- ### Install Microsoft.RoslynTools from Azure DevOps feed Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/dotnet-roslyn-tools/Tool/README.md Installs the latest published build of the Microsoft.RoslynTools tool using the dotnet tool install command with the --prerelease flag and the specified Azure DevOps NuGet feed. Add -g to install globally, which makes the tool available as roslyn-tools. ```console dotnet tool install Microsoft.RoslynTools --prerelease --add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json ``` -------------------------------- ### Execute Visitor in Main Source: https://github.com/dotnet/roslyn/wiki/docs/vb-syntax.docx Instantiate the collector, visit the tree, and print the results. ```vb         Dim visitor As New ImportsCollector()        visitor.Visit(root)         For Each statement In visitor.Imports            Console.WriteLine(statement)        Next ``` -------------------------------- ### Complete Program.cs for binding names and expressions Source: https://github.com/dotnet/roslyn/wiki/docs/csharp-semantic.pdf The complete Program.cs after the tutorial. It parses a HelloWorld program, creates a compilation, gets the semantic model, binds the using directive to the System namespace, prints namespace members, and finds the string literal. ```csharp @" using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( new MetadataFileReference( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); var model = compilation.GetSemanticModel(tree); var nameInfo = model.GetSymbolInfo(root.Usings[0].Name); var systemSymbol = (INamespaceSymbol)nameInfo.Symbol; foreach (var ns in systemSymbol.GetNamespaceMembers()) { Console.WriteLine(ns.Name); } var helloWorldString = root.DescendantNodes() .OfType() .First(); ``` -------------------------------- ### Parse VB source into syntax tree in Module1.vb Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-VB-Semantic-Analysis Replaces Module1.vb in a Stand-Alone Code Analysis Tool project. Parses a VB source string into a syntax tree and gets its root. Requires a project created from the 'Stand-Alone Code Analysis Tool' template and the .NET Compiler Platform SDK. The source text contains a complete HelloWorld namespace; Option Strict is set to Off to simplify examples. ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections.Generic Imports System.Text Namespace HelloWorld Class Class1 Shared Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Class End Namespace") Dim root As CompilationUnitSyntax = tree.GetRoot() End Sub End Module ``` -------------------------------- ### Example azure-pipelines.yml using templates-official jobs.yml with multiple outputs Source: https://github.com/dotnet/roslyn/blob/main/eng/common/template-guidance.md Shows a pipeline extending MicroBuild.1ES.Official.yml and using /eng/common/templates-official/jobs/jobs.yml@self. It configures templateContext.outputs to publish logs from the Build.ArtifactStagingDirectory, then runs a job that writes a file and copies build outputs to the artifact staging directory. Multiple outputs are only applicable when referencing templates-official. ```yaml # azure-pipelines.yml extends: template: azure-pipelines/MicroBuild.1ES.Official.yml@MicroBuildTemplate parameters: stages: - stage: build jobs: - template: /eng/common/templates-official/jobs/jobs.yml@self parameters: # 1ES makes use of outputs to reduce security task injection overhead templateContext: outputs: - output: pipelineArtifact displayName: 'Publish logs from source' continueOnError: true condition: always() targetPath: $(Build.ArtifactStagingDirectory)/artifacts/log artifactName: Logs jobs: - job: Windows steps: - script: echo "friendly neighborhood" > artifacts/marvel/spiderman.txt # copy build outputs to artifact staging directory for publishing - task: CopyFiles@2 displayName: Gather build output inputs: SourceFolder: '$(System.DefaultWorkingDirectory)/artifacts/marvel' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/marvel' ``` -------------------------------- ### Visual Basic Property with Get and Set Source: https://github.com/dotnet/roslyn/blob/main/src/RoslynSdk/Samples/CSharp/CSharpToVisualBasicConverter/CSharpToVisualBasicConverter.Test/TestFiles/AllConstructs.txt Shows a property with Get and Set accessors. ```Visual Basic Public Property P As String Get Return "A" End Get Set End Set End Property ``` -------------------------------- ### Complete Program.cs with transformation logic Source: https://github.com/dotnet/roslyn/wiki/docs/csharp-syntax-transform.docx The complete Program.cs file after following the walkthrough. It includes the Main method that creates a test compilation, iterates over syntax trees, applies the TypeInferenceRewriter, and writes changed trees back to disk, plus the CreateTestCompilation method that builds the compilation from source files and metadata references. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace TransformationCS { internal class Program { private static void Main() { Compilation test = CreateTestCompilation(); foreach (SyntaxTree sourceTree in test.SyntaxTrees) { SemanticModel model = test.GetSemanticModel(sourceTree); TypeInferenceRewriter rewriter = new TypeInferenceRewriter(model); SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot()); if (newSource != sourceTree.GetRoot()) { File.WriteAllText(sourceTree.FilePath, newSource.ToFullString()); } } } private static Compilation CreateTestCompilation() { SyntaxTree programTree = CSharpSyntaxTree.ParseFile(@"..\..\Program.cs"); SyntaxTree rewriterTree = CSharpSyntaxTree.ParseFile(@"..\..\TypeInferenceRewriter.cs"); SyntaxTree[] sourceTrees = { programTree, rewriterTree }; MetadataReference mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); MetadataReference codeAnalysis = new MetadataFileReference(typeof(SyntaxTree).Assembly.Location); MetadataReference csharpCodeAnalysis = new MetadataFileReference(typeof(CSharpSyntaxTree).Assembly.Location); MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis }; return CSharpCompilation.Create("TransformationCS", sourceTrees, references, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); } } } ``` -------------------------------- ### C# example: SelectMany with AdditionalTextsProvider Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md C# example showing how to use SelectMany on an IncrementalValuesProvider to flatten elements from additional files into individual items for generation. The example extracts each element from each additional file and then transforms the individual elements. ```csharp // get the additional text provider IncrementalValuesProvider additionalTexts = initContext.AdditionalTextsProvider; // extract each element from each additional file IncrementalValuesProvider elements = additionalTexts.SelectMany(static (text, _) => /*transform text into an array of MyElementType*/); // now the generator can consider the union of elements in all additional texts, without needing to consider multiple files IncrementalValuesProvider transformed = elements.Select(static (element, _) => /*transform the individual element*/); ``` -------------------------------- ### Print Hello World in C# Interactive Source: https://github.com/dotnet/roslyn/wiki/C Enter this in the C# Interactive window and press Enter to print 'Hello, World!' to the console. ```csharp > Console.Write("Hello, World!") ``` -------------------------------- ### Module1.vb with Main and CreateTestCompilation Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-VB-Syntax-Transformation The final Module1.vb file after following the walkthrough. It defines the Main entry point that iterates over syntax trees, applies the TypeInferenceRewriter, and writes changed files. Also includes the CreateTestCompilation function that builds the test compilation with the necessary references and options. ```VB.NET Option Strict Off Module Module1 Sub Main() Dim test As Compilation = CreateTestCompilation() For Each sourceTree As SyntaxTree In test.SyntaxTrees Dim model As SemanticModel = test.GetSemanticModel(sourceTree) Dim rewriter As New TypeInferenceRewriter(model) Dim newSource As SyntaxNode = rewriter.Visit(sourceTree.GetRoot()) If newSource IsNot sourceTree.GetRoot() Then File.WriteAllText(sourceTree.FilePath, newSource.ToFullString()) End If Next End Sub Private Function CreateTestCompilation() As Compilation Dim globalImports As String() = {"Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.VisualBasic", "Microsoft.CodeAnalysis.VisualBasic.Syntax"} Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication). WithGlobalImports(From s In globalImports Select GlobalImport.Parse(s)) Dim module1Tree As SyntaxTree = VisualBasicSyntaxTree.ParseText(File.ReadAllText("..\..\Module1.vb"),, "..\..\Module1.vb",) Dim rewriterTree As SyntaxTree = VisualBasicSyntaxTree.ParseText(File.ReadAllText( "..\..\TypeInferenceRewriter.vb"),, "..\..\TypeInferenceRewriter.vb",) Dim sourceTrees As SyntaxTree() = {module1Tree, rewriterTree} Dim mscorlib As MetadataReference = MetadataReference.CreateFromFile(GetType(Object).Assembly.Location) Dim codeAnalysis As MetadataReference = MetadataReference.CreateFromFile(GetType(SyntaxTree).Assembly.Location) Dim vbCodeAnalysis As MetadataReference = MetadataReference.CreateFromFile(GetType(VisualBasicSyntaxTree).Assembly.Location) Dim references As MetadataReference() = {mscorlib, codeAnalysis, vbCodeAnalysis} Return VisualBasicCompilation.Create("TransformationVB", sourceTrees, references, options) End Function End Module ``` -------------------------------- ### Debug.Assert failure log example Source: https://github.com/dotnet/roslyn/blob/main/docs/contributing/bootstrap-builds.md An example of a stack trace found in Build.Server.log when a Debug.Assert call fails during compilation. ```txt ID=VBCSCompiler TID=33: Debug.Assert failed with message: Fail: Stack Trace at Microsoft.CodeAnalysis.CommandLine.ExitingTraceListener.Exit(String originalMessage) at Microsoft.CodeAnalysis.CommandLine.ExitingTraceListener.WriteLine(String message) at System.Diagnostics.TraceInternal.Fail(String message) at System.Diagnostics.Debug.Assert(Boolean condition) at Microsoft.CodeAnalysis.GeneratorDriver..ctor(GeneratorDriverState state) at Microsoft.CodeAnalysis.CSharp.CSharpGeneratorDriver..ctor(GeneratorDriverState state) at Microsoft.CodeAnalysis.CSharp.CSharpGeneratorDriver.FromState(GeneratorDriverState state) at Microsoft.CodeAnalysis.GeneratorDriver.RunGeneratorsAndUpdateCompilation(Compilation compilation, Compilation& outputCompilation, ImmutableArray`1& diagnostics, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.CommonCompiler.RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray`1 generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray`1 additionalTexts, DiagnosticBag generatorDiagnostics) at Microsoft.CodeAnalysis.CommonCompiler.CompileAndEmit(TouchedFileLogger touchedFilesLogger, Compilation& compilation, ImmutableArray`1 analyzers, ImmutableArray`1 generators, ImmutableArray`1 additionalTextFiles, AnalyzerConfigSet analyzerConfigSet, ImmutableArray`1 sourceFileAnalyzerConfigOptions, ImmutableArray`1 embeddedTexts, DiagnosticBag diagnostics, CancellationToken cancellationToken, CancellationTokenSource& analyzerCts, AnalyzerDriver& analyzerDriver, Nullable`1& generatorTimingInfo) at Microsoft.CodeAnalysis.CommonCompiler.RunCore(TextWriter consoleOutput, ErrorLogger errorLogger, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.CommonCompiler.Run(TextWriter consoleOutput, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.CompilerServer.CompilerServerHost.RunCompilation(RunRequest& request, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.CompilerServer.CompilerServerHost.Microsoft.CodeAnalysis.CompilerServer.ICompilerServerHost.RunCompilation(RunRequest& request, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.CompilerServer.ClientConnectionHandler.<>c__DisplayClass8_0.b__1() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot) at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart(Object obj) ``` -------------------------------- ### Compiler Server Error Log Example Source: https://github.com/dotnet/roslyn/blob/main/docs/contributing/bootstrap-builds.md An example of an EndOfStreamException error log indicating a potential bug in the compiler server. ```text ID=MSBuild 60300 TID=3: Error Error: 'EndOfStreamException' 'Reached end of stream before end of read.' occurred during 'Reading response for d2c3aeac-bd8a-4251-bde0-2e11bbc57d13' Stack trace: at Microsoft.CodeAnalysis.CommandLine.BuildProtocolConstants.d__4.MoveNext() in C:\Users\jaredpar\code\wt\ros2\src\Compilers\Core\CommandLine\BuildProtocol.cs:line 641 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult() at Microsoft.CodeAnalysis.CommandLine.BuildResponse.d__5.MoveNext() in C:\Users\jaredpar\code\wt\ros2\src\Compilers\Core\CommandLine\BuildProtocol.cs:line 342 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at Microsoft.CodeAnalysis.CommandLine.BuildServerConnection.<g__tryRunRequestAsync|7_1>d.MoveNext() in C:\Users\jaredpar\code\wt\ros2\src\Compilers\Shared\BuildServerConnection.cs:line 288 ``` -------------------------------- ### Verify LSP configuration with /lsp show Source: https://github.com/dotnet/roslyn/blob/main/docs/roslyn-language-server-copilot-plugin.md Expected output from the /lsp show command in Copilot CLI, confirming that the C# language server is configured. The output lists the server under 'Plugin-configured servers' with the 'csharp' label and the source '[from dotnet]'. ```text Plugin-configured servers: • csharp: (.cs) [from dotnet] ``` -------------------------------- ### Examples of native integer type representations Source: https://github.com/dotnet/roslyn/blob/main/docs/features/NativeIntegerAttribute.md Examples showing how different type declarations are represented in metadata with optional NativeIntegerAttribute annotations. ```csharp System.IntPtr A; // System.IntPtr A nint B; // [NativeInteger] System.IntPtr B IEnumerable C // [NativeInteger] System.Collections.Generic.IEnumerable C (System.IntPtr, nint) D; // [NativeInteger(new[] { false, true })] System.ValueTuple D ``` -------------------------------- ### Run roslyn-language-server with stdio and autoLoadProjects Source: https://github.com/dotnet/roslyn/blob/main/src/LanguageServer/roslyn-language-server/README.md Launches the language server using standard I/O for communication and automatically discovers and loads projects based on workspace folders. This is an example of typical usage; the server is designed to be launched by editor clients. ```bash roslyn-language-server --stdio --autoLoadProjects ``` -------------------------------- ### Get TypeInfo for string literal Source: https://github.com/dotnet/roslyn/wiki/docs/csharp-semantic.pdf Gets the TypeInfo for the string literal expression. The Type property is not null and returns the INamedTypeSymbol for System.String. ```csharp var literalInfo = model.GetTypeInfo(helloWorldString); ``` -------------------------------- ### Restore and build the repository with restore.cmd Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Restores required tools and builds the entire repository once. Run this before opening Razor.slnx in Visual Studio or VS Code, and after pulling large sets of changes. You may need to set the execution policy with `Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser` and restart Visual Studio after SDK updates. ```ps1 .\restore.cmd ```