### Implement PerfTest Setup and Test Methods Source: https://github.com/dotnet/roslyn/blob/main/src/Test/Perf/readme.md This C# code defines the Setup and Test methods for a performance test. Setup initializes file paths, and Test executes the 'csc' compiler for a 'hello world' example. ```csharp 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(); } ``` -------------------------------- ### Profile with dotnet trace (Console 1) Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/Replay/README.md Start the Replay tool with the `-w` option to get the compiler server's PID. This console will display the PID and wait for user input to continue. ```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 ``` -------------------------------- ### PublicAPI.Shipped.txt example Source: https://github.com/dotnet/roslyn/blob/main/docs/Adding Optional Parameters in Public API.md Example entry in PublicAPI.Shipped.txt for a method with optional parameters. ```txt Example.O(string o1 = null, string o2 = null) -> void ``` -------------------------------- ### Install dotnet-agent-skills Plugin Source: https://github.com/dotnet/roslyn/blob/main/docs/roslyn-language-server-copilot-plugin.md Install the dotnet-agent-skills plugin from the marketplace to enable C# LSP features. Restart your agent after installation. ```bash /plugin install dotnet@dotnet-agent-skills ``` -------------------------------- ### Example: Registering Additional Files Output Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md This example demonstrates how to extract file paths from additional texts, collect them, and register a source output that prints these paths. ```csharp // get the additional text provider IncrementalValuesProvider additionalTexts = initContext.AdditionalTextsProvider; // apply a 1-to-1 transform on each text, extracting the path IncrementalValuesProvider transformed = additionalTexts.Select(static (text, _) => text.Path); // collect the paths into a batch IncrementalValueProvider> collected = transformed.Collect(); // take the file paths from the above batch and make some user visible syntax initContext.RegisterSourceOutput(collected, static (sourceProductionContext, filePaths) => { sourceProductionContext.AddSource("additionalFiles.cs", @" namespace Generated { public class AdditionalTextList { public static void PrintTexts() { System.Console.WriteLine(\"Additional Texts were: " + string.Join(", ", filePaths) + @" ""); } } }"); }); ``` -------------------------------- ### Install Dependencies and Launch Extension for Testing Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/InsertingRazorIntoVSCodeCSharp.md After updating the `package.json` file, run these commands to install necessary dependencies and launch the extension for local validation. This ensures your changes are correctly integrated and functional. ```bash npx gulp installDependencies ``` -------------------------------- ### Install Roslyn Language Server Tool Source: https://github.com/dotnet/roslyn/blob/main/docs/roslyn-language-server-copilot-plugin.md Manually install the roslyn-language-server tool globally using the .NET CLI. Use the --prerelease flag if needed. ```bash dotnet tool install -g roslyn-language-server --prerelease ``` -------------------------------- ### CI Build Cache Summary Workflow Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Design/compiler-output-cache-experiment.md Records the build start time, runs a build with cache enabled, and then uses -cachestats with the recorded start time to get a summary of cache activity during that specific 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 ``` -------------------------------- ### Complete C# Syntax Transformation Example Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-C A complete example demonstrating the creation of a name, parsing code, updating a using directive, and replacing the node in the syntax tree. ```C# 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 static 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;\nusing System.Collections;\nusing System.Linq;\nusing System.Text;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello, World!\");\n }\n }\n}"); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); } } } ``` -------------------------------- ### Full Program for Semantic Analysis Example Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-C A complete C# program demonstrating semantic analysis, including parsing code, creating a compilation, getting a semantic model, and analyzing string literals. ```C# 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( MetadataReference.CreateFromFile( 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); } } } } ``` -------------------------------- ### Full VB.NET Semantic Analysis Example Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-VB-Semantic-Analysis A complete example demonstrating parsing VB.NET code, creating a compilation, getting a semantic model, and analyzing imports and string literals. ```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() Dim compilation As Compilation = VisualBasicCompilation.Create("HelloWorld"). AddReferences(MetadataReference.CreateFromAssembly( GetType(Object).Assembly)). AddSyntaxTrees(tree) Dim model = compilation.GetSemanticModel(tree) Dim firstImport As SimpleImportsClauseSyntax = 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 Console.Clear() For Each name In methodNames Console.WriteLine(name) Next End Sub End Module ``` -------------------------------- ### Install Standalone roslyn-language-server Source: https://github.com/dotnet/roslyn/blob/main/docs/Glossary - C Installs the roslyn-language-server as a global .NET tool. This enables its use as a standalone process. ```bash dotnet tool install --global roslyn-language-server ``` -------------------------------- ### Complete C# Syntax Transformation Example Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C A comprehensive example demonstrating the creation of a qualified name, parsing code, updating a using directive, and replacing the node in the syntax tree. ```C# 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 static 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;\nusing System.Collections;\nusing System.Linq;\nusing System.Text;\n \nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello, World!\");\n }\n }\n}"); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); } } } ``` -------------------------------- ### Complete VB.NET Code Example for Syntax Transformation Source: https://github.com/dotnet/roslyn/wiki/Getting-Started-VB-Syntax-Transformation A complete example demonstrating parsing a code file, creating a new import clause, and replacing the old one in the syntax tree. This shows the full workflow of a transformation. ```VB.NET Option Strict Off Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory Module Module1 Sub Main() Dim name As NameSyntax = IdentifierName("System") name = QualifiedName(name, IdentifierName("Collections")) name = QualifiedName(name, IdentifierName("Generic")) Dim tree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Module1 Sub Main(args As String()) Console.WriteLine("Hello, World!") End Sub End Module End Namespace") Dim root As CompilationUnitSyntax = tree.GetRoot() Dim oldImportClause As SimpleImportsClauseSyntax = root.Imports(1).ImportsClauses(0) Dim newImportClause = oldImportClause.WithName(name) root = root.ReplaceNode(oldImportClause, newImportClause) End Sub End Module ``` -------------------------------- ### Install Metadata Viewer Tool Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic Inputs.md Install the `mdv` (MetaData Viewer) tool globally using the .NET CLI. This tool is used to generate metadata dumps for assembly comparison. ```bash dotnet tool install mdv -g --prerelease --add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json ``` -------------------------------- ### Conditional Compilation Start with #if Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentPreprocessorDirectiveTest/StartOfLine_04/TestComponent.ir.txt Use `#if` to conditionally include code blocks. This example shows the start of a conditional block that will be compiled if the 'true' condition is met. ```razor var x = #if true; ``` -------------------------------- ### Launch Roslyn Language Server with Standard I/O Source: https://github.com/dotnet/roslyn/blob/main/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/README.md Example command to launch the Roslyn Language Server using standard input/output for communication and enabling automatic project loading. ```bash roslyn-language-server --stdio --autoLoadProjects ``` -------------------------------- ### Corrected Preprocessor Directives at Line Start (Razor) Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/Compiler Breaking Changes - DotNet 9.md This example shows the corrected placement of preprocessor directives at the start of a line, which is now required in Razor files. ```razor @{ #if DEBUG /* This is allowed */ }
test
@{ #endif /* This is allowed */ } ``` -------------------------------- ### System.Array.GetLowerBound Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/System.Runtime.txt Gets the starting lower bound of the specified dimension of the Array. ```APIDOC ## System.Array.GetLowerBound ### Description Gets the starting lower bound of the specified dimension of the Array. ### Method int GetLowerBound(Array array, int dimension) ### Parameters - **array** (Array) - The array. - **dimension** (int) - A zero-based index that specifies the dimension for which to get the lower bound. ``` -------------------------------- ### Use Tuples in C# Quickstart Source: https://github.com/dotnet/roslyn/blob/main/docs/features/tuples.md Demonstrates basic tuple usage in C#, including passing tuples as parameters, returning them, and accessing elements by position or named fields. ```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); } } ``` -------------------------------- ### Example Syntax Trees Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md Illustrative syntax trees for file1.cs, file2.cs, and file3.cs to demonstrate cross-file dependencies and semantic analysis. ```csharp // file1.cs public class Class1 { public int Method1() => 0; } // file2.cs public class Class2 { public Class1 Method2() => null; } // file3.cs public class Class3 {} ``` -------------------------------- ### Sample .ruleset File Structure Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Rule Set Format.md Demonstrates a basic .ruleset file with included rules and specific rule actions. ```XML ``` -------------------------------- ### Conditional Compilation End with #endif Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentPreprocessorDirectiveTest/StartOfLine_04/TestComponent.ir.txt Use `#endif` to mark the end of a conditionally compiled code block. This example shows the closing of a block that was started with `#if`. ```razor x #endif; ``` -------------------------------- ### Use Tuples in Visual Basic Quickstart Source: https://github.com/dotnet/roslyn/blob/main/docs/features/tuples.md Illustrates basic tuple usage in Visual Basic, showing how to define, pass, and access tuple elements with or without named fields. ```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 ``` -------------------------------- ### Restrictions on Redundant Readonly Modifiers Source: https://github.com/dotnet/roslyn/blob/main/docs/features/readonly-instance-members.md Illustrates that redundant `readonly` modifiers are not permitted on properties. For example, a property cannot have both a `readonly get` accessor and a `readonly` modifier on the property itself. ```csharp public readonly int Prop1 { readonly get => 42; } // Not allowed public int Prop2 { readonly get => this._store["Prop2"]; readonly set => this._store["Prop2"]; } // Not allowed ``` -------------------------------- ### Unchecked Subtraction with Nullable SByte Operands Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedArithmeticBinaryOperators.txt Demonstrates unchecked subtraction between two nullable SByte operands, yielding a nullable SByte. This mirrors the previous example but with both parameters typed as nullable SByte from the start. ```C# Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Subtract( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ``` -------------------------------- ### Create Syntax Provider for Return Type Kind Source: https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md An example of creating a syntax provider that extracts the return type kind of method symbols. It uses a predicate to identify MethodDeclarationSyntax nodes and a transform to get the return type's kind. ```csharp // create a syntax provider that extracts the return type kind of method symbols var returnKinds = initContext.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is MethodDeclarationSyntax, static (n, _) => ((IMethodSymbol)n.SemanticModel.GetDeclaredSymbol(n.Node)).ReturnType.Kind); ``` -------------------------------- ### String Literal Initialization Examples Source: https://github.com/dotnet/roslyn/blob/main/docs/features/string-literals-data-section.md Demonstrates different ways to initialize byte arrays and string literals, showing how they might reuse the same data field when the 'data section' emit strategy is applied to string literals. ```cs ReadOnlySpan a = new byte[6] { 72, 101, 108, 108, 111, 46 }; ReadOnlySpan b = stackalloc byte[6] { 72, 101, 108, 108, 111, 46 }; ReadOnlySpan c = "Hello."u8; string d = "Hello."; // assuming this string literal is eligible for the `ldsfld` emit strategy ``` -------------------------------- ### Component Bind-Value and OnChanged with Matching Properties Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentCodeGenerationTest/BindToComponent_SpecifiesValueAndChangeEvent_WithMatchingProperties/TestComponent.ir.txt This example demonstrates a component setup where the 'bind-Value' attribute is used in conjunction with a matching 'Value' property and an 'OnChanged' event handler. This is a common pattern for implementing two-way data binding in Blazor components. ```cshtml ``` -------------------------------- ### Start Polling for Sync Status Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/TestFiles/FormattingLog/GameTracAdmin/InitialDocument.txt Starts a timer to periodically poll for the synchronization status. Ensures any existing polling timer is stopped before starting a new one. ```csharp private void StartPolling() { StopPolling(); ``` -------------------------------- ### Check .NET SDK Version Source: https://github.com/dotnet/roslyn/blob/main/docs/roslyn-language-server-copilot-plugin.md Verify that a compatible .NET SDK is installed by running 'dotnet --version'. This is crucial for project load compatibility. ```bash dotnet --version ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/README.md Execute all available benchmarks when no specific benchmark name is provided. This will present a list of benchmarks to choose from. Compile in Release mode and specify the target framework. ```cmd dotnet run -c Release -f net472 ``` -------------------------------- ### End Get Statement Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/Microsoft.CodeAnalysis.VisualBasic.txt Creates an End Get statement. ```APIDOC ## EndGetStatement ### Description Creates an End Get statement. ### Method `EndGetStatement()` ``` ```APIDOC ## EndGetStatement ### Description Creates an End Get statement with tokens. ### Method `EndGetStatement(SyntaxToken, SyntaxToken)` ### Parameters * `endKeyword` (SyntaxToken) - The End keyword token. * `getKeyword` (SyntaxToken) - The Get keyword token. ``` -------------------------------- ### Get Compilation Async Source: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt Asynchronously gets the compilation for the project. ```APIDOC ## GetCompilationAsync ### Description Asynchronously gets the compilation for the project. ### Method Signature `Microsoft.CodeAnalysis.Project.GetCompilationAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task` ### Parameters * **cancellationToken** (System.Threading.CancellationToken, optional) - A token to monitor for cancellation requests. ### Returns A task that represents the asynchronous operation. The task result contains the `Compilation` object for the project. ``` -------------------------------- ### Complete C# Code for Syntax Analysis Example Source: https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C This is the complete C# code for the 'GettingStartedCS' project, incorporating all the steps for parsing and traversing a syntax tree. Ensure all necessary using directives are included. ```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;\nusing System.Collections;\nusing System.Linq;\nusing System.Text;\n ``` -------------------------------- ### Execute 'Hello World' in C# Interactive Source: https://github.com/dotnet/roslyn/wiki/C The basic 'Hello World' program to start with in the C# Interactive window. ```csharp > Console.Write("Hello, World!") ``` -------------------------------- ### PublicAPI.Unshipped.txt example Source: https://github.com/dotnet/roslyn/blob/main/docs/Adding Optional Parameters in Public API.md Example entry in PublicAPI.Unshipped.txt after a change, indicating removal. ```txt *REMOVED*Example.O(string o1 = null, string o2 = null) -> void ``` -------------------------------- ### List Initialization with Element Initialization Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedCollectionInitializers.txt Demonstrates initializing a List of Strings with a single element using ElementInit. This pattern is used when adding items to a collection. ```VisualBasic List(Of String) ) { ElementInit( Void Add(System.String) Constant( World! type: System.String ) ) } type: System.Collections.Generic.List`1[System.String] ) ) } type: System.Collections.Generic.List`1[System.Collections.Generic.List`1[System.String]] ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Int32,System.String,System.Object] ) ``` -------------------------------- ### Razor Error: @ followed by < at Statement Start Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/legacyTest/TestFiles/ParserTests/CSharpErrorTest/OutputsErrorIfAtSignFollowedByLessThanSignAtStatementStart.diag.txt Illustrates the incorrect usage where '@' is followed by '<' at the start of a statement, leading to a parsing error. Use HTML start tags for markup switching. ```razor @if(isLoggedIn) {

Hello, @user!

} ``` -------------------------------- ### Member Initialization with Array and List Initializers Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedCollectionInitializers.txt Illustrates initializing a class member with nested array and list initializers. This complex example shows how to populate custom collections and arrays within a member initialization. ```VisualBasic Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Convert( MemberInit( NewExpression( New( Void .ctor()( ) type: Clazz ) ) bindings: MemberAssignment( member: Custom[] F expression: { NewArrayInit( ListInit( New( <.ctor>( ) type: Custom ) { ElementInit( Void Add(System.Object) Convert( NewArrayInit( Parameter( x type: System.Int32 ) type: System.Int32[] ) type: System.Object ) ) ElementInit( Void Add(System.String, System.Object) Convert( Parameter( x type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Convert( NewArrayInit( Constant( a type: System.String ) type: System.String[] ) type: System.Object ) ) } type: Custom ) ListInit( New( <.ctor>( ) type: Custom ) { ElementInit( Void Add(System.Object) Convert( NewArrayInit( Parameter( x type: System.Int32 ) type: System.Int32[] ) type: System.Object ) ) } type: Custom ) New( <.ctor>( ) type: Custom ) type: Custom[] ) } ) ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Int32,System.String,System.Object] ) ``` -------------------------------- ### SARIF Runs Section Example Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Error Log Format.md An example of the SARIF 'runs' section, which is the core entry in the error log. This example omits the detailed 'results', 'rules', and 'ruleConfigurationOverrides' for brevity, focusing on the overall structure. ```json "runs": [ { "results": [ ], "properties": { "analyzerExecutionTime": "x.xxx" }, "tool": { "driver": { "name": "Microsoft (R) Visual C# Compiler", "version": "4.4.0-dev ()", "dottedQuadFileVersion": "42.42.42.42", "semanticVersion": "42.42.42", "language": "en-US", "rules": [ ] } }, "invocations": [ { "executionSuccessful": true, "ruleConfigurationOverrides": [ ] } ], "columnKind": "utf16CodeUnits" } ] ``` -------------------------------- ### Get Dependent Version Async Source: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt Asynchronously gets the version of the project, considering all dependent projects. ```APIDOC ## GetDependentVersionAsync ### Description Asynchronously gets the version of the project, considering all dependent projects. ### Method Signature `Microsoft.CodeAnalysis.Project.GetDependentVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task` ### Parameters * **cancellationToken** (System.Threading.CancellationToken, optional) - A token to monitor for cancellation requests. ### Returns A task that represents the asynchronous operation. The task result contains the `VersionStamp` representing the version. ``` -------------------------------- ### Build the Razor Project (macOS/Linux) Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Build the entire Razor project from the command line on a macOS or Linux machine. ```bash ./build.sh ``` -------------------------------- ### Pre-Compilation Source Output Usage Example Source: https://github.com/dotnet/roslyn/blob/main/docs/features/pre-compilation-source-outputs.md Example demonstrating how to register a pre-compilation source output to process additional files and generate source code visible to the compilation. It also shows a subsequent regular phase that utilizes the pre-compiled source. ```csharp public void Initialize(IncrementalGeneratorInitializationContext context) { // Pre-compilation phase: read additional files and emit source // that will be visible to the compilation. var protoFiles = context.AdditionalTextsProvider .Where(f => f.Path.EndsWith(".proto")); context.RegisterPreCompilationSourceOutput(protoFiles, (ctx, file) => { var types = ParseProtoFile(file.GetText()!.ToString()); ctx.AddSource($"{file.Path}.g.cs", GenerateTypes(types)); }); // Regular phase: the compilation now contains the types generated above. context.RegisterSourceOutput(context.CompilationProvider, (ctx, compilation) => { var messageType = compilation.GetTypeByMetadataName("MyProto.MyMessage"); // messageType is non-null - it was generated in the pre-compilation phase ctx.AddSource("Serializers.g.cs", GenerateSerializer(messageType!)); }); } ``` -------------------------------- ### Loop Start Mapping Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentCodeGenerationTest/Legacy_3_1_WhiteSpace_InMarkupInFunctionsBlock/TestComponent.mappings.txt Maps the source location of the start of a loop within markup to its generated location. ```html for (var i = 0; i < 100; i++) { ``` -------------------------------- ### XML Example Element Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/PublicAPI.Shipped.txt Creates an XML element for an example, with content provided as a SyntaxList or an array of XmlNodeSyntax. ```APIDOC ## XmlExampleElement ### Description Creates an XML element suitable for examples. ### Method Signatures `Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.XmlExampleElement(content As Microsoft.CodeAnalysis.SyntaxList(Of Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlNodeSyntax)) -> Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax` `Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.XmlExampleElement(ParamArray content As Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlNodeSyntax()) -> Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax` ``` -------------------------------- ### Run Replay Tool Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/Replay/README.md Execute the Replay tool against a collected binary log. Specify the target framework and configuration. The tool replays compilation events and outputs results to a specified directory. ```cmd e:\code\roslyn\src\Tools\Replay> dotnet run --framework net472 --configuration Release e:\code\example\msbuild.binlog ``` -------------------------------- ### Install Scripting API NuGet Package Source: https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples Use this command to install the necessary NuGet package for C# scripting. ```powershell Install-Package Microsoft.CodeAnalysis.CSharp.Scripting ``` -------------------------------- ### NuGet Packaging of Resource Assemblies Source: https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Localizing Analyzers.md Example of how to structure the files in a NuGet package to include localized resource assemblies. The target path mirrors the build output structure. ```XML ... ``` -------------------------------- ### Get Dependent Semantic Version Async Source: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt Asynchronously gets the semantic version of the project, considering all dependent projects. ```APIDOC ## GetDependentSemanticVersionAsync ### Description Asynchronously gets the semantic version of the project, considering all dependent projects. ### Method Signature `Microsoft.CodeAnalysis.Project.GetDependentSemanticVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task` ### Parameters * **cancellationToken** (System.Threading.CancellationToken, optional) - A token to monitor for cancellation requests. ### Returns A task that represents the asynchronous operation. The task result contains the `VersionStamp` representing the semantic version. ``` -------------------------------- ### Cross-Platform Path Handling Source: https://github.com/dotnet/roslyn/blob/main/docs/infrastructure/port-tests-to-unix.md Illustrates creating cross-platform compatible paths using Path.Combine and a utility method for rooted paths. ```csharp // Cross-platform path handling var tempPath = Path.GetTempPath(); var path = Path.Combine(tempPath, "subdir", "file.txt"); var rootedPath = TestPathUtil.GetRootedPath("temp", "subdir", "file.txt"); ``` -------------------------------- ### Razor C# Using Directive Example Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/legacyTest/TestFiles/ParserTests/CSharpPreprocessorTest/ElseNotOnNewline.cspans.txt Example of a C# 'using' directive within a Razor code block. ```cshtml @{ @using System.Text var builder = new StringBuilder(); } ``` -------------------------------- ### List All Benchmarks Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/perf/Microbenchmarks/readme.md Run the benchmark executable without any parameters to display a list of all available benchmarks, allowing you to choose one to run. ```bash dotnet run -c Release ``` -------------------------------- ### Conditional Compilation Start - Razor Source: https://github.com/dotnet/roslyn/blob/main/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentPreprocessorDirectiveTest/StartOfLine_04/TestComponent.mappings.txt Use `#if` to conditionally include code blocks. This directive must appear at the start of a line. ```razor var x = #if true; ``` -------------------------------- ### Show LSP Configuration in Copilot CLI Source: https://github.com/dotnet/roslyn/blob/main/docs/roslyn-language-server-copilot-plugin.md Use the '/lsp show' command in Copilot CLI to verify that the C# language server is configured. ```bash Plugin-configured servers: • csharp: (.cs) [from dotnet] ``` -------------------------------- ### Build the Razor Project (Windows) Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Build the entire Razor project from the command line on a Windows machine. ```powershell .\build.cmd ``` -------------------------------- ### Get Accessor Block Creation Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/Microsoft.CodeAnalysis.VisualBasic.txt Provides overloads for creating a get accessor block, with or without statements and an end block statement. ```APIDOC ## GetAccessorBlock ### Description Creates a get accessor block. ### Method Signatures Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorBlock(Microsoft.CodeAnalysis.VisualBasic.Syntax.AccessorStatementSyntax) Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorBlock(Microsoft.CodeAnalysis.VisualBasic.Syntax.AccessorStatementSyntax,Microsoft.CodeAnalysis.SyntaxList{Microsoft.CodeAnalysis.VisualBasic.Syntax.StatementSyntax}) Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorBlock(Microsoft.CodeAnalysis.VisualBasic.Syntax.AccessorStatementSyntax,Microsoft.CodeAnalysis.SyntaxList{Microsoft.CodeAnalysis.VisualBasic.Syntax.StatementSyntax},Microsoft.CodeAnalysis.VisualBasic.Syntax.EndBlockStatementSyntax) ``` -------------------------------- ### VirtualCharSequence Structure Source: https://github.com/dotnet/roslyn/blob/main/docs/ide/api-designs/Virtual Character System.md Wraps a VirtualCharGreenSequence with a token start offset to provide position-aware VirtualChars. Supports slicing while maintaining the token start context. ```csharp internal readonly struct VirtualCharSequence { private readonly int _tokenStart; private readonly VirtualCharGreenSequence _sequence; public VirtualChar this[int index] => new(_sequence[index], _tokenStart); public VirtualCharSequence Slice(int start, int length) => new(_tokenStart, _sequence.Slice(start, length)); } ``` -------------------------------- ### Build Roslyn Solution Source: https://github.com/dotnet/roslyn/blob/main/AGENTS.md Use these commands to build the entire Roslyn solution on Windows or Unix-based systems. ```shell build.cmd # or build.sh ``` -------------------------------- ### Get Accessor Statement Creation Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/SemanticSearch/ReferenceAssemblies/Apis/Microsoft.CodeAnalysis.VisualBasic.txt Provides overloads for creating a get accessor statement with attributes, modifiers, an identifier token, and an optional parameter list. ```APIDOC ## GetAccessorStatement ### Description Creates a get accessor statement. ### Method Signatures Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorStatement Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorStatement(Microsoft.CodeAnalysis.SyntaxList{Microsoft.CodeAnalysis.VisualBasic.Syntax.AttributeListSyntax},Microsoft.CodeAnalysis.SyntaxTokenList,Microsoft.CodeAnalysis.SyntaxToken,Microsoft.CodeAnalysis.VisualBasic.Syntax.ParameterListSyntax) Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.GetAccessorStatement(Microsoft.CodeAnalysis.SyntaxList{Microsoft.CodeAnalysis.VisualBasic.Syntax.AttributeListSyntax},Microsoft.CodeAnalysis.SyntaxTokenList,Microsoft.CodeAnalysis.VisualBasic.Syntax.ParameterListSyntax) ``` -------------------------------- ### WithCompilationOptions Source: https://github.com/dotnet/roslyn/blob/main/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt Creates a new project with the specified compilation options. ```APIDOC ## WithCompilationOptions ### Description Creates a new project with the specified compilation options. ### Method Signature `Microsoft.CodeAnalysis.Project WithCompilationOptions(Microsoft.CodeAnalysis.CompilationOptions options)` ``` -------------------------------- ### Pattern-Based Asynchronous Disposal Example Source: https://github.com/dotnet/roslyn/blob/main/docs/features/enhanced-using.md Provides an example of pattern-based asynchronous disposal where a type implements a DisposeAsync method, allowing its use with await using. ```csharp public class C { public static async Task M() { await using (AsyncDisposer a = new AsyncDisposer()) { } } } public class AsyncDisposer { public async ValueTask DisposeAsync() => Console.WriteLine("DisposeAsync"); } ``` -------------------------------- ### VirtualCharGreen Examples Source: https://github.com/dotnet/roslyn/blob/main/docs/ide/api-designs/Virtual Character System.md Illustrates the creation of VirtualCharGreen instances for different scenarios, including regular characters, tab characters from escape sequences, and Unicode characters from escape sequences. Shows how offset and width are used. ```csharp // Regular character 'a' in "abc" new VirtualCharGreen('a', offset: ..., width: 1) ``` ```csharp // Tab character from "\t" escape new VirtualCharGreen('\t', offset: ..., width: 2) ``` ```csharp // 'A' from Unicode escape "\u0041" new VirtualCharGreen('A', offset: ..., width: 6) ``` -------------------------------- ### Existing Platform Check Utility Source: https://github.com/dotnet/roslyn/blob/main/docs/infrastructure/port-tests-to-unix.md Provides an example of using an existing utility method for checking if the current OS is Windows. ```csharp // Existing utility ExecutionConditionUtil.IsWindows ``` -------------------------------- ### Get Help with #help Directive Source: https://github.com/dotnet/roslyn/wiki/Interactive-Window Use the #help directive to view all variable commands and key bindings. Provide an argument to get help for a specific command. ```csharp #help ``` ```csharp #help clear ``` -------------------------------- ### VisualBasicCompilationOptions Constructor Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/PublicAPI.Shipped.txt Creates a new instance of VisualBasicCompilationOptions with specified settings. ```APIDOC ## Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions.New ### Description Initializes a new instance of the VisualBasicCompilationOptions class. ### Parameters - **outputKind** (Microsoft.CodeAnalysis.OutputKind) - The kind of output to generate. - **reportSuppressedDiagnostics** (Boolean) - Whether to report suppressed diagnostics. - **moduleName** (String) - Optional name of the module. - **mainTypeName** (String) - Optional name of the main type. - **scriptClassName** (String) - Optional name of the script class, defaults to "Script". - **globalImports** (System.Collections.Generic.IEnumerable) - Optional global imports. - **rootNamespace** (String) - Optional root namespace. - **optionStrict** (Microsoft.CodeAnalysis.VisualBasic.OptionStrict) - The Option Strict setting, defaults to Off. - **optionInfer** (Boolean) - Whether Option Infer is enabled, defaults to True. - **optionExplicit** (Boolean) - Whether Option Explicit is enabled, defaults to True. - **optionCompareText** (Boolean) - Whether Option Compare Text is enabled, defaults to False. - **parseOptions** (Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions) - Optional parse options. - **embedVbCoreRuntime** (Boolean) - Whether to embed the VB Core runtime, defaults to False. - **optimizationLevel** (Microsoft.CodeAnalysis.OptimizationLevel) - The optimization level, defaults to Debug. - **checkOverflow** (Boolean) - Whether to check for overflow, defaults to True. - **cryptoKeyContainer** (String) - Optional crypto key container name. - **cryptoKeyFile** (String) - Optional crypto key file path. - **cryptoPublicKey** (System.Collections.Immutable.ImmutableArray) - Optional crypto public key. - **delaySign** (Boolean?) - Optional value indicating whether to delay signing. - **platform** (Microsoft.CodeAnalysis.Platform) - The target platform, defaults to AnyCpu. - **generalDiagnosticOption** (Microsoft.CodeAnalysis.ReportDiagnostic) - The general diagnostic option, defaults to Default. - **specificDiagnosticOptions** (System.Collections.Generic.IEnumerable>) - Optional specific diagnostic options. - **concurrentBuild** (Boolean) - Whether concurrent build is enabled, defaults to True. - **deterministic** (Boolean) - Whether the build is deterministic, defaults to False. - **xmlReferenceResolver** (Microsoft.CodeAnalysis.XmlReferenceResolver) - Optional XML reference resolver. - **sourceReferenceResolver** (Microsoft.CodeAnalysis.SourceReferenceResolver) - Optional source reference resolver. - **metadataReferenceResolver** (Microsoft.CodeAnalysis.MetadataReferenceResolver) - Optional metadata reference resolver. - **assemblyIdentityComparer** (Microsoft.CodeAnalysis.AssemblyIdentityComparer) - Optional assembly identity comparer. - **strongNameProvider** (Microsoft.CodeAnalysis.StrongNameProvider) - Optional strong name provider. ### Returns Void ``` -------------------------------- ### Build and Deploy Roslyn Extensions Source: https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building, Debugging, and Testing on Windows.md Use this command to build and deploy Roslyn extensions. Ensure you are in the project root directory. ```batch .\Build.cmd -Restore -Configuration Release -deployExtensions -launch ``` -------------------------------- ### Install Microsoft.Net.Compilers.Toolset NuPkg Source: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Compiler Toolset NuPkgs.md Use this command to install the C# and VB compilers via NuGet. This package overrides the default MSBuild compiler with the version from the branch it was built in. ```cmd > nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers ``` -------------------------------- ### List Source: https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/PublicAPI.Shipped.txt Creates a SyntaxList. ```APIDOC ## List ### Description Creates a syntax list from a collection of nodes. ### Method Shared ### Signature Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.List(Of TNode)() -> Microsoft.CodeAnalysis.SyntaxList(Of TNode) Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.List(Of TNode)(nodes As System.Collections.Generic.IEnumerable(Of TNode)) -> Microsoft.CodeAnalysis.SyntaxList(Of TNode) ``` -------------------------------- ### Run BuildBoss Tool Source: https://github.com/dotnet/roslyn/blob/main/src/Tools/BuildBoss/README.md Execute the BuildBoss tool with paths to solution, project, or build log files for validation. ```cmd > BuildBoss.exe ``` -------------------------------- ### Preprocessor Directives Not at Line Start (Razor) Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/Compiler Breaking Changes - DotNet 9.md Preprocessor directives like #if must now start at the beginning of a line in Razor files, with only whitespace allowed before them. Previously, these could appear mid-line. ```razor @{ #if DEBUG /* Previously allowed, now triggers RZ1043 */ }
test
@{ #endif /* Previously allowed, now triggers RZ1043 */ } ``` -------------------------------- ### Restore Dependencies and Build Razor Source: https://github.com/dotnet/roslyn/blob/main/docs/razor/contributing/BuildFromSource.md Execute this command to download required tools and build the entire Razor repository. It's also recommended to run this after pulling significant changes. ```powershell .\restore.cmd ```